├── .eslintrc.json ├── .gitattributes ├── .npmignore ├── .travis.yml ├── AUTHORS.txt ├── CONTRIBUTING.md ├── Gruntfile.js ├── README.md ├── SECURITY.md ├── appveyor.yml ├── binding.gyp ├── build-scripts ├── build-csdk.js ├── generate-constants.js ├── generate-enums.js ├── generate-functions.js ├── helpers │ ├── header-paths.js │ └── repo-paths.js └── postinstall.js ├── grunt-build ├── js-build-files.js ├── js-example-files.js ├── js-lib-files.js ├── js-test-files.js └── tasks │ ├── alias.js │ ├── clangformat.js │ ├── options │ ├── clean.js │ ├── coveralls.js │ ├── esformatter.js │ ├── eslint.js │ ├── iot-js-api.js │ └── makeReport.js │ ├── testdist.js │ └── testsuite.js ├── index.js ├── js ├── README.md ├── client.delete.js ├── client.discovery.js ├── client.get.coaps.js ├── client.get.js ├── client.observe.js ├── client.presence-only.js ├── client.presence.js ├── envirophat │ ├── README.md │ ├── client.envirophat.ocf.js │ ├── enviro_phat.py │ └── server.envirophat.ocf.js ├── high-level-client.coaps.js ├── high-level-resource-creation-client.js ├── high-level-resource-creation-server.js ├── high-level-server.coaps.js ├── mock-sensor.js ├── multi-server-client.js ├── multi-server-server1.js ├── multi-server-server2.js ├── node_modules │ ├── README.md │ └── iotivity-node │ │ ├── index.js │ │ └── lowlevel.js ├── server.delete.js ├── server.discoverable.js ├── server.get.coaps.js ├── server.get.js ├── server.observable.js └── server.presence.js ├── lib ├── BackedObject.js ├── Client.js ├── ClientHandles.js ├── ClientResource.js ├── Device.js ├── Request.js ├── Resolver.js ├── Server.js ├── ServerResource.js ├── StorageHandler.js ├── configurationDirectory.js ├── csdk.js ├── doAPI.js ├── establishDestination.js ├── listenerCount.js └── payload.js ├── lowlevel.js ├── package.json ├── patches ├── 0000-fix-IOT-2417.patch ├── 0001-remove-windows-WX.patch ├── 0002-fix-logger.patch ├── 0003-remove-dependencies.patch ├── 0004-darwin-needs-sqlite-too.patch └── 0005-remove-rd-cpp.patch ├── src ├── common.cc ├── common.h ├── constants.cc.in ├── constants.h ├── enums.cc.in ├── enums.h ├── functions.h ├── functions │ ├── entity-handler.cc │ ├── entity-handler.h │ ├── oc-create-delete-resource.cc │ ├── oc-do-resource.cc │ ├── oc-register-persistent-storage-handler.cc │ ├── oc-server-resource-utils.cc │ ├── oc-server-resource-utils.h │ ├── oc-server-response.cc │ ├── oc-set-default-device-entity-handler.cc │ └── simple.cc ├── main.cc ├── structures.cc ├── structures.h └── structures │ ├── handles.cc │ ├── handles.h │ ├── oc-client-response.cc │ ├── oc-client-response.h │ ├── oc-dev-addr.cc │ ├── oc-dev-addr.h │ ├── oc-entity-handler-response.cc │ ├── oc-entity-handler-response.h │ ├── oc-identity.cc │ ├── oc-identity.h │ ├── oc-payload-macros.h │ ├── oc-payload.cc │ ├── oc-payload.h │ └── oc-rep-payload │ ├── to-c.cc │ ├── to-c.h │ ├── to-js.cc │ └── to-js.h └── tests ├── assert-to-console.js ├── dlopennow.cc ├── getresult.js ├── istanbul.json ├── preamble.js ├── provision ├── index.js ├── produceClientContent.js └── produceServerContent.js ├── security.boilerplate.json ├── setup.js ├── suite.js ├── tests ├── API Presence.js ├── API Retrieve Secure Resource │ ├── client.js │ └── server.js ├── Backed Object.js ├── Callback Exception │ ├── client.js │ └── server.js ├── Complex Payload │ ├── client.js │ └── server.js ├── Device Entity Handler │ ├── client.js │ └── server.js ├── Discovery │ ├── client.js │ └── server.js ├── Exceptions.js ├── Get Request │ ├── client.js │ └── server.js ├── Interactive Server Startup.js ├── Local Device And Platform.js ├── Multiple Observers │ ├── client1.js │ ├── client2.js │ └── server.js ├── Resource Directory │ ├── cleanupRequest.js │ ├── client1.js │ ├── client2.js │ └── server.js └── Resource Operations.js └── utils.js /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "eslint-config-jquery", 3 | "root": true, 4 | "globals": { 5 | "Promise": false 6 | }, 7 | "env": { 8 | "node": true 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text eol=lf 2 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | .eslintrc.json 2 | .npmignore 3 | .travis.yml 4 | appveyor.yml 5 | grunt-build 6 | Gruntfile.js 7 | tests 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: cpp 3 | 4 | matrix: 5 | fast_finish: true 6 | include: 7 | - env: NODE_VERSION=4.0 TEST_SCRIPT=lint 8 | os: linux 9 | - env: NODE_VERSION=lts/argon TEST_SCRIPT=test 10 | os: linux 11 | addons: &1 12 | apt: 13 | sources: 14 | - ubuntu-toolchain-r-test 15 | packages: 16 | - libcurl4-openssl-dev 17 | - uuid-dev 18 | - g++-4.8 19 | - libboost-all-dev 20 | - env: NODE_VERSION=lts/argon TEST_SCRIPT=test 21 | os: osx 22 | osx_image: xcode8.2 23 | - env: NODE_VERSION=lts/boron TEST_SCRIPT=test 24 | os: linux 25 | addons: *1 26 | - env: NODE_VERSION=lts/boron TEST_SCRIPT=test 27 | os: osx 28 | osx_image: xcode8.2 29 | - env: NODE_VERSION=5.5.0 TEST_SCRIPT=test 30 | os: linux 31 | addons: *1 32 | - env: NODE_VERSION=5.5.0 TEST_SCRIPT=test 33 | os: osx 34 | osx_image: xcode8.2 35 | - env: NODE_VERSION=stable TEST_SCRIPT=test 36 | os: linux 37 | addons: *1 38 | - env: NODE_VERSION=stable TEST_SCRIPT=test 39 | os: osx 40 | osx_image: xcode8.2 41 | - env: NODE_VERSION=7 TEST_SCRIPT=test 42 | os: linux 43 | addons: *1 44 | - env: NODE_VERSION=7 TEST_SCRIPT=test 45 | os: osx 46 | osx_image: xcode8.2 47 | - env: NODE_VERSION=stable TEST_SCRIPT=publish-coverage 48 | os: linux 49 | addons: *1 50 | - env: NODE_VERSION=8.4.0 TEST_SCRIPT=test SET_NODE_OPTIONS=--napi-modules 51 | os: linux 52 | addons: *1 53 | - env: NODE_VERSION=8.4.0 TEST_SCRIPT=test SET_NODE_OPTIONS=--napi-modules 54 | os: osx 55 | osx_image: xcode8.2 56 | allow_failures: 57 | - env: NODE_VERSION=stable TEST_SCRIPT=publish-coverage 58 | os: linux 59 | addons: *1 60 | install: 61 | - | 62 | if test "x${TRAVIS_OS_NAME}x" = "xlinuxx"; then 63 | export CXX="g++-4.8" CC="gcc-4.8" 64 | fi 65 | - rm -rf ~/.nvm 66 | - wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.7/install.sh | 67 | bash 68 | - source ~/.nvm/nvm.sh 69 | - nvm install "${NODE_VERSION}" 70 | - | 71 | if test "x${TRAVIS_OS_NAME}x" = "xosxx"; then 72 | sudo easy_install pip 73 | sudo pip install --egg 'scons<3.0.0' 74 | fi 75 | - node --version 76 | - npm --version 77 | - npm install -g grunt-cli 78 | - | 79 | if test "x${TEST_SCRIPT}x" = "xtestx" -o "x${TEST_SCRIPT}x" = "xpublish-coveragex"; then 80 | npm install -g "$(npm pack)" 81 | fi 82 | - npm install --ignore-scripts 83 | - | 84 | if test "x${TEST_SCRIPT}x" = "xtestx" -o "x${TEST_SCRIPT}x" = "xpublish-coveragex"; then 85 | npm link iotivity-node 86 | fi 87 | script: 88 | - NODE_OPTIONS="${SET_NODE_OPTIONS}" grunt "${TEST_SCRIPT}" --ci 89 | 90 | # Send a notification to chat.freenode.net#iotivity-node 91 | # The server#channel-name is encrypted so notifications are only sent from the 92 | # main repo and not from forks or PRs. 93 | notifications: 94 | irc: 95 | channels: 96 | - secure: i1PXMQry2x9WqT2Iv9Lq66+VHkettjrDhiC1C6ha/yPI5P9sNGZmad0hiBtg7Z8NfmaFuWUqwFI5fnw/iM1hqQKMQVIuYLsLdagZLldtYcUR3Un+2yVsn9PFj5PnS2kd9aUBOO+7YOt1v6snRGGJQsjlD5cAKaZ7QZrw2OpMVsjLmS1TjrOZz6jPkZUqixVo+lnnWTKIWjx7LIkaCiihPUn1CDV5ke3s9BLp/9NhCe77wa2qq1AXIjrjUYPif9kogqnIKJW/KTqvgcixOTxJqjNIC/dKWU8UEyH3ZeH9JxeSrZwxztTOHCgfcDklanZrI9uCUOMOa1Vs/MxW8FLxr09SsjYWH4GYjQpb5RRzHvRLYlL1VukdUz1M5nr0riImrDDumigxxGNpmgLprQ9w1jkMK1AnDtAhA8CBkad+D0gkuwRej53izi285zPu9MV/DTSW1zGmYo33GoyV3pbkuItdCEERmC7aoY4cRTLjjdOL8dJUjpZ8R7mGJRZWEtDl629eSbDhciA8LM9SCiXLrT73wiHtSO/fE/BPJy2QBOQfbtEx7HCQ3yNyPFmvkE/cZts0dtF5WAOhw6xSDXuNKq+rdk3bv133GOoqoTZ7rs1R11fKPOZG6MKDyyGrSHB3vG6u1L+9blq9CYTvfncka/u7HVh9RV1cuzCuYfY7yog= 97 | -------------------------------------------------------------------------------- /AUTHORS.txt: -------------------------------------------------------------------------------- 1 | binmiao 2 | Gabriel Schulhof 3 | Geoffroy Van Cutsem 4 | Hans Bakker 5 | Philippe Coval 6 | Rami Alshafi 7 | Sakari Poussa 8 | Srinivasa Ragavan 9 | Sudarsana Nagineni 10 | Tonny Tzeng 11 | Trevor Bramwell 12 | wanghongjuan 13 | Zhiqiang Zhang 14 | Zoltan Kis 15 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright 2016 Intel Corporation 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | module.exports = function( grunt ) { 17 | "use strict"; 18 | 19 | var path = require( "path" ); 20 | var suites; 21 | 22 | require( "load-grunt-config" )( grunt, { 23 | configPath: [ 24 | path.join( __dirname, "grunt-build", "tasks", "options" ), 25 | path.join( __dirname, "grunt-build", "tasks" ) 26 | ], 27 | init: true 28 | } ); 29 | 30 | suites = grunt.option( "ocf-suites" ) ? 31 | grunt.option( "ocf-suites" ).split( "," ) : undefined; 32 | 33 | if ( suites ) { 34 | grunt.config.set( "iot-js-api.plain.tests", suites ); 35 | grunt.config.set( "iot-js-api.secure.tests", suites ); 36 | grunt.config.set( "iot-js-api.coverage.tests", suites ); 37 | } 38 | 39 | require( "load-grunt-tasks" )( grunt ); 40 | grunt.task.loadNpmTasks( "iot-js-api" ); 41 | 42 | }; 43 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Setting up security 2 | 3 | Currently security is supported via resources that are marked as secure, and via an ACL file set up a priori. The high level bindings provide a persistent storage mechanism which iotivity uses to store ACLs. The mechanism works as follows: 4 | 5 | 0. The sha256sum of the absolute path of the main script which was used to launch the node process is computed. For example, if the script is `/home/user/secure-door/secure-door-lock.js`, then the sha256sum will be `08417c1debd48131536fa8bc152d776c9e8949b639d1e0fa200b14d5f6c917c8`. The sha256sum corresponding to the above script can be obtained with the following command: 6 | ``` 7 | echo -n '/home/user/secure-door/secure-door-lock.js' | sha256sum 8 | ``` 9 | 10 | 0. The directory `${HOME}/.iotivity-node/` is created, where `` is the checksum computed above. 11 | 12 | 0. The ACL file generated by iotivity will be placed into that directory. You can use `iotivity-installed/bin/json2cbor` from the location where iotivity-node was installed to create a cbor file which you can place in the above-mentioned directory. 13 | 14 | 0. `test/preamble.js` is a utility script which you can use as a reference for generating your own ACL files. It's not suitable for production use, because it always gives full access to the resources it accepts as parameters, since it was designed for use by the test suite. 15 | 16 | 0. The details of the structure of JSON source files to be used with `json2cbor` are described at https://wiki.iotivity.org/security_resource_manager. 17 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | init: 2 | - git config --global core.autocrlf input 3 | 4 | shallow_clone: true 5 | 6 | environment: 7 | matrix: 8 | - nodejs_version: "4" 9 | - nodejs_version: "5.5.0" 10 | - nodejs_version: "6" 11 | - nodejs_version: "8" 12 | 13 | platform: 14 | - x86 15 | - x64 16 | 17 | matrix: 18 | fast_finish: true 19 | 20 | install: 21 | - ps: Get-NetAdapterBinding | where {$_.componentid -like "ms_tcpip6"} | Disable-NetAdapterBinding 22 | - ps: Get-NetAdapterBinding 23 | - ps: Install-Product node $env:nodejs_version x64 24 | - pip install --egg "scons<3.0.0" 25 | - node --version 26 | - npm -g install npm@5.3.0 27 | - npm --version 28 | - npm install -g grunt-cli 29 | 30 | test_script: 31 | - ps: npm install -g "$(npm pack)" 32 | - npm install --ignore-scripts 33 | - npm link iotivity-node 34 | - grunt test --ci 35 | 36 | build: off 37 | -------------------------------------------------------------------------------- /build-scripts/generate-constants.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var _ = { 16 | map: require( "lodash.map" ), 17 | uniq: require( "lodash.uniq" ), 18 | without: require( "lodash.without" ) 19 | }; 20 | var path = require( "path" ); 21 | var fs = require( "fs" ); 22 | var includePaths = require( "./helpers/header-paths" ); 23 | var repoPaths = require( "./helpers/repo-paths" ); 24 | 25 | function parseFileForConstants( fileName ) { 26 | return _.map( 27 | _.without( 28 | _.uniq( 29 | _.map( 30 | fs.readFileSync( fileName, { encoding: "utf8" } ) 31 | .replace( /\r/g, "" ) 32 | .split( "\n" ), 33 | function( line ) { 34 | var fields; 35 | 36 | if ( !line.match( /^#define/ ) ) { 37 | return; 38 | } 39 | 40 | // Do what awk does - split into tokens by whitespace 41 | fields = line.match( /\S+/g ); 42 | if ( fields.length > 2 && !fields[ 1 ].match( /[()]/ ) && 43 | 44 | // Constants we don't want 45 | fields[ 1 ] !== "OC_RSRVD_DEVICE_TTL" ) { 46 | return ( fields[ 2 ][ 0 ] === "\"" ? "string_utf8" : "double" ) + 47 | " " + fields[ 1 ]; 48 | } 49 | } ) 50 | ), 51 | undefined ), 52 | function( line ) { 53 | var fields = line.split( " " ); 54 | return [ 55 | "#ifdef " + fields[ 1 ], 56 | "C2J_SET_PROPERTY_RETURN(" + ( [ 57 | "env", 58 | "exports", 59 | "\"" + fields[ 1 ] + "\"", 60 | fields[ 0 ], 61 | fields[ 1 ] 62 | ] 63 | .concat( fields[ 0 ] === "string_utf8" ? [ "strlen(" + fields[ 1 ] + ")" ] : [] ) 64 | .join( ", " ) ) + ");", 65 | "#endif /* def " + fields[ 1 ] + " */" 66 | ].join( "\n" ) + "\n"; 67 | } ).join( "\n" ); 68 | } 69 | 70 | var constantsCC = path.join( repoPaths.generated, "constants.cc" ); 71 | 72 | fs.writeFileSync( constantsCC, [ 73 | fs.readFileSync( path.join( repoPaths.src, "constants.cc.in" ), { encoding: "utf8" } ), 74 | "std::string InitConstants(napi_env env, napi_value exports) {", 75 | " // ocstackconfig.h: Stack configuration", 76 | parseFileForConstants( includePaths[ "ocstackconfig.h" ] ), 77 | " // octypes.h: Type definitions", 78 | parseFileForConstants( includePaths[ "octypes.h" ] ), 79 | " // octypes.h: Type definitions", 80 | parseFileForConstants( includePaths[ "rd_client.h" ] ), 81 | " return std::string();", 82 | "}" 83 | ].join( "\n" ) ); 84 | -------------------------------------------------------------------------------- /build-scripts/generate-enums.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var fs = require( "fs" ); 16 | var path = require( "path" ); 17 | var includePaths = require( "./helpers/header-paths" ); 18 | var repoPaths = require( "./helpers/repo-paths" ); 19 | 20 | // We don't generate bindings for these enums because they're not defined in our use case. 21 | var exceptions = [ "OCConnectUserPref_t" ]; 22 | 23 | var startingBraceRegex = /^}\s*/; 24 | var closingBraceRegex = /^}/; 25 | 26 | function parseFileForEnums( destination, fileName ) { 27 | var print = false; 28 | var output = ""; 29 | var enumList = []; 30 | fs.readFileSync( fileName, { encoding: "utf8" } ) 31 | .replace( /\r/g, "" ) 32 | .split( "\n" ) 33 | .forEach( function( line ) { 34 | var fields, enumName; 35 | 36 | if ( line.match( /^typedef\s+enum(\s+\S+\s+{)?/ ) ) { 37 | print = true; 38 | } 39 | if ( print ) { 40 | fields = line.match( /\S+/g ); 41 | if ( !fields ) { 42 | return; 43 | } 44 | 45 | if ( !fields[ 0 ].match( /^[{}]/ ) && fields[ 0 ] !== "typedef" ) { 46 | if ( fields[ 0 ].match( /^[A-Z]/ ) ) { 47 | fields[ 0 ] = fields[ 0 ].replace( /,/g, "" ); 48 | output += " SET_CONSTANT(env, *jsEnum, " + fields[ 0 ] + ", double);\n"; 49 | } else if ( fields[ 0 ].match( /^#(if|endif)/ ) ) { 50 | output += line + "\n"; 51 | } 52 | } else if ( fields[ 0 ].match( closingBraceRegex ) ) { 53 | enumName = line 54 | .replace( startingBraceRegex, "" ) 55 | .replace( /\s*;.*$/, "" ); 56 | if ( exceptions.indexOf( enumName ) < 0 ) { 57 | enumList.push( " SET_ENUM(env, exports, " + enumName + ");" ); 58 | fs.writeFileSync( destination, 59 | [ 60 | "static std::string bind_" + enumName + 61 | "(napi_env env, napi_value *jsEnum) {", 62 | " NAPI_CALL_RETURN(env, napi_create_object(env, jsEnum));" 63 | ].join( "\n" ) + "\n", 64 | { flag: "a" } ); 65 | } 66 | } else if ( fields[ 0 ] !== "typedef" && fields[ 0 ] !== "{" ) { 67 | if ( exceptions.indexOf( enumName ) < 0 ) { 68 | fs.writeFileSync( destination, line, { flag: "a" } ); 69 | } 70 | } 71 | if ( line.match( /;$/ ) ) { 72 | print = false; 73 | if ( exceptions.indexOf( enumName ) < 0 ) { 74 | fs.writeFileSync( destination, output + "\n return std::string();\n}\n", 75 | { flag: "a" } ); 76 | } 77 | output = ""; 78 | } 79 | } 80 | } ); 81 | return enumList.join( "\n" ); 82 | } 83 | 84 | var enumsCC = path.join( repoPaths.generated, "enums.cc" ); 85 | 86 | fs.writeFileSync( enumsCC, "" ); 87 | 88 | fs.writeFileSync( enumsCC, 89 | fs.readFileSync( path.join( repoPaths.src, "enums.cc.in" ), { encoding: "utf8" } ), 90 | { flag: "a" } ); 91 | 92 | fs.writeFileSync( enumsCC, [ 93 | "std::string InitEnums(napi_env env, napi_value exports) {", 94 | parseFileForEnums( enumsCC, includePaths[ "octypes.h" ] ), 95 | parseFileForEnums( enumsCC, includePaths[ "ocpresence.h" ] ), 96 | " return std::string();", 97 | "}" 98 | ].join( "\n" ) + "\n", 99 | { flag: "a" } ); 100 | -------------------------------------------------------------------------------- /build-scripts/generate-functions.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var _ = { 16 | map: require( "lodash.map" ), 17 | flattenDeep: require( "lodash.flattendeep" ), 18 | uniq: require( "lodash.uniq" ), 19 | without: require( "lodash.without" ) 20 | }; 21 | var fs = require( "fs" ); 22 | var path = require( "path" ); 23 | var repoPaths = require( "./helpers/repo-paths" ); 24 | 25 | function getMethods( topPath ) { 26 | return _.uniq( 27 | _.flattenDeep( 28 | _.map( 29 | fs.readdirSync( topPath ), 30 | function( item ) { 31 | item = path.join( topPath, item ); 32 | return fs.statSync( item ).isDirectory() ? 33 | getMethods( item ) : 34 | _.without( 35 | _.map( 36 | fs.readFileSync( item, { encoding: "utf8" } ) 37 | .replace( /\r/g, "" ) 38 | .split( "\n" ), 39 | function( line ) { 40 | var match = line.match( /^napi_value\s+bind_([^(]+)/ ); 41 | if ( match && match.length > 1 ) { 42 | return match[ 1 ].replace( /\s/g, "" ); 43 | } 44 | } ), 45 | undefined ); 46 | } ) ) ); 47 | } 48 | 49 | var methods; 50 | var functionsCC = path.join( repoPaths.generated, "functions.cc" ); 51 | var protosH = path.join( repoPaths.generated, "function-prototypes.h" ); 52 | 53 | methods = getMethods( repoPaths.src ); 54 | 55 | fs.writeFileSync( protosH, [ 56 | "#ifndef __IOTIVITY_NODE_FUNCTION_PROTOTYPES_H__", 57 | "#define __IOTIVITY_NODE_FUNCTION_PROTOTYPES_H__", 58 | "" 59 | ] 60 | .concat( _.map( methods, function( item ) { 61 | return "napi_value bind_" + item + "(napi_env env, napi_callback_info info);"; 62 | } ) ) 63 | .concat( [ 64 | "", 65 | "#endif /* ndef __IOTIVITY_NODE_FUNCTION_PROTOTYPES_H__ */" 66 | ] ) 67 | .join( "\n" ) ); 68 | 69 | fs.writeFileSync( functionsCC, [ 70 | "#include \"../src/functions.h\"", 71 | "#include \"function-prototypes.h\"", 72 | "", 73 | "std::string InitFunctions(napi_env env, napi_value exports) {" 74 | ] 75 | .concat( _.map( methods, function( item ) { 76 | return " SET_FUNCTION(env, exports, " + item + ");"; 77 | } ) ) 78 | .concat( [ 79 | " return std::string();", 80 | "}\n" 81 | ] ) 82 | .join( "\n" ) ); 83 | -------------------------------------------------------------------------------- /build-scripts/helpers/header-paths.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var fs = require( "fs" ); 16 | var path = require( "path" ); 17 | 18 | var index, fileIndex, completeFileName; 19 | 20 | var filesToFind = [ "octypes.h", "ocpresence.h", "ocstackconfig.h", "rd_client.h" ]; 21 | 22 | var paths = {}; 23 | 24 | var isIncludePathRegex = /^-I\s*/; 25 | 26 | // indices 0 and 1 are "node" resp. this file's name. 2 may be "-c" to indeicate that the rest of 27 | // the arguments are CFLAGS, not include paths. 28 | 29 | var cflags = ( process.argv[ 2 ] === "-c" ); 30 | 31 | for ( fileIndex in filesToFind ) { 32 | completeFileName = ""; 33 | for ( index = ( cflags ? 3 : 2 ); index < process.argv.length; index++ ) { 34 | if ( cflags && !process.argv[ index ].match( isIncludePathRegex ) ) { 35 | continue; 36 | } 37 | completeFileName = path.join( ( cflags ? 38 | process.argv[ index ].replace( isIncludePathRegex, "" ) : 39 | process.argv[ index ] ), filesToFind[ fileIndex ] ); 40 | if ( fs.existsSync( completeFileName ) ) { 41 | break; 42 | } 43 | completeFileName = ""; 44 | } 45 | if ( completeFileName ) { 46 | paths[ filesToFind[ fileIndex ] ] = completeFileName; 47 | } else { 48 | throw new Error( "Failed to find file " + filesToFind[ fileIndex ] ); 49 | } 50 | } 51 | 52 | module.exports = paths; 53 | -------------------------------------------------------------------------------- /build-scripts/helpers/repo-paths.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var fs = require( "fs" ); 16 | var path = require( "path" ); 17 | 18 | var rootPath = path.resolve( path.join( __dirname, "..", ".." ) ); 19 | var installPrefix = path.join( rootPath, "iotivity-installed" ); 20 | 21 | var paths = { 22 | root: rootPath, 23 | generated: path.join( rootPath, "generated" ), 24 | src: path.join( rootPath, "src" ), 25 | iotivity: path.join( rootPath, "iotivity-native" ), 26 | installPrefix: installPrefix, 27 | patchesPath: path.join( rootPath, "patches" ), 28 | installLibraries: path.join( installPrefix, "lib" ), 29 | installHeaders: path.join( installPrefix, "include" ) 30 | }; 31 | 32 | try { 33 | fs.mkdirSync( paths.generated ); 34 | } catch ( anError ) { 35 | if ( anError.code !== "EEXIST" ) { 36 | throw anError; 37 | } 38 | }; 39 | 40 | module.exports = paths; 41 | -------------------------------------------------------------------------------- /build-scripts/postinstall.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var path = require( "path" ); 16 | var fs = require( "fs" ); 17 | var shelljs = require( "shelljs" ); 18 | var os = require( "os" ); 19 | var repoPaths = require( "./helpers/repo-paths" ); 20 | var addonAbsoluteName = require( "bindings" )( { bindings: "iotivity", path: true } ); 21 | var addonAbsolutePath = path.dirname( addonAbsoluteName ); 22 | var addonName = path.basename( addonAbsoluteName ); 23 | 24 | var isDependency; 25 | 26 | try { 27 | isDependency = ( JSON.parse( process.env.npm_config_argv ).remain.length > 0 ); 28 | } catch ( anError ) {} 29 | isDependency = isDependency || 30 | ( "NODE_ENV" in process.env && process.env.NODE_ENV === "production" ); 31 | if ( !isDependency ) { 32 | try { 33 | isDependency = ( "iotivity-node" in 34 | JSON.parse( 35 | fs.readFileSync( 36 | path.join( __dirname, "..", "..", "..", "package.json" ) ) ).dependencies ); 37 | } catch ( anError ) {} 38 | } 39 | 40 | // If we're not installed as a dependency of another package then leave intermediate files, 41 | // sources, and build scripts lying around 42 | if ( !isDependency ) { 43 | return; 44 | } 45 | 46 | // Purge intermediate build files but leave the addon where it is 47 | shelljs.mv( addonAbsoluteName, repoPaths.root ); 48 | if ( os.platform() === "win32" ) { 49 | shelljs.mv( path.join( addonAbsolutePath, "octbstack.dll" ), repoPaths.root ); 50 | } 51 | shelljs.rm( "-rf", path.join( repoPaths.root, "build" ) ); 52 | shelljs.mkdir( "-p", addonAbsolutePath ); 53 | shelljs.mv( path.join( repoPaths.root, addonName ), addonAbsolutePath ); 54 | if ( os.platform() === "win32" ) { 55 | shelljs.mv( path.join( repoPaths.root, "octbstack.dll" ), addonAbsolutePath ); 56 | } 57 | 58 | // Purge any and all files not needed after building 59 | shelljs.rm( "-rf", 60 | path.join( repoPaths.root, "binding.gyp" ), 61 | path.join( repoPaths.root, ".gitattributes" ), 62 | path.join( repoPaths.root, "node_modules", "nan" ), 63 | path.join( repoPaths.root, "node_modules", ".bin" ), 64 | path.join( repoPaths.root, "build-scripts" ), 65 | path.join( repoPaths.installLibraries, "*.a" ), 66 | path.join( repoPaths.installLibraries, "*.lib" ), 67 | path.join( repoPaths.installLibraries, "*.dll" ), 68 | path.join( repoPaths.installLibraries, "extlibs" ), 69 | path.join( repoPaths.installLibraries, "resource" ), 70 | repoPaths.installHeaders, 71 | repoPaths.generated, 72 | repoPaths.iotivity, 73 | repoPaths.patchesPath, 74 | repoPaths.src ); 75 | -------------------------------------------------------------------------------- /grunt-build/js-build-files.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = [ 16 | "Gruntfile.js", 17 | "grunt-build/**/*.js", 18 | "build-scripts/**/*.js" 19 | ]; 20 | -------------------------------------------------------------------------------- /grunt-build/js-example-files.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = [ "js/*.js" ]; 16 | -------------------------------------------------------------------------------- /grunt-build/js-lib-files.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = [ 16 | "index.js", 17 | "lowlevel.js", 18 | "lib/*.js" 19 | ]; 20 | -------------------------------------------------------------------------------- /grunt-build/js-test-files.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = [ "tests/**/*.js" ]; 16 | -------------------------------------------------------------------------------- /grunt-build/tasks/alias.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = function( grunt ) { 16 | 17 | grunt.registerTask( "lint", [ "eslint" ] ); 18 | 19 | grunt.registerTask( "default", [ "test" ] ); 20 | 21 | grunt.registerTask( "test", [ "lint" ] 22 | .concat( grunt.option( "ci" ) ? [ "testdist" ] : [] ) 23 | .concat( [ "iot-js-api:plain", "iot-js-api:secure", "testsuite" ] ) ); 24 | 25 | grunt.registerTask( "format", [ "esformatter", "clangformat" ] ); 26 | 27 | grunt.registerTask( "coverage", [ "clean:coverage", "iot-js-api:coverage", "makeReport" ] ); 28 | 29 | grunt.registerTask( "publish-coverage", [ "coverage", "coveralls:coverage" ] ); 30 | 31 | }; 32 | -------------------------------------------------------------------------------- /grunt-build/tasks/clangformat.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = function( grunt ) { 16 | 17 | var spawn = require( "child_process" ).spawn; 18 | 19 | grunt.task.registerTask( "clangformat", "Format the C++ files", function() { 20 | var done = this.async(); 21 | 22 | spawn( ( process.env.SHELL || "sh" ), 23 | [ 24 | "-c", 25 | "find src -type f | while read; do " + 26 | "clang-format -style=Google -i \"$REPLY\" && echo \"File $REPLY formatted.\";" + 27 | "done" 28 | ], 29 | { stdio: "inherit" } ) 30 | .on( "exit", function( code ) { 31 | done.apply( this, ( code === 0 ? [] : [ false ] ) ); 32 | } ); 33 | } ); 34 | 35 | }; 36 | -------------------------------------------------------------------------------- /grunt-build/tasks/options/clean.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = { 16 | coverage: [ "coverage" ] 17 | }; 18 | -------------------------------------------------------------------------------- /grunt-build/tasks/options/coveralls.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = { 16 | coverage: { 17 | src: "coverage/lcov.info" 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /grunt-build/tasks/options/esformatter.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = { 16 | options: { 17 | preset: "jquery", 18 | plugins: [ "esformatter-jquery-chain" ] 19 | }, 20 | src: [] 21 | .concat( require( "../../js-build-files" ) ) 22 | .concat( require( "../../js-example-files" ) ) 23 | .concat( require( "../../js-lib-files" ) ) 24 | .concat( require( "../../js-test-files" ) ) 25 | }; 26 | -------------------------------------------------------------------------------- /grunt-build/tasks/options/eslint.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = { 16 | examples: { src: require( "../../js-example-files" ) }, 17 | tests: { src: require( "../../js-test-files" ) }, 18 | 19 | // The library and the build files must not use the global "console" 20 | lib: { 21 | options: { 22 | rules: { 23 | "no-restricted-globals": [ 2, "console" ] 24 | } 25 | }, 26 | src: require( "../../js-lib-files" ) 27 | }, 28 | build: { 29 | options: { 30 | rules: { 31 | "no-restricted-globals": [ 2, "console" ] 32 | } 33 | }, 34 | src: require( "../../js-build-files" ) 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /grunt-build/tasks/options/makeReport.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = { 16 | src: "coverage/**/coverage*.json", 17 | options: { 18 | type: "lcov", 19 | dir: "coverage", 20 | print: "detail" 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /grunt-build/tasks/testsuite.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = function( grunt ) { 16 | 17 | var assignIn = require( "lodash.assignin" ), 18 | path = require( "path" ), 19 | spawn = require( "child_process" ).spawn; 20 | 21 | grunt.task.registerTask( "testsuite", "Run the test suite", function() { 22 | var done = this.async(); 23 | spawn( "node", 24 | [ path.join( process.cwd(), "tests", "suite.js" ) ] 25 | 26 | // The argument to pass to require() in order to obtain iotivity-node 27 | .concat( [ grunt.option( "ci" ) ? 28 | path.dirname( require.resolve( "iotivity-node" ) ) : 29 | process.cwd() 30 | ] ) 31 | 32 | // The suites to run, or no argument if suites are not specified 33 | .concat( grunt.option( "suites" ) ? [ grunt.option( "suites" ) ] : [] ), 34 | { 35 | env: assignIn( {}, process.env, { "MALLOC_CHECK_": 2 } ), 36 | stdio: "inherit" 37 | } ) 38 | .on( "close", function( code ) { 39 | done( code === 0 || code === null ); 40 | } ); 41 | } ); 42 | 43 | }; 44 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = require( "./lib/Device" ); 16 | 17 | -------------------------------------------------------------------------------- /js/README.md: -------------------------------------------------------------------------------- 1 | # `iotivity-node` Examples 2 | 3 | ## COAPS 4 | 5 | The files `high-level-client.coaps.js` and `high-level-server.coaps.js` are for 6 | a client/server pair illustrating DTLS access to a resource. To run the example, 7 | please follow the steps below: 8 | 9 | 0. In addition to `iotivity-node`, build `iotivity` with `SECURED=1` and 10 | `RD_MODE=all`. Let the root of the `iotivity` repository be `$iotivityRoot`. 11 | 12 | 0. Calculate the sha256 sum of the server. The example below assumes the server 13 | is located in `/home/user/iotivity-node/js/high-level-server.coaps.js`. 14 | Replace the path in the example below with the actual absolute path to the 15 | file `high-level-server.coaps.js`. 16 | 17 | ```sh 18 | echo -n '/home/user/iotivity-node/js/high-level-server.coaps.js' | sha256sum 19 | ``` 20 | 21 | Copy the resulting value to the clipboard. Let the value be `$serverHash`. 22 | 23 | 0. Create the directory `${HOME}/.iotivity-node/$serverHash`. 24 | 25 | ```sh 26 | mkdir -p ~/.iotivity-node/$serverHash 27 | ``` 28 | 29 | 0. Copy the file 30 | `$iotivityRoot/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat` 31 | to `${HOME}/.iotivity-node/$serverHash/oic_svr_db.dat` 32 | 33 | 0. Start the server 34 | 35 | ```sh 36 | node high-level-server.coaps.js 37 | ``` 38 | 39 | 0. Switch to the directory where iotivity built the provisioning client, and run 40 | it from there. Let `$platform` be the platform for which you build iotivity, 41 | `$architecture` be the architecture for which you built iotivity, and 42 | `$buildType` be the build type - i.e., `release` for a production build, and 43 | `debug` for a development build. 44 | 45 | ```sh 46 | cd $iotivityRoot/out/$platform/$architecture/$buildType/resource/csdk/security/provisioning/sample 47 | ./provisioningclient 48 | ``` 49 | 50 | 0. Choose 11 from the menu by typing `11` and pressing `Enter` to discover 51 | unowned devices. The server should be listed under "Discovered Unowned 52 | Devices" with uuid `12345678-1234-1234-1234-123456789012`. 53 | 54 | 0. Choose 20 from the menu by typing `20` and pressing `Enter` to assume 55 | ownership of the devices discovered in the previous step. 56 | 57 | 0. Choose 99 to exit the client. 58 | 59 | 0. Calculate the sha256 sum of the client. The example below assumes the client 60 | is located in `/home/user/iotivity-node/js/high-level-client.coaps.js`. 61 | Replace the path in the example below with the actual absolute path to the 62 | file `high-level-client.coaps.js`. 63 | 64 | ```sh 65 | echo -n '/home/user/iotivity-node/js/high-level-client.coaps.js' | sha256sum 66 | ``` 67 | 68 | Copy the resulting value to the clipboard. Let the value be `$clientHash`. 69 | 70 | 0. Create the directory `${HOME}/.iotivity-node/$clientHash`. 71 | 72 | ```sh 73 | mkdir -p ~/.iotivity-node/$clientHash 74 | ``` 75 | 76 | 0. Copy the file `oic_svr_db_client.dat` from the current directory (in which 77 | the `provisioningclient` program was built) to the newly created directory 78 | and rename it to `oic_svr_db.dat`. 79 | 80 | ```sh 81 | cp ./oic_svr_db_client.dat ${HOME}/.iotivity-node/$clientHash/oic_svr_db.dat 82 | ``` 83 | 84 | 0. Launch the client. 85 | 86 | ```sh 87 | node high-level-client.coaps.js 88 | ``` 89 | -------------------------------------------------------------------------------- /js/client.delete.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-node-delete-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in client mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 26 | 27 | intervalId = setInterval( function() { 28 | iotivity.OCProcess(); 29 | }, 1000 ); 30 | 31 | console.log( "Issuing discovery request" ); 32 | 33 | // Discover resources and list them 34 | iotivity.OCDoResource( 35 | 36 | // The bindings fill in this object 37 | handleReceptacle, 38 | 39 | iotivity.OCMethod.OC_REST_DISCOVER, 40 | 41 | // Standard path for discovering resources 42 | iotivity.OC_MULTICAST_DISCOVERY_URI, 43 | 44 | // There is no destination 45 | null, 46 | 47 | // There is no payload 48 | null, 49 | iotivity.OCConnectivityType.CT_DEFAULT, 50 | iotivity.OCQualityOfService.OC_HIGH_QOS, 51 | function( handle, response ) { 52 | console.log( "Received response to DISCOVER request:" ); 53 | console.log( JSON.stringify( response, null, 4 ) ); 54 | var index, 55 | destination = response.addr, 56 | getHandleReceptacle = {}, 57 | resources = response && response.payload && response.payload.resources, 58 | resourceCount = resources ? resources.length : 0, 59 | deleteResponseHandler = function( handle, response ) { 60 | console.log( "Received response to DELETE request:" ); 61 | console.log( JSON.stringify( response, null, 4 ) ); 62 | return iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 63 | }; 64 | 65 | // If the sample URI is among the resources, issue the GET request to it 66 | for ( index = 0; index < resourceCount; index++ ) { 67 | if ( resources[ index ].uri === sampleUri ) { 68 | iotivity.OCDoResource( 69 | getHandleReceptacle, 70 | iotivity.OCMethod.OC_REST_DELETE, 71 | sampleUri, 72 | destination, 73 | null, 74 | iotivity.OCConnectivityType.CT_DEFAULT, 75 | iotivity.OCQualityOfService.OC_HIGH_QOS, 76 | deleteResponseHandler, 77 | null ); 78 | } 79 | } 80 | 81 | return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 82 | }, 83 | 84 | // There are no header options 85 | null ); 86 | 87 | // Exit gracefully when interrupted 88 | process.on( "SIGINT", function() { 89 | console.log( "SIGINT: Quitting..." ); 90 | 91 | // Tear down the processing loop and stop iotivity 92 | clearInterval( intervalId ); 93 | iotivity.OCStop(); 94 | 95 | // Exit 96 | process.exit( 0 ); 97 | } ); 98 | -------------------------------------------------------------------------------- /js/client.discovery.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | iotivity = require( "iotivity-node/lowlevel" ), 18 | options = ( function() { 19 | var index, 20 | returnValue = { 21 | 22 | // By default we discover resources 23 | discoveryUri: iotivity.OC_MULTICAST_DISCOVERY_URI 24 | }; 25 | 26 | for ( index in process.argv ) { 27 | if ( process.argv[ index ] === "-d" || process.argv[ index ] === "--device" ) { 28 | returnValue.discoveryUri = iotivity.OC_RSRVD_DEVICE_URI; 29 | } else if ( process.argv[ index ] === "-p" || process.argv[ index ] === "-platform" ) { 30 | returnValue.discoveryUri = iotivity.OC_RSRVD_PLATFORM_URI; 31 | } 32 | } 33 | 34 | return returnValue; 35 | } )(); 36 | 37 | console.log( "Starting OCF stack in client mode" ); 38 | 39 | // Start iotivity and set up the processing loop 40 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 41 | 42 | intervalId = setInterval( function() { 43 | iotivity.OCProcess(); 44 | }, 1000 ); 45 | 46 | console.log( "Issuing discovery request" ); 47 | 48 | // Discover resources and list them 49 | iotivity.OCDoResource( 50 | 51 | // The bindings fill in this object 52 | handleReceptacle, 53 | 54 | iotivity.OCMethod.OC_REST_DISCOVER, 55 | 56 | // Standard path for discovering devices/resources 57 | options.discoveryUri, 58 | 59 | // There is no destination 60 | null, 61 | 62 | // There is no payload 63 | null, 64 | iotivity.OCConnectivityType.CT_DEFAULT, 65 | iotivity.OCQualityOfService.OC_HIGH_QOS, 66 | function( handle, response ) { 67 | console.log( "Discovery response: " + JSON.stringify( response, null, 4 ) ); 68 | return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 69 | }, 70 | 71 | // There are no header options 72 | null ); 73 | 74 | // Exit gracefully when interrupted 75 | process.on( "SIGINT", function() { 76 | console.log( "SIGINT: Quitting..." ); 77 | 78 | // Tear down the processing loop and stop iotivity 79 | clearInterval( intervalId ); 80 | iotivity.OCStop(); 81 | 82 | // Exit 83 | process.exit( 0 ); 84 | } ); 85 | -------------------------------------------------------------------------------- /js/client.get.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-node-get-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in client mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 26 | 27 | intervalId = setInterval( function() { 28 | iotivity.OCProcess(); 29 | }, 1000 ); 30 | 31 | console.log( "Issuing discovery request" ); 32 | 33 | // Discover resources and list them 34 | iotivity.OCDoResource( 35 | 36 | // The bindings fill in this object 37 | handleReceptacle, 38 | 39 | iotivity.OCMethod.OC_REST_DISCOVER, 40 | 41 | // Standard path for discovering resources 42 | iotivity.OC_MULTICAST_DISCOVERY_URI, 43 | 44 | // There is no destination 45 | null, 46 | 47 | // There is no payload 48 | null, 49 | iotivity.OCConnectivityType.CT_DEFAULT, 50 | iotivity.OCQualityOfService.OC_HIGH_QOS, 51 | function( handle, response ) { 52 | console.log( "Received response to DISCOVER request:" ); 53 | console.log( JSON.stringify( response, null, 4 ) ); 54 | var index, 55 | destination = response.addr, 56 | getHandleReceptacle = {}, 57 | resources = response && response.payload && response.payload.resources, 58 | resourceCount = resources ? resources.length : 0, 59 | getResponseHandler = function( handle, response ) { 60 | console.log( "Received response to GET request:" ); 61 | console.log( JSON.stringify( response, null, 4 ) ); 62 | return iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 63 | }; 64 | 65 | // If the sample URI is among the resources, issue the GET request to it 66 | for ( index = 0; index < resourceCount; index++ ) { 67 | if ( resources[ index ].uri === sampleUri ) { 68 | iotivity.OCDoResource( 69 | getHandleReceptacle, 70 | iotivity.OCMethod.OC_REST_GET, 71 | sampleUri, 72 | destination, 73 | { 74 | type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION, 75 | values: { 76 | question: "How many angels can dance on the head of a pin?" 77 | } 78 | }, 79 | iotivity.OCConnectivityType.CT_DEFAULT, 80 | iotivity.OCQualityOfService.OC_HIGH_QOS, 81 | getResponseHandler, 82 | null ); 83 | } 84 | } 85 | 86 | return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 87 | }, 88 | 89 | // There are no header options 90 | null ); 91 | 92 | // Exit gracefully when interrupted 93 | process.on( "SIGINT", function() { 94 | console.log( "SIGINT: Quitting..." ); 95 | 96 | // Tear down the processing loop and stop iotivity 97 | clearInterval( intervalId ); 98 | iotivity.OCStop(); 99 | 100 | // Exit 101 | process.exit( 0 ); 102 | } ); 103 | -------------------------------------------------------------------------------- /js/client.presence-only.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | iotivity = require( "iotivity-node/lowlevel" ); 18 | 19 | // Start iotivity and set up the processing loop 20 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 21 | 22 | intervalId = setInterval( function() { 23 | iotivity.OCProcess(); 24 | }, 1000 ); 25 | 26 | function listenForPresence() { 27 | 28 | // Request resource presence notifications 29 | console.log( "OCDoResource(presence): " + iotivity.OCDoResource( 30 | 31 | // The bindings fill in this object 32 | handleReceptacle, 33 | 34 | iotivity.OCMethod.OC_REST_DISCOVER, 35 | iotivity.OC_RSRVD_PRESENCE_URI, 36 | 37 | null, 38 | null, 39 | iotivity.OCConnectivityType.CT_DEFAULT, 40 | iotivity.OCQualityOfService.OC_HIGH_QOS, 41 | function( handle, response ) { 42 | var returnValue = iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 43 | 44 | console.log( "Received response to PRESENCE request:" ); 45 | console.log( JSON.stringify( response, null, 4 ) ); 46 | 47 | if ( response.result === iotivity.OCStackResult.OC_STACK_COMM_ERROR ) { 48 | 49 | console.log( "Request failed. Trying again." ); 50 | setTimeout( listenForPresence, 0 ); 51 | returnValue = iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 52 | } 53 | 54 | return returnValue; 55 | }, 56 | 57 | // There are no header options 58 | null ) ); 59 | } 60 | 61 | listenForPresence(); 62 | 63 | // Exit gracefully when interrupted 64 | process.on( "SIGINT", function() { 65 | console.log( "SIGINT: Quitting..." ); 66 | 67 | // Tear down the processing loop and stop iotivity 68 | clearInterval( intervalId ); 69 | iotivity.OCStop(); 70 | 71 | // Exit 72 | process.exit( 0 ); 73 | } ); 74 | -------------------------------------------------------------------------------- /js/client.presence.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.presence.js 19 | sampleUri = "/a/iotivity-node-presence-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | // Start iotivity and set up the processing loop 23 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 24 | 25 | intervalId = setInterval( function() { 26 | iotivity.OCProcess(); 27 | }, 1000 ); 28 | 29 | // Discover resources and list them 30 | iotivity.OCDoResource( 31 | 32 | // The bindings fill in this object 33 | handleReceptacle, 34 | 35 | iotivity.OCMethod.OC_REST_DISCOVER, 36 | 37 | // Standard path for discovering resources 38 | iotivity.OC_MULTICAST_DISCOVERY_URI, 39 | 40 | // There is no destination 41 | null, 42 | 43 | // There is no payload 44 | null, 45 | iotivity.OCConnectivityType.CT_DEFAULT, 46 | iotivity.OCQualityOfService.OC_HIGH_QOS, 47 | function( handle, response ) { 48 | console.log( "Received response to DISCOVER request:" ); 49 | console.log( JSON.stringify( response, null, 4 ) ); 50 | var index, 51 | destination = response.addr, 52 | presenceHandleReceptacle = {}, 53 | resources = response && response.payload && response.payload.resources, 54 | resourceCount = resources ? resources.length : 0, 55 | presenceResponseHandler = function( handle, response ) { 56 | console.log( "Received response to PRESENCE request:" ); 57 | console.log( JSON.stringify( response, null, 4 ) ); 58 | return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 59 | }; 60 | 61 | // If the sample URI is among the resources, issue the GET request to it 62 | for ( index = 0; index < resourceCount; index++ ) { 63 | if ( resources[ index ].uri === sampleUri ) { 64 | iotivity.OCDoResource( 65 | presenceHandleReceptacle, 66 | iotivity.OCMethod.OC_REST_PRESENCE, 67 | iotivity.OC_RSRVD_PRESENCE_URI, 68 | destination, 69 | null, 70 | iotivity.OCConnectivityType.CT_DEFAULT, 71 | iotivity.OCQualityOfService.OC_HIGH_QOS, 72 | presenceResponseHandler, 73 | null ); 74 | } 75 | } 76 | 77 | return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 78 | }, 79 | 80 | // There are no header options 81 | null ); 82 | 83 | // Exit gracefully when interrupted 84 | process.on( "SIGINT", function() { 85 | console.log( "SIGINT: Quitting..." ); 86 | 87 | // Tear down the processing loop and stop iotivity 88 | clearInterval( intervalId ); 89 | iotivity.OCStop(); 90 | 91 | // Exit 92 | process.exit( 0 ); 93 | } ); 94 | -------------------------------------------------------------------------------- /js/envirophat/enviro_phat.py: -------------------------------------------------------------------------------- 1 | ''' Copyright 2017 Vprime 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License.*/ 14 | 15 | @author Rami Alshafi ''' 16 | # to install the envirophat dependecies, type the following command 17 | # $ curl https://get.pimoroni.com/envirophat | bash 18 | # make sure to type 'y' or 'n' when prompted 19 | import sys 20 | import envirophat 21 | 22 | if __name__ == "__main__": 23 | arguments = sys.argv 24 | if len(arguments) == 2: 25 | if arguments[1] == "0": 26 | envirophat.leds.off() 27 | print "leds:status:False" 28 | elif arguments[1] == "1": 29 | envirophat.leds.on() 30 | print "leds:status:True" 31 | elif arguments[1] == "2": 32 | print "weather:temperature:"+str(envirophat.weather.temperature()) 33 | elif arguments[1] == "3": 34 | print "motion:accelerometer:"+str(list(envirophat.motion.accelerometer())) 35 | elif arguments[1] == "4": 36 | print "light:rgb:"+str(list(envirophat.light.rgb())) 37 | else: 38 | print "error:wrong_command:please press any of the following options: 0, 1, 2, 3, 4" 39 | -------------------------------------------------------------------------------- /js/high-level-client.coaps.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | console.log( "Acquiring OCF device" ); 16 | 17 | var client = require( "iotivity-node" ).client; 18 | 19 | function errorHandler( error ) { 20 | console.log( error.stack + ": " + JSON.stringify( error, null, 4 ) ); 21 | process.exit( 1 ); 22 | } 23 | 24 | function observer( resource ) { 25 | console.log( "Observation: " + JSON.stringify( resource, null, 4 ) ); 26 | } 27 | 28 | client 29 | .on( "resourcefound", function( resource ) { 30 | console.log( "Found resource: " + JSON.stringify( resource, null, 4 ) ); 31 | resource.on( "error", errorHandler ); 32 | 33 | client.retrieve( resource, observer ) 34 | .then( function( resultingResource ) { 35 | console.log( "Resulting resource: " + 36 | JSON.stringify( resultingResource, null, 4 ) ); 37 | } ) 38 | .catch( errorHandler ); 39 | } ) 40 | .findResources( { resourcePath: "/a/light" } ) 41 | .catch( errorHandler ); 42 | 43 | console.log( "Started looking for resources" ); 44 | -------------------------------------------------------------------------------- /js/high-level-resource-creation-client.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | console.log( "Acquiring OCF device" ); 16 | 17 | var device = require( "iotivity-node" ); 18 | 19 | function throwError( error ) { 20 | console.error( error.stack ? error.stack : ( error.message ? error.message : error ) + 21 | JSON.stringify( error, null, 4 ) ); 22 | process.exit( 1 ); 23 | } 24 | 25 | new Promise( function( fulfill, reject ) { 26 | var resourceFoundHandler = function( resource ) { 27 | console.log( "Discovered the following resource:\n" + 28 | JSON.stringify( resource, null, 4 ) ); 29 | 30 | // We've discovered the resource we were seeking. 31 | if ( resource.resourcePath === "/a/high-level-resource-creation-example" ) { 32 | console.log( "Found the test server" ); 33 | device.client.removeListener( "resourcefound", resourceFoundHandler ); 34 | fulfill( resource.deviceId ); 35 | } 36 | }; 37 | 38 | // Add a listener that will receive the results of the discovery 39 | device.client.on( "resourcefound", resourceFoundHandler ); 40 | 41 | console.log( "Issuing discovery request" ); 42 | device.client.findResources().catch( function( error ) { 43 | device.client.removeListener( "resourcefound", resourceFoundHandler ); 44 | reject( "findResource() failed: " + error ); 45 | } ); 46 | } ).then( function( deviceId ) { 47 | console.log( "deviceId discovered" ); 48 | return device.client.create( { 49 | deviceId: deviceId, 50 | resourcePath: "/a/new-resource", 51 | resourceTypes: [ "core.light" ], 52 | interfaces: [ "oic.if.baseline" ], 53 | properties: { 54 | exampleProperty: 23 55 | } 56 | } ); 57 | } ).then( function( resource ) { 58 | console.log( "remote resource successfully created: " + 59 | JSON.stringify( resource, null, 4 ) ); 60 | return device.client.delete( resource ); 61 | } ).then( function() { 62 | console.log( "remote resource successfully deleted" ); 63 | } ).catch( throwError ); 64 | -------------------------------------------------------------------------------- /js/high-level-resource-creation-server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var path = require( "path" ); 16 | 17 | require( "../tests/preamble" )( __filename, [ 18 | { 19 | href: "/a/high-level-resource-creation-example", 20 | rel: "", 21 | rt: [ "core.light" ], 22 | "if": [ "oic.if.baseline" ] 23 | }, 24 | 25 | // The resource the remote end will ask us to create 26 | { 27 | href: "/a/new-resource", 28 | rel: "", 29 | rt: [ "core.light" ], 30 | "if": [ "oic.if.baseline" ] 31 | } 32 | ], path.resolve( path.join( __dirname, ".." ) ) ); 33 | 34 | var resourceCreatedByRemote, 35 | device = require( "iotivity-node" ), 36 | _ = { 37 | extend: require( "lodash.assignin" ), 38 | bind: require( "lodash.bind" ) 39 | }; 40 | 41 | device.device = _.extend( device.device, { 42 | coreSpecVersion: "res.1.1.0", 43 | dataModels: [ "something.1.0.0" ], 44 | name: "api-server-example" 45 | } ); 46 | device.platform = _.extend( device.platform, { 47 | manufacturerName: "Intel", 48 | manufactureDate: new Date( "Wed Sep 23 10:04:17 EEST 2015" ), 49 | platformVersion: "1.1.1", 50 | firmwareVersion: "0.0.1", 51 | supportUrl: "http://example.com/" 52 | } ); 53 | 54 | function throwError( error ) { 55 | console.error( error.stack ? error.stack : ( error.message ? error.message : error ) ); 56 | process.exit( 1 ); 57 | } 58 | 59 | device.server 60 | .oncreate( function( request ) { 61 | console.log( "create request" ); 62 | device.server.register( _.extend( request.data, { 63 | discoverable: true 64 | } ) ).then( function( resource ) { 65 | console.log( "resource successfully registered" ); 66 | resourceCreatedByRemote = resource; 67 | request.respond( resource ); 68 | resource.ondelete( function( request ) { 69 | console.log( "delete request" ); 70 | resourceCreatedByRemote.unregister().then( 71 | function() { 72 | console.log( "resource successfully deleted" ); 73 | request.respond() 74 | .then( function() { 75 | console.log( "delete request successfully delivered" ); 76 | }, 77 | function( anError ) { 78 | console.log( ( "" + anError.stack ) + 79 | JSON.stringify( anError, null, 4 ) ); 80 | } ); 81 | }, 82 | _.bind( request.respondWithError, request ) ); 83 | } ); 84 | }, _.bind( request.respondWithError, request ) ); 85 | } ) 86 | .register( { 87 | resourcePath: "/a/high-level-resource-creation-example", 88 | resourceTypes: [ "core.light" ], 89 | interfaces: [ "oic.if.baseline" ], 90 | discoverable: true, 91 | observable: true, 92 | properties: { someValue: 0, someOtherValue: "Helsinki" } 93 | } ).then( function() { 94 | console.log( "initial resource successfully registered" ); 95 | }, throwError ); 96 | -------------------------------------------------------------------------------- /js/high-level-server.coaps.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | function ObservationWrapper( resource ) { 16 | if ( !( this instanceof ObservationWrapper ) ) { 17 | return new ObservationWrapper( resource ); 18 | } 19 | this.resource = resource; 20 | this.observerCount = 0; 21 | } 22 | 23 | ObservationWrapper.prototype.addObserver = function() { 24 | if ( this.observerCount === 0 ) { 25 | console.log( "Firing up interval" ); 26 | var resource = this.resource; 27 | this.intervalId = setInterval( function() { 28 | resource.properties.outputValue = Math.round( Math.random() * 42 ) + 1; 29 | resource.notify(); 30 | }, 1000 ); 31 | } 32 | this.observerCount++; 33 | }; 34 | 35 | ObservationWrapper.prototype.removeObserver = function() { 36 | this.observerCount--; 37 | if ( this.observerCount <= 0 ) { 38 | console.log( "Turning off interval" ); 39 | clearInterval( this.intervalId ); 40 | this.observerCount = 0; 41 | this.intervalId = 0; 42 | } 43 | }; 44 | 45 | var observationWrapper; 46 | 47 | function errorHandler( error ) { 48 | console.log( error.stack + ": " + JSON.stringify( error, null, 4 ) ); 49 | process.exit( 1 ); 50 | } 51 | 52 | console.log( "Acquiring OCF device" ); 53 | 54 | var ocf = require( "iotivity-node" ); 55 | 56 | ocf.device.coreSpecVersion = "ocf.1.1.0"; 57 | 58 | ocf.server 59 | .register( { 60 | resourcePath: "/a/light", 61 | resourceTypes: [ "core.light" ], 62 | interfaces: [ "oic.if.baseline" ], 63 | discoverable: true, 64 | observable: true, 65 | secure: true 66 | } ) 67 | .then( function( resource ) { 68 | console.log( "Resource registered: " + JSON.stringify( resource, null, 4 ) ); 69 | observationWrapper = ObservationWrapper( resource ); 70 | resource 71 | .onretrieve( function( request ) { 72 | if ( "observe" in request ) { 73 | var observationRequest = request.observe ? "add" : "remove"; 74 | console.log( "Observation request: " + observationRequest ); 75 | observationWrapper[ observationRequest + "Observer" ](); 76 | } 77 | request.target.properties.outputValue = 78 | Math.round( Math.random() * 42 ) + 1; 79 | console.log( "Retrieve request received. Responding with " + 80 | JSON.stringify( request.target, null, 4 ) ); 81 | request 82 | .respond() 83 | .catch( errorHandler ); 84 | } ) 85 | .onupdate( function( request ) { 86 | console.log( "Update request: " + JSON.stringify( request, null, 4 ) ); 87 | resource.properties = request.data; 88 | request.respond(); 89 | } ); 90 | } ) 91 | .catch( errorHandler ); 92 | -------------------------------------------------------------------------------- /js/mock-sensor.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This mock sensor implementation triggers an event with some data every once in a while 16 | 17 | // Return a random integer between 0 and @upperLimit 18 | function randomInteger( upperLimit ) { 19 | return Math.round( Math.random() * upperLimit ); 20 | } 21 | 22 | var _ = { 23 | extend: require( "lodash.assignin" ), 24 | bind: require( "lodash.bind" ) 25 | }; 26 | 27 | var possibleStrings = [ 28 | "Helsinki", 29 | "Espoo", 30 | "Tampere", 31 | "Oulu", 32 | "Mikkeli", 33 | "Ii" 34 | ]; 35 | 36 | var MockSensor = function MockSensor() { 37 | function trigger() { 38 | this.emit( "change", this.currentData() ); 39 | setTimeout( _.bind( trigger, this ), randomInteger( 1000 ) + 1000 ); 40 | } 41 | if ( !this._isMockSensor ) { 42 | return new MockSensor(); 43 | } 44 | setTimeout( _.bind( trigger, this ), randomInteger( 1000 ) + 1000 ); 45 | }; 46 | 47 | require( "util" ).inherits( MockSensor, require( "events" ).EventEmitter ); 48 | 49 | _.extend( MockSensor.prototype, { 50 | _isMockSensor: true, 51 | currentData: function() { 52 | return { 53 | someValue: Math.round( Math.random() * 42 ), 54 | someOtherValue: possibleStrings[ randomInteger( possibleStrings.length - 1 ) ] 55 | }; 56 | } 57 | } ); 58 | 59 | module.exports = MockSensor; 60 | -------------------------------------------------------------------------------- /js/multi-server-client.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | iotivity = require( "iotivity-node/lowlevel" ); 18 | 19 | console.log( "Starting OCF stack in server mode" ); 20 | 21 | // Start iotivity and set up the processing loop 22 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 23 | 24 | intervalId = setInterval( function() { 25 | iotivity.OCProcess(); 26 | }, 1000 ); 27 | 28 | console.log( "Issuing discovery request" ); 29 | 30 | // Discover resources and list them 31 | iotivity.OCDoResource( 32 | 33 | // The bindings fill in this object 34 | handleReceptacle, 35 | 36 | iotivity.OCMethod.OC_REST_DISCOVER, 37 | 38 | // Standard path for discovering resources 39 | iotivity.OC_MULTICAST_DISCOVERY_URI, 40 | 41 | // There is no destination 42 | null, 43 | 44 | // There is no payload 45 | null, 46 | iotivity.OCConnectivityType.CT_DEFAULT, 47 | iotivity.OCQualityOfService.OC_HIGH_QOS, 48 | function( handle, response ) { 49 | console.log( "Received response to DISCOVER request:" ); 50 | console.log( JSON.stringify( response, null, 4 ) ); 51 | var index, 52 | destination = response.addr, 53 | getHandleReceptacle = {}, 54 | resources = response && response.payload && response.payload.resources, 55 | resourceCount = resources ? resources.length : 0, 56 | getResponseHandler = function( handle, response ) { 57 | console.log( "Received response to GET request:" ); 58 | console.log( JSON.stringify( response, null, 4 ) ); 59 | return iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 60 | }; 61 | 62 | // If the sample URI is among the resources, issue the GET request to it 63 | for ( index = 0; index < resourceCount; index++ ) { 64 | if ( resources[ index ].uri.match( /iotivity-multi-server/ ) ) { 65 | iotivity.OCDoResource( 66 | getHandleReceptacle, 67 | iotivity.OCMethod.OC_REST_GET, 68 | resources[ index ].uri, 69 | destination, 70 | null, 71 | iotivity.OCConnectivityType.CT_DEFAULT, 72 | iotivity.OCQualityOfService.OC_HIGH_QOS, 73 | getResponseHandler, 74 | null ); 75 | } 76 | } 77 | 78 | return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 79 | }, 80 | 81 | // There are no header options 82 | null ); 83 | 84 | // Exit gracefully when interrupted 85 | process.on( "SIGINT", function() { 86 | console.log( "SIGINT: Quitting..." ); 87 | 88 | // Tear down the processing loop and stop iotivity 89 | clearInterval( intervalId ); 90 | iotivity.OCStop(); 91 | 92 | // Exit 93 | process.exit( 0 ); 94 | } ); 95 | -------------------------------------------------------------------------------- /js/multi-server-server1.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-multi-server-server1", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in server mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 26 | 27 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 28 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 29 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 30 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "test.0.0.1" ); 31 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 32 | iotivity.OC_RSRVD_DEVICE_NAME, "server.multi-server1" ); 33 | 34 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 35 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 36 | 37 | intervalId = setInterval( function() { 38 | iotivity.OCProcess(); 39 | }, 1000 ); 40 | 41 | console.log( "Registering resource" ); 42 | 43 | iotivity.OCCreateResource( 44 | handleReceptacle, 45 | "core.fan", 46 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 47 | sampleUri, 48 | function( flag, request ) { 49 | if ( request && request.method === iotivity.OCMethod.OC_REST_GET ) { 50 | iotivity.OCDoResponse( { 51 | requestHandle: request.requestHandle, 52 | resourceHandle: request.resource, 53 | ehResult: iotivity.OCEntityHandlerResult.OC_EH_OK, 54 | payload: { 55 | type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION, 56 | values: { 57 | answer: "Multi-server sample server 1" 58 | } 59 | }, 60 | resourceUri: sampleUri, 61 | sendVendorSpecificHeaderOptions: [] 62 | } ); 63 | } 64 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 65 | }, 66 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 67 | 68 | console.log( "Server ready" ); 69 | 70 | // Exit gracefully when interrupted 71 | process.on( "SIGINT", function() { 72 | console.log( "SIGINT: Quitting..." ); 73 | 74 | // Tear down the processing loop and stop iotivity 75 | clearInterval( intervalId ); 76 | iotivity.OCDeleteResource( handleReceptacle.handle ); 77 | iotivity.OCStop(); 78 | 79 | // Exit 80 | process.exit( 0 ); 81 | } ); 82 | -------------------------------------------------------------------------------- /js/multi-server-server2.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-multi-server-server2", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in server mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 26 | 27 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 28 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 29 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 30 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "test.0.0.1" ); 31 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 32 | iotivity.OC_RSRVD_DEVICE_NAME, "server.multi-server2" ); 33 | 34 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 35 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 36 | 37 | intervalId = setInterval( function() { 38 | iotivity.OCProcess(); 39 | }, 1000 ); 40 | 41 | console.log( "Registering resource" ); 42 | 43 | iotivity.OCCreateResource( 44 | handleReceptacle, 45 | "core.fan", 46 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 47 | sampleUri, 48 | function( flag, request ) { 49 | if ( request && request.method === iotivity.OCMethod.OC_REST_GET ) { 50 | iotivity.OCDoResponse( { 51 | requestHandle: request.requestHandle, 52 | resourceHandle: request.resource, 53 | ehResult: iotivity.OCEntityHandlerResult.OC_EH_OK, 54 | payload: { 55 | type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION, 56 | values: { 57 | answer: "Multi-server sample server 2" 58 | } 59 | }, 60 | resourceUri: sampleUri, 61 | sendVendorSpecificHeaderOptions: [] 62 | } ); 63 | } 64 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 65 | }, 66 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 67 | 68 | console.log( "Server ready" ); 69 | 70 | // Exit gracefully when interrupted 71 | process.on( "SIGINT", function() { 72 | console.log( "SIGINT: Quitting..." ); 73 | 74 | // Tear down the processing loop and stop iotivity 75 | clearInterval( intervalId ); 76 | iotivity.OCDeleteResource( handleReceptacle.handle ); 77 | iotivity.OCStop(); 78 | 79 | // Exit 80 | process.exit( 0 ); 81 | } ); 82 | -------------------------------------------------------------------------------- /js/node_modules/README.md: -------------------------------------------------------------------------------- 1 | # NOTE 2 | 3 | This directory, and the file iotivity.js are only required so the example look the way they would 4 | outside the repository. This makes them easier to copy. 5 | 6 | Without it, the examples, in order to work, would have to 7 | 8 | ```JS 9 | var iotivity = require( "../" ); 10 | ``` 11 | 12 | With this hack in place, they can 13 | 14 | ```JS 15 | var iotivity = require( "iotivity" ); 16 | ``` 17 | 18 | and so they look exactly the way they would outside the project. 19 | 20 | If you copy any of the examples outside the project, you need not and **must** not copy this 21 | directory or the file iotivity.js along with them. You need only npm install iotivity first. 22 | -------------------------------------------------------------------------------- /js/node_modules/iotivity-node/index.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = require( "../../../index" ); 16 | -------------------------------------------------------------------------------- /js/node_modules/iotivity-node/lowlevel.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = require( "../../../lowlevel" ); 16 | -------------------------------------------------------------------------------- /js/server.delete.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-node-delete-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in server mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 26 | 27 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 28 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 29 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 30 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "test.0.0.1" ); 31 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 32 | iotivity.OC_RSRVD_DEVICE_NAME, "server.delete" ); 33 | 34 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 35 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 36 | 37 | intervalId = setInterval( function() { 38 | iotivity.OCProcess(); 39 | }, 1000 ); 40 | 41 | console.log( "Registering resource" ); 42 | 43 | // Create a new resource 44 | iotivity.OCCreateResource( 45 | 46 | // The bindings fill in this object 47 | handleReceptacle, 48 | 49 | "core.fan", 50 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 51 | sampleUri, 52 | function( flag, request ) { 53 | console.log( "Entity handler called with flag = " + flag + " and the following request:" ); 54 | console.log( JSON.stringify( request, null, 4 ) ); 55 | 56 | // If we find the magic question in the request, we return the magic answer 57 | if ( request && request.method === iotivity.OCMethod.OC_REST_DELETE ) { 58 | 59 | var result = iotivity.OCDeleteResource( handleReceptacle.handle ); 60 | 61 | console.log( "OCDeleteResource() has resulted in " + result ); 62 | 63 | if ( result === iotivity.OCStackResult.OC_STACK_OK ) { 64 | handleReceptacle = null; 65 | } 66 | 67 | iotivity.OCDoResponse( { 68 | requestHandle: request.requestHandle, 69 | resourceHandle: null, 70 | ehResult: result ? 71 | iotivity.OCEntityHandlerResult.OC_EH_ERROR : 72 | iotivity.OCEntityHandlerResult.OC_EH_RESOURCE_DELETED, 73 | payload: null, 74 | resourceUri: sampleUri, 75 | sendVendorSpecificHeaderOptions: [] 76 | } ); 77 | 78 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 79 | } 80 | 81 | // By default we error out 82 | return iotivity.OCEntityHandlerResult.OC_EH_ERROR; 83 | }, 84 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 85 | 86 | console.log( "Server ready" ); 87 | 88 | // Exit gracefully when interrupted 89 | process.on( "SIGINT", function() { 90 | console.log( "SIGINT: Quitting..." ); 91 | 92 | // Tear down the processing loop and stop iotivity 93 | clearInterval( intervalId ); 94 | if ( handleReceptacle ) { 95 | iotivity.OCDeleteResource( handleReceptacle.handle ); 96 | } 97 | iotivity.OCStop(); 98 | 99 | // Exit 100 | process.exit( 0 ); 101 | } ); 102 | -------------------------------------------------------------------------------- /js/server.discoverable.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | iotivity = require( "iotivity-node/lowlevel" ); 18 | 19 | console.log( "Starting OCF stack in server mode" ); 20 | 21 | // Start iotivity and set up the processing loop 22 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 23 | 24 | intervalId = setInterval( function() { 25 | iotivity.OCProcess(); 26 | }, 1000 ); 27 | 28 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 29 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 30 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 31 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "test.0.0.1" ); 32 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 33 | iotivity.OC_RSRVD_DEVICE_NAME, "server.discoverable" ); 34 | 35 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 36 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 37 | 38 | console.log( "Registering resources" ); 39 | 40 | // Create a new resource 41 | iotivity.OCCreateResource( 42 | 43 | // The bindings fill in this object 44 | handleReceptacle, 45 | 46 | "core.fan", 47 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 48 | "/a/fan", 49 | function( flag, request ) { 50 | console.log( "Entity handler called with flag = " + flag + " and the following request:" ); 51 | console.log( JSON.stringify( request, null, 4 ) ); 52 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 53 | }, 54 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 55 | 56 | // Create a new resource 57 | iotivity.OCCreateResource( 58 | 59 | // The bindings fill in this object 60 | handleReceptacle, 61 | 62 | "core.light", 63 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 64 | "/a/light", 65 | function( flag, request ) { 66 | console.log( "Entity handler called with flag = " + flag + " and the following request:" ); 67 | console.log( JSON.stringify( request, null, 4 ) ); 68 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 69 | }, 70 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 71 | 72 | console.log( "Server ready" ); 73 | 74 | // Exit gracefully when interrupted 75 | process.on( "SIGINT", function() { 76 | console.log( "SIGINT: Quitting..." ); 77 | 78 | // Tear down the processing loop and stop iotivity 79 | clearInterval( intervalId ); 80 | iotivity.OCDeleteResource( handleReceptacle.handle ); 81 | iotivity.OCStop(); 82 | 83 | // Exit 84 | process.exit( 0 ); 85 | } ); 86 | -------------------------------------------------------------------------------- /js/server.get.coaps.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-node-get-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in server mode" ); 23 | 24 | iotivity.OCRegisterPersistentStorageHandler( require( "../lib/StorageHandler" )() ); 25 | 26 | // Start iotivity and set up the processing loop 27 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 28 | 29 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 30 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 31 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 32 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "abc.0.0.1" ); 33 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 34 | iotivity.OC_RSRVD_DEVICE_NAME, "server.get" ); 35 | 36 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 37 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 38 | 39 | intervalId = setInterval( function() { 40 | iotivity.OCProcess(); 41 | }, 1000 ); 42 | 43 | console.log( "Registering resource" ); 44 | 45 | // Create a new resource 46 | iotivity.OCCreateResource( 47 | 48 | // The bindings fill in this object 49 | handleReceptacle, 50 | 51 | "core.fan", 52 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 53 | sampleUri, 54 | function( flag, request ) { 55 | console.log( "Entity handler called with flag = " + flag + " and the following request:" ); 56 | console.log( JSON.stringify( request, null, 4 ) ); 57 | 58 | // If we find the magic question in the request, we return the magic answer 59 | if ( request && request.payload && request.payload.values && 60 | request.payload.values.question === 61 | "How many angels can dance on the head of a pin?" ) { 62 | 63 | iotivity.OCDoResponse( { 64 | requestHandle: request.requestHandle, 65 | resourceHandle: request.resource, 66 | ehResult: iotivity.OCEntityHandlerResult.OC_EH_OK, 67 | payload: { 68 | type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION, 69 | values: { 70 | "answer": "As many as wanting." 71 | } 72 | }, 73 | resourceUri: sampleUri, 74 | sendVendorSpecificHeaderOptions: [] 75 | } ); 76 | 77 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 78 | } 79 | 80 | // By default we error out 81 | return iotivity.OCEntityHandlerResult.OC_EH_ERROR; 82 | }, 83 | iotivity.OCResourceProperty.OC_DISCOVERABLE | iotivity.OCResourceProperty.OC_SECURE ); 84 | 85 | console.log( "Server ready" ); 86 | 87 | // Exit gracefully when interrupted 88 | process.on( "SIGINT", function() { 89 | console.log( "SIGINT: Quitting..." ); 90 | 91 | // Tear down the processing loop and stop iotivity 92 | clearInterval( intervalId ); 93 | iotivity.OCDeleteResource( handleReceptacle.handle ); 94 | iotivity.OCStop(); 95 | 96 | // Exit 97 | process.exit( 0 ); 98 | } ); 99 | -------------------------------------------------------------------------------- /js/server.get.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as server.get.js 19 | sampleUri = "/a/iotivity-node-get-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in server mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 26 | 27 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 28 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 29 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 30 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "abc.0.0.1" ); 31 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 32 | iotivity.OC_RSRVD_DEVICE_NAME, "server.get" ); 33 | 34 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 35 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 36 | 37 | intervalId = setInterval( function() { 38 | iotivity.OCProcess(); 39 | }, 1000 ); 40 | 41 | console.log( "Registering resource" ); 42 | 43 | // Create a new resource 44 | iotivity.OCCreateResource( 45 | 46 | // The bindings fill in this object 47 | handleReceptacle, 48 | 49 | "core.fan", 50 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 51 | sampleUri, 52 | function( flag, request ) { 53 | console.log( "Entity handler called with flag = " + flag + " and the following request:" ); 54 | console.log( JSON.stringify( request, null, 4 ) ); 55 | 56 | // If we find the magic question in the request, we return the magic answer 57 | if ( request && request.payload && request.payload.values && 58 | request.payload.values.question === 59 | "How many angels can dance on the head of a pin?" ) { 60 | 61 | iotivity.OCDoResponse( { 62 | requestHandle: request.requestHandle, 63 | resourceHandle: request.resource, 64 | ehResult: iotivity.OCEntityHandlerResult.OC_EH_OK, 65 | payload: { 66 | type: iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION, 67 | values: { 68 | "answer": "As many as wanting." 69 | } 70 | }, 71 | resourceUri: sampleUri, 72 | sendVendorSpecificHeaderOptions: [] 73 | } ); 74 | 75 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 76 | } 77 | 78 | // By default we error out 79 | return iotivity.OCEntityHandlerResult.OC_EH_ERROR; 80 | }, 81 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 82 | 83 | console.log( "Server ready" ); 84 | 85 | // Exit gracefully when interrupted 86 | process.on( "SIGINT", function() { 87 | console.log( "SIGINT: Quitting..." ); 88 | 89 | // Tear down the processing loop and stop iotivity 90 | clearInterval( intervalId ); 91 | iotivity.OCDeleteResource( handleReceptacle.handle ); 92 | iotivity.OCStop(); 93 | 94 | // Exit 95 | process.exit( 0 ); 96 | } ); 97 | -------------------------------------------------------------------------------- /js/server.presence.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var intervalId, 16 | handleReceptacle = {}, 17 | 18 | // This is the same value as client.presence.js 19 | sampleUri = "/a/iotivity-node-presence-sample", 20 | iotivity = require( "iotivity-node/lowlevel" ); 21 | 22 | console.log( "Starting OCF stack in server mode" ); 23 | 24 | // Start iotivity and set up the processing loop 25 | iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 26 | 27 | intervalId = setInterval( function() { 28 | iotivity.OCProcess(); 29 | }, 1000 ); 30 | 31 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 32 | iotivity.OC_RSRVD_SPEC_VERSION, "res.1.1.0" ); 33 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 34 | iotivity.OC_RSRVD_DATA_MODEL_VERSION, "test.0.0.1" ); 35 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_DEVICE, 36 | iotivity.OC_RSRVD_DEVICE_NAME, "server.presence" ); 37 | 38 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType.PAYLOAD_TYPE_PLATFORM, 39 | iotivity.OC_RSRVD_MFG_NAME, "iotivity-node" ); 40 | 41 | console.log( "Registering resource" ); 42 | 43 | // Create a new resource 44 | iotivity.OCCreateResource( 45 | 46 | // The bindings fill in this object 47 | handleReceptacle, 48 | 49 | "core.fan", 50 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 51 | sampleUri, 52 | function( flag, request ) { 53 | console.log( "Entity handler called with flag = " + flag + " and the following request:" ); 54 | console.log( JSON.stringify( request, null, 4 ) ); 55 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 56 | }, 57 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 58 | 59 | // Read keystrokes from stdin 60 | var stdin = process.stdin; 61 | 62 | stdin.setRawMode( true ); 63 | stdin.resume(); 64 | stdin.setEncoding( "utf8" ); 65 | stdin.on( "data", function( key ) { 66 | var result; 67 | 68 | switch ( key ) { 69 | 70 | case "p": 71 | result = iotivity.OCStartPresence( 0 ); 72 | console.log( "OCStartPresence: " + result ); 73 | break; 74 | 75 | case "s": 76 | result = iotivity.OCStopPresence(); 77 | console.log( "OCStopPresence: " + result ); 78 | break; 79 | 80 | // ^C 81 | case "\u0003": 82 | 83 | // Tear down the processing loop and stop iotivity 84 | clearInterval( intervalId ); 85 | iotivity.OCDeleteResource( handleReceptacle.handle ); 86 | iotivity.OCStopPresence(); 87 | iotivity.OCStop(); 88 | 89 | // Exit 90 | process.exit( 0 ); 91 | break; 92 | 93 | default: 94 | return; 95 | } 96 | 97 | console.log( "Press 'p' to turn on presence\nPress 's' to turn off presence\n" + 98 | "Press Ctrl+C to exit" ); 99 | } ); 100 | 101 | console.log( "Press 'p' to turn on presence\nPress 's' to turn off presence\n" + 102 | "Press Ctrl+C to exit" ); 103 | -------------------------------------------------------------------------------- /lib/BackedObject.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var assignIn = require( "lodash.assignin" ); 16 | 17 | function accessors( instance, property, value, backer ) { 18 | return { 19 | get: function() { 20 | return value; 21 | }, 22 | set: function( newValue ) { 23 | var result; 24 | var toCommit = assignIn( {}, instance ); 25 | 26 | toCommit[ property ] = newValue; 27 | 28 | result = backer( toCommit ); 29 | if ( result instanceof Error ) { 30 | throw result; 31 | } 32 | 33 | value = newValue; 34 | } 35 | }; 36 | } 37 | 38 | function BackedObject( object, backer ) { 39 | var index; 40 | 41 | if ( !( this instanceof BackedObject ) ) { 42 | return new BackedObject( object, backer ); 43 | } 44 | 45 | for ( index in object ) { 46 | Object.defineProperty( this, index, assignIn( { 47 | enumerable: true 48 | }, accessors( this, index, object[ index ], backer ) ) ); 49 | } 50 | } 51 | 52 | module.exports = assignIn( BackedObject, { 53 | attach: function( object, property, value, backer, wasSet ) { 54 | var index; 55 | var keys = []; 56 | 57 | for ( index in value ) { 58 | keys.push( index ); 59 | } 60 | value = BackedObject( value, backer ); 61 | 62 | Object.defineProperty( object, property, { 63 | enumerable: true, 64 | get: function() { 65 | return value; 66 | }, 67 | set: function( newValue ) { 68 | var result, index; 69 | var actualValue = {}; 70 | 71 | for ( index in keys ) { 72 | actualValue[ keys[ index ] ] = newValue[ keys[ index ] ] || null; 73 | } 74 | 75 | newValue = BackedObject( actualValue, backer ); 76 | if ( wasSet ) { 77 | wasSet( newValue ); 78 | } 79 | 80 | result = backer( newValue ); 81 | if ( result instanceof Error ) { 82 | throw result; 83 | } 84 | 85 | value = newValue; 86 | } 87 | } ); 88 | if ( wasSet ) { 89 | wasSet( value ); 90 | } 91 | 92 | return value; 93 | } 94 | } ); 95 | -------------------------------------------------------------------------------- /lib/Request.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var assignIn = require( "lodash.assignin" ); 16 | var doAPI = require( "./doAPI" ); 17 | var csdk = require( "./csdk" ); 18 | var payload = require( "./payload" ); 19 | var ServerResource = require( "./ServerResource" ); 20 | 21 | function respond( request, error, data ) { 22 | var responsePayload = null; 23 | var resourceHandle = request.target ? request.target._private.handle : null; 24 | 25 | // Special case: The server has decided to throw out an observer because of a network failure 26 | // encountered while attempting to deliver a notification. In that case, we do nothing. 27 | if ( !request.id && request.observe === false ) { 28 | return Promise.resolve(); 29 | } 30 | 31 | resourceHandle = ( ( resourceHandle && resourceHandle.stale ) ? null : resourceHandle ); 32 | 33 | if ( !error ) { 34 | if ( !data && request.type === "retrieve" ) { 35 | data = request.target.properties; 36 | } 37 | 38 | responsePayload = ( request.type === "create" ) ? 39 | ( data ? 40 | payload.initToCreateRequestPayload( data ) : 41 | new Error( "create: missing payload" ) ) : 42 | ( data ? 43 | payload.objectToRepPayload( 44 | data instanceof ServerResource ? 45 | data._private.translate( request.options ) : 46 | request.target._private.translate( request.options ) ) : 47 | null ); 48 | 49 | if ( responsePayload instanceof Error ) { 50 | error = responsePayload; 51 | responsePayload = null; 52 | } 53 | } 54 | 55 | var response = { 56 | requestHandle: request.id, 57 | resourceHandle: resourceHandle, 58 | ehResult: csdk.OCEntityHandlerResult[ 59 | error ? "OC_EH_ERROR" : 60 | request.type === "create" ? "OC_EH_RESOURCE_CREATED" : 61 | request.type === "delete" ? "OC_EH_RESOURCE_DELETED" : 62 | "OC_EH_OK" 63 | ], 64 | payload: responsePayload, 65 | sendVendorSpecificHeaderOptions: [], 66 | resourceUri: request.target ? request.target.resourcePath : data.resourcePath 67 | }; 68 | 69 | return doAPI( "OCDoResponse", "Failed to send response", response ) 70 | .catch( function( error ) { 71 | return Promise.reject( assignIn( error, { 72 | request: request, 73 | response: response 74 | } ) ); 75 | } ); 76 | } 77 | 78 | function Request( init ) { 79 | if ( !( this instanceof Request ) ) { 80 | return new Request( init ); 81 | } 82 | assignIn( this, init ); 83 | } 84 | 85 | assignIn( Request.prototype, { 86 | respond: function( data ) { 87 | return respond( this, null, data ); 88 | }, 89 | respondWithError: function( error ) { 90 | return respond( this, error ); 91 | } 92 | } ); 93 | 94 | module.exports = Request; 95 | -------------------------------------------------------------------------------- /lib/Resolver.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var _ = { 16 | extend: require( "lodash.assignin" ), 17 | findKey: require( "lodash.findkey" ), 18 | isEqual: require( "lodash.isequal" ) 19 | }; 20 | var Resolver = function() { 21 | if ( !( this instanceof Resolver ) ) { 22 | return new Resolver(); 23 | } 24 | 25 | // deviceId -> address 26 | this._addresses = {}; 27 | }; 28 | _.extend( Resolver.prototype, { 29 | add: function( deviceId, address ) { 30 | this._addresses[ deviceId ] = address; 31 | }, 32 | remove: function( item ) { 33 | delete this._addresses[ typeof item === "string" ? item : 34 | _.findKey( this._addresses, function( value ) { 35 | return _.isEqual( value, item ); 36 | } ) ]; 37 | }, 38 | get: function( item ) { 39 | return ( typeof item === "string" ? this._addresses[ item ] : 40 | _.findKey( this._addresses, function( value ) { 41 | return _.isEqual( value, item ); 42 | } ) ) || _.extend( new Error( "Device not found" ), { 43 | given: item 44 | } ); 45 | } 46 | } ); 47 | 48 | module.exports = new Resolver(); 49 | -------------------------------------------------------------------------------- /lib/StorageHandler.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Persistent storage handler 16 | // 17 | // Creates a directory structure of the following form: 18 | // ${HOME}/.iotivity-node 19 | // | 20 | // +-- 21 | // | 22 | // +-- 23 | // | 24 | // ... 25 | // | 26 | // +-- 27 | // is constructed from process.argv[1] by replacing '/' and ':' characters with 28 | // underscores. 29 | // 30 | // File names passed to open have no path component, so they will be created under 31 | // ${HOME}/.iotivity-node/ 32 | 33 | var assignIn = require( "lodash.assignin" ), 34 | fs = require( "fs" ), 35 | path = require( "path" ), 36 | configurationDirectory = require( "./configurationDirectory" ), 37 | StorageHandler = function StorageHandler() { 38 | if ( !( this instanceof StorageHandler ) ) { 39 | return new StorageHandler(); 40 | } 41 | this._directory = configurationDirectory(); 42 | }; 43 | 44 | assignIn( StorageHandler.prototype, { 45 | open: function( filename, mode ) { 46 | var fd, 47 | absolutePath = path.join( this._directory, filename ); 48 | 49 | mode = mode.replace( /b/g, "" ); 50 | 51 | // If the requested file does not exist, create it 52 | try { 53 | fd = fs.openSync( absolutePath, "wx" ); 54 | fs.closeSync( fd ); 55 | } catch ( theError ) { 56 | if ( theError.message.substr( 0, 6 ) !== "EEXIST" ) { 57 | throw theError; 58 | } 59 | } 60 | 61 | // Open the file in the requested mode 62 | fd = fs.openSync( absolutePath, mode ); 63 | fd = ( fd === undefined ? -1 : fd ); 64 | return fd; 65 | }, 66 | close: function( fp ) { 67 | fs.closeSync( fp ); 68 | return 0; 69 | }, 70 | read: function( buffer, totalSize, fp ) { 71 | return fs.readSync( fp, buffer, 0, totalSize, null ); 72 | }, 73 | write: function( buffer, totalSize, fp ) { 74 | return fs.writeSync( fp, buffer, 0, totalSize, null ); 75 | }, 76 | unlink: function( path ) { 77 | fs.unlinkSync( path ); 78 | return 0; 79 | } 80 | } ); 81 | 82 | module.exports = StorageHandler; 83 | -------------------------------------------------------------------------------- /lib/configurationDirectory.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Configuration directory 16 | // 17 | // Creates a directory structure of the following form: 18 | // ${HOME}/.iotivity-node 19 | // | 20 | // +-- 21 | // | 22 | // +-- 23 | // | 24 | // ... 25 | // | 26 | // +-- 27 | // is the sha256sum of the absolute filename of the main Node.js module. 28 | 29 | var path = require( "path" ); 30 | var sha = require( "sha.js" ); 31 | var osenv = require( "osenv" ); 32 | var shelljs = require( "shelljs" ); 33 | 34 | function configurationDirectory( mainPath ) { 35 | var myDirectory = path.join( osenv.home(), ".iotivity-node", 36 | 37 | // Absent a path that was passed in as mainPath, we hash the absolute path to the top-level 38 | // script to create the directory where we store the files for this instance. If no top 39 | // level script is found, we construct a path using the current working directory and the 40 | // process id. 41 | sha( "sha256" ) 42 | .update( mainPath || 43 | require.main && require.main.filename || 44 | path.join( process.cwd(), ( "" + process.pid ) ), "utf8" ) 45 | .digest( "hex" ) ); 46 | 47 | shelljs.mkdir( "-p", myDirectory ); 48 | 49 | return myDirectory; 50 | } 51 | 52 | module.exports = configurationDirectory; 53 | -------------------------------------------------------------------------------- /lib/csdk.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var iotivity = require( "bindings" )( "iotivity" ); 16 | var StorageHandler = require( "./StorageHandler" ); 17 | 18 | function stackOKOrThrow( result, message ) { 19 | var theError; 20 | 21 | if ( result !== iotivity.OCStackResult.OC_STACK_OK ) { 22 | theError = new Error( message ); 23 | theError.result = result; 24 | throw theError; 25 | } 26 | } 27 | 28 | stackOKOrThrow( iotivity.OCRegisterPersistentStorageHandler( new StorageHandler() ), 29 | "OCRegisterPersistentStorageHandler() failed" ); 30 | stackOKOrThrow( iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT_SERVER ), "OCInit() failed" ); 31 | stackOKOrThrow( iotivity.OCStartPresence( 0 ), "OCStartPresence() failed" ); 32 | setInterval( function() { 33 | var result; 34 | 35 | // This catches errors thrown from native callbacks - for example, if the JS callback return 36 | // value fails validation 37 | try { 38 | result = iotivity.OCProcess(); 39 | } catch ( theError ) { 40 | throw theError; 41 | } 42 | stackOKOrThrow( result, "OCProcess() failed" ); 43 | }, 100 ); 44 | 45 | module.exports = iotivity; 46 | -------------------------------------------------------------------------------- /lib/doAPI.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var assignIn = require( "lodash.assignin" ); 16 | var csdk = require( "./csdk" ); 17 | 18 | // api: The API to call. 19 | // error: The message of the Error with which to reject 20 | // The rest of the arguments are passed to the API requested. 21 | function doAPI( api, error ) { 22 | var apiArguments = Array.prototype.slice.call( arguments, 2 ); 23 | return new Promise( function( fulfill, reject ) { 24 | var result = csdk[ api ].apply( this, apiArguments ); 25 | if ( result === csdk.OCStackResult.OC_STACK_OK ) { 26 | fulfill(); 27 | } else { 28 | reject( assignIn( new Error( error ), { 29 | result: result 30 | } ) ); 31 | } 32 | } ); 33 | } 34 | 35 | module.exports = doAPI; 36 | -------------------------------------------------------------------------------- /lib/establishDestination.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Prefer an endpoint to a resource address if an endpoint is given. 16 | module.exports = function establishDestination( resourceId, endpoint ) { 17 | return endpoint ? { 18 | deviceId: null, 19 | requestUri: endpoint.origin + resourceId.requestUri 20 | } : resourceId; 21 | }; 22 | -------------------------------------------------------------------------------- /lib/listenerCount.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var EventEmitter = require( "events" ).EventEmitter; 16 | 17 | module.exports = function listenerCount( emitter, event ) { 18 | return ( typeof emitter.listenerCount === "function" ) ? 19 | emitter.listenerCount( event ) : 20 | EventEmitter.listenerCount( emitter, event ); 21 | }; 22 | -------------------------------------------------------------------------------- /lowlevel.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // Return the low-level API 16 | module.exports = require( "bindings" )( "iotivity" ); 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "iotivity-node", 3 | "version": "1.3.1-2", 4 | "description": "IoTivity bindings", 5 | "repository": "https://github.com/otcshare/iotivity-node/", 6 | "license": "Apache-2.0", 7 | "main": "index.js", 8 | "engines": { 9 | "node": ">0.10" 10 | }, 11 | "keywords": [ 12 | "oic", 13 | "iotivity", 14 | "iot" 15 | ], 16 | "scripts": { 17 | "test": "grunt test", 18 | "postinstall": "node build-scripts/postinstall.js" 19 | }, 20 | "gypfile": true, 21 | "dependencies": { 22 | "bindings": "~1.2.1", 23 | "lodash.assignin": "^4.0.0", 24 | "lodash.bind": "^4.0.0", 25 | "lodash.bindkey": "^4.0.0", 26 | "lodash.find": "^4.0.0", 27 | "lodash.findindex": "^4.0.0", 28 | "lodash.findkey": "^4.0.0", 29 | "lodash.flattendeep": "^4.0.0", 30 | "lodash.foreach": "^4.0.0", 31 | "lodash.isequal": "^4.0.0", 32 | "lodash.isnil": "^4.0.0", 33 | "lodash.map": "^4.0.0", 34 | "lodash.mergewith": "^4.0.0", 35 | "lodash.omitby": "^4.0.0", 36 | "lodash.pick": "^4.0.0", 37 | "lodash.remove": "^4.0.0", 38 | "lodash.uniq": "^4.0.0", 39 | "lodash.without": "^4.0.0", 40 | "node-addon-api": "^1.2.0", 41 | "osenv": "^0.1.3", 42 | "sha.js": "^2.4.4", 43 | "shelljs": "^0.5.3" 44 | }, 45 | "devDependencies": { 46 | "async": "^0.9.0", 47 | "commitplease": "^2.7.10", 48 | "esformatter-jquery-chain": "^1.1.0", 49 | "eslint-config-jquery": "0.1.2", 50 | "glob": "^7.1.1", 51 | "grunt": "^0.4.5", 52 | "grunt-contrib-clean": "^1.0.0", 53 | "grunt-coveralls": "^1.0.1", 54 | "grunt-esformatter": "^1.0.1", 55 | "grunt-eslint": "18.1.0", 56 | "grunt-istanbul": "^0.7.1", 57 | "iot-js-api": "git+https://github.com/intel/iot-js-api/#65d6995a15756715ec69a5e2ac4a644aca3c623d", 58 | "istanbul": "^0.4.5", 59 | "load-grunt-config": "^0.17.2", 60 | "load-grunt-tasks": "^3.2.0", 61 | "lodash.zipobject": "^4.0.0", 62 | "qunitjs": "^1.18.0", 63 | "uuid": "^2.0.1" 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /patches/0001-remove-windows-WX.patch: -------------------------------------------------------------------------------- 1 | diff --git a/build_common/windows/SConscript b/build_common/windows/SConscript 2 | index fbd8b8d11..4f1b09a3f 100644 3 | --- a/build_common/windows/SConscript 4 | +++ b/build_common/windows/SConscript 5 | @@ -159,7 +159,7 @@ if env['CC'] == 'cl': 6 | '/wd4232', '/wd4503', '/wd4512', '/wd4706']) 7 | 8 | # Enabling /W4 warnings globally for Windows builds. 9 | - env.AppendUnique(CCFLAGS=['/W4', '/WX']) 10 | + env.AppendUnique(CCFLAGS=['/W4']) 11 | env.AppendUnique(CCFLAGS=['/EHsc']) 12 | 13 | # Set release/debug flags 14 | -------------------------------------------------------------------------------- /patches/0002-fix-logger.patch: -------------------------------------------------------------------------------- 1 | diff --git a/resource/csdk/logger/src/logger.c b/resource/csdk/logger/src/logger.c 2 | index e7a80d8e1..f0d479dd2 100644 3 | --- a/resource/csdk/logger/src/logger.c 4 | +++ b/resource/csdk/logger/src/logger.c 5 | @@ -30,6 +30,7 @@ 6 | #define _POSIX_C_SOURCE 200809L 7 | #endif 8 | 9 | +#include 10 | #include "iotivity_config.h" 11 | 12 | // Pull in _POSIX_TIMERS feature test macro to check for 13 | @@ -328,7 +329,7 @@ void OCLog(int level, const char * tag, const char * logStr) 14 | ms = now.tv_usec * 1000; 15 | } 16 | #endif 17 | - printf("%02d:%02d.%03d %s: %s: %s\n", min, sec, ms, LEVEL[level], tag, logStr); 18 | + fprintf(stderr, "%s: %02d:%02d.%03d %s: %s: %s\n", getenv("LOG_PREFIX"), min, sec, ms, LEVEL[level], tag, logStr); 19 | } 20 | #endif 21 | } 22 | -------------------------------------------------------------------------------- /patches/0003-remove-dependencies.patch: -------------------------------------------------------------------------------- 1 | diff --git a/SConstruct b/SConstruct 2 | index 0da7e319c..75d0372ab 100644 3 | --- a/SConstruct 4 | +++ b/SConstruct 5 | @@ -62,40 +62,3 @@ build_dir = env.get('BUILD_DIR') 6 | 7 | # Build 'resource' sub-project 8 | SConscript(build_dir + 'resource/SConscript') 9 | - 10 | -if target_os not in ['arduino','darwin','ios', 'android', 'msys_nt', 'windows']: 11 | - SConscript(build_dir + 'examples/OICMiddle/SConscript') 12 | - 13 | -java_build = None 14 | -if (env.get('BUILD_JAVA') and env.get('JAVA_HOME')) or target_os == 'android': 15 | - java_build = SConscript(build_dir + 'java/SConscript') 16 | - 17 | -# Build 'service' sub-project 18 | -service_build = SConscript(build_dir + 'service/SConscript') 19 | - 20 | -if java_build: 21 | - Depends(service_build, java_build) 22 | - 23 | -# Build other sub-projects 24 | -SConscript(dirs=[ 25 | - build_dir + 'cloud', 26 | - build_dir + 'plugins', 27 | - build_dir + 'bridging', 28 | -]) 29 | - 30 | -# Append target information to the help information (if needed) 31 | -# To see help info, execute: 32 | -# $ scons [options] -h 33 | -# Note some help is option-dependent, e.g. java-related options are 34 | -# not added to the help unless BUILD_JAVA is seen 35 | -# 36 | -# This is not really needed unless requesting help, consider adding check: 37 | -#if env.GetOption('help'): 38 | -env.PrintTargets() 39 | - 40 | -# Print bin upload command line (arduino only) 41 | -if target_os == 'arduino': 42 | - env.UploadHelp() 43 | - 44 | -# to install the generated pc file into custom prefix location 45 | -env.UserInstallTargetPCFile('iotivity.pc', 'iotivity.pc') 46 | diff --git a/resource/SConscript b/resource/SConscript 47 | index 3ec59999c..c11173486 100644 48 | --- a/resource/SConscript 49 | +++ b/resource/SConscript 50 | @@ -42,21 +42,3 @@ SConscript('csdk/SConscript') 51 | if target_os not in ['arduino', 'darwin', 'ios']: 52 | # Build liboc_logger 53 | SConscript('oc_logger/SConscript') 54 | - 55 | - # Build liboc 56 | - SConscript('src/SConscript') 57 | - 58 | -if target_os in ['windows', 'linux']: 59 | - # Build IoTivity Procedural Client API 60 | - SConscript('IPCA/SConscript') 61 | - 62 | -if target_os not in ['arduino','darwin','ios','android']: 63 | - # Build examples 64 | - SConscript('examples/SConscript') 65 | - 66 | -if target_os in ['linux', 'windows', 'darwin', 'msys_nt']: 67 | - if target_os == 'darwin': 68 | - env.Command('#/out/darwin/iotivity-csdk.framework', None, '#/tools/darwin/mkfwk_osx.sh') 69 | - 70 | - # Build C/C++ unit tests 71 | - SConscript('unit_tests.scons') 72 | diff --git a/resource/csdk/resource-directory/SConscript b/resource/csdk/resource-directory/SConscript 73 | index f28a5f3db..857eb04ad 100644 74 | --- a/resource/csdk/resource-directory/SConscript 75 | +++ b/resource/csdk/resource-directory/SConscript 76 | @@ -125,15 +125,3 @@ if 'SERVER' in rd_mode: 77 | 'include/rd_server.h', 'resource', 'rd_server.h') 78 | rd_env.UserInstallTargetHeader( 79 | 'include/rd_database.h', 'resource', 'rd_database.h') 80 | - 81 | -###################################################################### 82 | -# Samples for the resource directory 83 | -###################################################################### 84 | -if target_os in ['linux']: 85 | - SConscript('samples/SConscript') 86 | - 87 | -###################################################################### 88 | -# Build UnitTests of the Resource Directory 89 | -################################################ ###################### 90 | -if target_os in ['linux']: 91 | - SConscript('unittests/SConscript') 92 | -------------------------------------------------------------------------------- /patches/0004-darwin-needs-sqlite-too.patch: -------------------------------------------------------------------------------- 1 | diff --git a/extlibs/sqlite3/SConscript b/extlibs/sqlite3/SConscript 2 | index 30e2184..c08fdda 100755 3 | --- a/extlibs/sqlite3/SConscript 4 | +++ b/extlibs/sqlite3/SConscript 5 | @@ -11,7 +11,7 @@ sqlite_env = env.Clone() 6 | target_os = sqlite_env.get('TARGET_OS') 7 | src_dir = sqlite_env.get('SRC_DIR') 8 | 9 | -targets_need_sqlite = ['android', 'msys_nt', 'windows', 'ios'] 10 | +targets_need_sqlite = ['android', 'msys_nt', 'windows', 'ios', 'darwin'] 11 | sqlite_dir = src_dir + '/extlibs/sqlite3/' 12 | sqlite_build_dir = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101/' 13 | sqlite_zip_file = src_dir + '/extlibs/sqlite3/sqlite-amalgamation-3081101.zip' 14 | -------------------------------------------------------------------------------- /patches/0005-remove-rd-cpp.patch: -------------------------------------------------------------------------------- 1 | diff --git a/resource/csdk/resource-directory/SConscript b/resource/csdk/resource-directory/SConscript 2 | index f28a5f3db..7f7edcedb 100644 3 | --- a/resource/csdk/resource-directory/SConscript 4 | +++ b/resource/csdk/resource-directory/SConscript 5 | @@ -54,7 +54,7 @@ if 'SERVER' in rd_mode: 6 | rd_env.AppendUnique(CPPDEFINES=['RD_SERVER']) 7 | 8 | rd_env.PrependUnique( 9 | - LIBS=['octbstack', 'oc', 'oc_logger', 'connectivity_abstraction']) 10 | + LIBS=['octbstack', 'oc_logger', 'connectivity_abstraction']) 11 | 12 | if target_os not in ['windows']: 13 | rd_env.AppendUnique( 14 | @@ -80,7 +80,6 @@ else: 15 | ###################################################################### 16 | RD_SRC_DIR = 'src/' 17 | rd_src_c = [] 18 | -rd_src_cpp = [] 19 | 20 | if 'SERVER' in rd_mode: 21 | rd_src_c += [ 22 | @@ -95,19 +94,13 @@ if 'CLIENT' in rd_mode: 23 | 24 | rd_src_all = rd_src_c 25 | 26 | -if target_os not in ['arduino', 'darwin', 'ios']: 27 | - rd_src_cpp += [RD_SRC_DIR + 'RDClient.cpp'] 28 | - if 'CLIENT' in rd_mode: 29 | - rd_src_all += rd_src_cpp 30 | - 31 | if target_os not in ['arduino', 'darwin', 'ios', 'msys_nt', 'windows']: 32 | rdsdk_shared = rd_env.SharedLibrary('resource_directory', rd_src_all) 33 | rdsdk_static = rd_env.StaticLibrary('resource_directory', rd_src_all) 34 | rdsdk = Flatten([rdsdk_static, rdsdk_shared]) 35 | elif target_os in ['msys_nt', 'windows']: 36 | rdsdk_c = rd_env.StaticLibrary('resource_directory_internal', rd_src_c) 37 | - rdsdk_cpp = rd_env.StaticLibrary('resource_directory', rd_src_cpp) 38 | - rdsdk = Flatten([rdsdk_c, rdsdk_cpp]) 39 | + rdsdk = Flatten([rdsdk_c]) 40 | else: 41 | rdsdk = rd_env.StaticLibrary('resource_directory', rd_src_all) 42 | 43 | -------------------------------------------------------------------------------- /src/common.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "common.h" 18 | 19 | NapiHandleScope::NapiHandleScope(napi_env _env) : scope(nullptr), env(_env) {} 20 | 21 | std::string NapiHandleScope::open() { 22 | NAPI_CALL_RETURN(env, napi_open_handle_scope(env, &scope)); 23 | return std::string(); 24 | } 25 | 26 | NapiHandleScope::~NapiHandleScope() { 27 | if (scope) { 28 | NAPI_CALL(env, napi_close_handle_scope(env, scope), THROW_BODY(env, )); 29 | } 30 | } 31 | 32 | std::string js_StringArray(napi_env env, OCStringLL *source, napi_value *ar) { 33 | size_t count; 34 | OCStringLL *item; 35 | napi_value val; 36 | 37 | for (item = source, count = 0; item; item = item->next, count++) 38 | ; 39 | NAPI_CALL_RETURN(env, napi_create_array_with_length(env, count, ar)); 40 | for (item = source, count = 0; item; item = item->next, count++) { 41 | DECLARE_HANDLE_SCOPE(scope, env, LOCAL_MESSAGE("failed to open scope")); 42 | NAPI_CALL_RETURN(env, napi_create_string_utf8(env, item->value, -1, &val)); 43 | NAPI_CALL_RETURN(env, napi_set_element(env, *ar, count, val)); 44 | } 45 | return std::string(); 46 | } 47 | 48 | std::string js_ArrayFromBytes(napi_env env, unsigned char *bytes, 49 | uint32_t length, napi_value *array) { 50 | uint32_t index; 51 | napi_value oneValue; 52 | NAPI_CALL_RETURN(env, napi_create_array_with_length(env, length, array)); 53 | for (index = 0; index < length; index++) { 54 | NAPI_CALL_RETURN( 55 | env, napi_create_uint32(env, (uint32_t)bytes[index], &oneValue)); 56 | NAPI_CALL_RETURN(env, napi_set_element(env, *array, index, oneValue)); 57 | } 58 | return std::string(); 59 | } 60 | 61 | std::string c_ArrayFromBytes(napi_env env, napi_value array, 62 | unsigned char *bytes, uint32_t length) { 63 | uint32_t index, arrayLength; 64 | napi_value oneValue; 65 | NAPI_CALL_RETURN(env, napi_get_array_length(env, array, &arrayLength)); 66 | for (index = 0; index < arrayLength; index++) { 67 | NAPI_CALL_RETURN(env, napi_get_element(env, array, index, &oneValue)); 68 | J2C_ASSIGN_VALUE_JS_RETURN( 69 | unsigned char, bytes[index], env, oneValue, napi_number, 70 | "byte array item " + std::to_string(index), uint32, uint32_t); 71 | } 72 | return std::string(); 73 | } 74 | -------------------------------------------------------------------------------- /src/constants.cc.in: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include "common.h" 19 | 20 | // The rest of this file is generated 21 | -------------------------------------------------------------------------------- /src/constants.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_CONSTANTS_H__ 18 | #define __IOTIVITY_NODE_CONSTANTS_H__ 19 | 20 | #include "common.h" 21 | 22 | std::string InitConstants(napi_env env, napi_value exports); 23 | 24 | #endif /* __IOTIVITY_NODE_CONSTANTS_H__ */ 25 | -------------------------------------------------------------------------------- /src/enums.cc.in: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "enums.h" 18 | 19 | extern "C" { 20 | #include 21 | } 22 | 23 | #define SET_CONSTANT(env, destination, name, type) \ 24 | C2J_SET_PROPERTY_RETURN((env), (destination), #name, type, name) 25 | 26 | #define SET_ENUM(env, destination, enumName) \ 27 | do { \ 28 | napi_value jsEnum; \ 29 | HELPER_CALL_RETURN(bind_##enumName((env), &jsEnum)); \ 30 | NAPI_CALL_RETURN((env), napi_set_named_property((env), (destination), \ 31 | #enumName, jsEnum)); \ 32 | } while (0) 33 | 34 | // The rest of this file is generated 35 | -------------------------------------------------------------------------------- /src/enums.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_ENUMS_H__ 18 | #define __IOTIVITY_NODE_ENUMS_H__ 19 | 20 | #include "common.h" 21 | 22 | std::string InitEnums(napi_env env, napi_value exports); 23 | 24 | #endif /* __IOTIVITY_NODE_ENUMS_H__ */ 25 | -------------------------------------------------------------------------------- /src/functions.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_FUNCTIONS_H__ 18 | #define __IOTIVITY_NODE_FUNCTIONS_H__ 19 | 20 | #include "common.h" 21 | 22 | #define SET_FUNCTION(env, destination, functionName) \ 23 | C2J_SET_PROPERTY_RETURN((env), (destination), #functionName, function, \ 24 | #functionName, NAPI_AUTO_LENGTH, \ 25 | bind_##functionName, 0) 26 | 27 | std::string InitFunctions(napi_env env, napi_value exports); 28 | 29 | #endif /* __IOTIVITY_NODE_FUNCTIONS_H__ */ 30 | -------------------------------------------------------------------------------- /src/functions/entity-handler.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "entity-handler.h" 18 | #include "../structures.h" 19 | 20 | std::string entityHandler(napi_env env, OCEntityHandlerFlag flag, 21 | OCEntityHandlerRequest *request, char *uri, 22 | napi_ref callback, OCEntityHandlerResult *result) { 23 | *result = OC_EH_ERROR; 24 | napi_value jsContext, jsCallback, jsReturnValue; 25 | NAPI_CALL_RETURN(env, napi_get_null(env, &jsContext)); 26 | NAPI_CALL_RETURN(env, napi_get_reference_value(env, callback, &jsCallback)); 27 | 28 | napi_value arguments[3]; 29 | NAPI_CALL_RETURN(env, napi_create_int32(env, (int32_t)flag, &arguments[0])); 30 | HELPER_CALL_RETURN(js_OCEntityHandlerRequest(env, request, &arguments[1])); 31 | if (uri) { 32 | NAPI_CALL_RETURN( 33 | env, napi_create_string_utf8(env, uri, strlen(uri), &arguments[2])); 34 | } 35 | 36 | NAPI_CALL_RETURN(env, 37 | napi_call_function(env, jsContext, jsCallback, (uri ? 3 : 2), 38 | arguments, &jsReturnValue)); 39 | 40 | J2C_ASSIGN_VALUE_JS_RETURN(OCEntityHandlerResult, *result, env, jsReturnValue, 41 | napi_number, "entity handler return value", uint32, 42 | uint32_t); 43 | return std::string(); 44 | } 45 | -------------------------------------------------------------------------------- /src/functions/entity-handler.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef _ENTITY_HANDLER_H_ 18 | #define _ENTITY_HANDLER_H_ 19 | 20 | extern "C" { 21 | #include 22 | } 23 | 24 | #include "../common.h" 25 | 26 | std::string entityHandler(napi_env env, OCEntityHandlerFlag flag, 27 | OCEntityHandlerRequest *request, char *uri, 28 | napi_ref callback, OCEntityHandlerResult *result); 29 | 30 | #define EH_BODY(env, flag, request, uri, callback) \ 31 | OCEntityHandlerResult result = OC_EH_ERROR; \ 32 | DECLARE_HANDLE_SCOPE(scope, ((env)), result); \ 33 | HELPER_CALL( \ 34 | entityHandler((env), (flag), (request), (uri), (callback), &result), \ 35 | THROW_BODY((env), result)); \ 36 | return result; 37 | 38 | #endif /* ndef _ENTITY_HANDLER_H_ */ 39 | -------------------------------------------------------------------------------- /src/functions/oc-server-resource-utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef _IOTIVITY_NODE_OC_SERVER_RESOURCE_UTILS_H_ 18 | #define _IOTIVITY_NODE_OC_SERVER_RESOURCE_UTILS_H_ 19 | 20 | #define DECLARE_HANDLE_DATA(varName, env, source, message) \ 21 | J2C_VALIDATE_VALUE_TYPE_THROW((env), (source), napi_object, message); \ 22 | JSOCResourceHandle *varName; \ 23 | HELPER_CALL_THROW((env), \ 24 | JSOCResourceHandle::Get((env), (source), &varName)); \ 25 | JS_ASSERT(varName, std::string() + message + " is invalid", \ 26 | THROW_BODY(env, 0)); 27 | 28 | #define FIRST_ARGUMENT_IS_HANDLE(argc) \ 29 | J2C_DECLARE_ARGUMENTS(env, info, argc); \ 30 | DECLARE_HANDLE_DATA(cData, env, arguments[0], "handle"); 31 | 32 | #endif /* ndef _IOTIVITY_NODE_OC_SERVER_RESOURCE_UTILS_H_ */ 33 | -------------------------------------------------------------------------------- /src/functions/oc-server-response.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "../common.h" 18 | #include "../structures/handles.h" 19 | #include "../structures/oc-entity-handler-response.h" 20 | #include "../structures/oc-rep-payload/to-c.h" 21 | #include "oc-server-resource-utils.h" 22 | 23 | extern "C" { 24 | #include 25 | #include 26 | } 27 | 28 | napi_value bind_OCDoResponse(napi_env env, napi_callback_info info) { 29 | J2C_DECLARE_ARGUMENTS(env, info, 1); 30 | J2C_VALIDATE_VALUE_TYPE_THROW(env, arguments[0], napi_object, "response"); 31 | OCEntityHandlerResponse resp; 32 | HELPER_CALL_THROW(env, c_OCEntityHandlerResponse(env, arguments[0], &resp)); 33 | std::unique_ptr payloadTracker( 34 | resp.payload, OCPayloadDestroy); 35 | OCStackResult result = OCDoResponse(&resp); 36 | C2J_SET_RETURN_VALUE(env, info, double, ((double)result)); 37 | } 38 | 39 | napi_value bind_OCNotifyListOfObservers(napi_env env, napi_callback_info info) { 40 | // handle 41 | FIRST_ARGUMENT_IS_HANDLE(4); 42 | 43 | // obsIdList and numberOfIds 44 | J2C_VALIDATE_IS_ARRAY_THROW(env, arguments[1], false, "observation ID list"); 45 | uint32_t obsCount, index; 46 | napi_value jsObsId; 47 | NAPI_CALL_THROW(env, napi_get_array_length(env, arguments[1], &obsCount)); 48 | std::unique_ptr observers(new OCObservationId[obsCount]()); 49 | for (index = 0; index < obsCount; index++) { 50 | NAPI_CALL_THROW(env, napi_get_element(env, arguments[1], index, &jsObsId)); 51 | J2C_ASSIGN_VALUE_JS( 52 | OCObservationId, observers.get()[index], env, jsObsId, napi_number, 53 | std::string("observation id[") + std::to_string(index) + "]", uint32, 54 | uint32_t, THROW_BODY(env, 0)); 55 | } 56 | 57 | // payload 58 | OCRepPayload *payload = nullptr; 59 | std::unique_ptr payloadTracker( 60 | nullptr, OCRepPayloadDestroy); 61 | DECLARE_VALUE_TYPE(payloadType, env, arguments[2], THROW_BODY(env, 0)); 62 | if (!(payloadType == napi_null || payloadType == napi_undefined)) { 63 | HELPER_CALL_THROW(env, c_OCRepPayload(env, arguments[2], &payload)); 64 | payloadTracker.reset(payload); 65 | } 66 | 67 | // qos 68 | J2C_DECLARE_VALUE_JS_THROW(OCQualityOfService, qos, env, arguments[3], 69 | napi_number, "qos", uint32, uint32_t); 70 | 71 | C2J_SET_RETURN_VALUE( 72 | env, info, double, 73 | ((double)OCNotifyListOfObservers(cData->data, observers.get(), 74 | (uint8_t)obsCount, payload, qos))); 75 | } 76 | -------------------------------------------------------------------------------- /src/functions/oc-set-default-device-entity-handler.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "../common.h" 18 | #include "entity-handler.h" 19 | 20 | extern "C" { 21 | #include 22 | #include 23 | } 24 | 25 | static napi_ref g_currentCallback = nullptr; 26 | static napi_env g_currentEnv = nullptr; 27 | 28 | static OCEntityHandlerResult defaultDeviceEntityHandler( 29 | OCEntityHandlerFlag flag, OCEntityHandlerRequest *request, char *uri, 30 | void *context) { 31 | EH_BODY(g_currentEnv, flag, request, uri, ((napi_ref)context)); 32 | } 33 | 34 | napi_value bind_OCSetDefaultDeviceEntityHandler(napi_env env, 35 | napi_callback_info info) { 36 | J2C_DECLARE_ARGUMENTS(env, info, 1); 37 | DECLARE_VALUE_TYPE(handlerType, env, arguments[0], THROW_BODY(env, 0)); 38 | 39 | OCDeviceEntityHandler newHandler = 0; 40 | napi_ref newCallback = 0, callbackToDelete = 0; 41 | if (handlerType == napi_function) { 42 | NAPI_CALL_THROW(env, 43 | napi_create_reference(env, arguments[0], 1, &newCallback)); 44 | newHandler = defaultDeviceEntityHandler; 45 | } 46 | OCStackResult result = 47 | OCSetDefaultDeviceEntityHandler(newHandler, (void *)newCallback); 48 | if (result == OC_STACK_OK) { 49 | callbackToDelete = g_currentCallback; 50 | g_currentCallback = newCallback; 51 | g_currentEnv = env; 52 | } else { 53 | callbackToDelete = newCallback; 54 | } 55 | if (callbackToDelete) { 56 | NAPI_CALL_THROW(env, napi_delete_reference(env, callbackToDelete)); 57 | } 58 | C2J_SET_RETURN_VALUE(env, info, double, ((double)result)); 59 | } 60 | -------------------------------------------------------------------------------- /src/main.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include "constants.h" 20 | #include "enums.h" 21 | #include "functions.h" 22 | #include "structures/handles.h" 23 | 24 | napi_value Init(napi_env env, napi_value exports) { 25 | HELPER_CALL(InitEnums(env, exports), THROW_BODY(env, NULL)); 26 | HELPER_CALL(InitConstants(env, exports), THROW_BODY(env, NULL)); 27 | HELPER_CALL(InitFunctions(env, exports), THROW_BODY(env, NULL)); 28 | return exports; 29 | } 30 | 31 | NAPI_MODULE(iotivity, Init) 32 | -------------------------------------------------------------------------------- /src/structures.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | extern "C" { 18 | #include 19 | } 20 | 21 | #include "common.h" 22 | #include "structures.h" 23 | #include "structures/handles.h" 24 | #include "structures/oc-dev-addr.h" 25 | #include "structures/oc-payload.h" 26 | 27 | std::string js_OCEntityHandlerRequest(napi_env env, 28 | OCEntityHandlerRequest *request, 29 | napi_value *result) { 30 | NAPI_CALL_RETURN(env, napi_create_object(env, result)); 31 | 32 | // The resource may be null if the request refers to a non-existing resource 33 | // and is being passed to the default device entity handler 34 | if (request->resource) { 35 | napi_ref jsRef = JSOCResourceHandle::handles[request->resource]; 36 | if (!jsRef) { 37 | return LOCAL_MESSAGE("resource handle not found"); 38 | } 39 | C2J_SET_PROPERTY_CALL_RETURN( 40 | env, *result, "resource", 41 | NAPI_CALL_RETURN(env, napi_get_reference_value(env, jsRef, &jsValue))); 42 | } 43 | 44 | if (request->requestHandle) { 45 | napi_value jsHandle; 46 | JSOCRequestHandle *cData; 47 | HELPER_CALL_RETURN(JSOCRequestHandle::New(env, &jsHandle, &cData)); 48 | cData->data = request->requestHandle; 49 | HELPER_CALL_RETURN(cData->Init(env, nullptr, jsHandle)); 50 | NAPI_CALL_RETURN( 51 | env, napi_set_named_property(env, *result, "requestHandle", jsHandle)); 52 | } else { 53 | C2J_SET_PROPERTY_CALL_RETURN( 54 | env, *result, "requestHandle", 55 | NAPI_CALL_RETURN(env, napi_get_null(env, &jsValue))); 56 | } 57 | 58 | C2J_SET_NUMBER_MEMBER_RETURN(env, *result, request, method); 59 | C2J_SET_PROPERTY_CALL_RETURN( 60 | env, *result, "devAddr", 61 | HELPER_CALL_RETURN(js_OCDevAddr(env, &(request->devAddr), &jsValue))); 62 | C2J_SET_STRING_IF_NOT_NULL_RETURN(env, *result, request, query); 63 | 64 | napi_value jsObsInfo; 65 | NAPI_CALL_RETURN(env, napi_create_object(env, &jsObsInfo)); 66 | C2J_SET_NUMBER_MEMBER_RETURN(env, jsObsInfo, &(request->obsInfo), action); 67 | C2J_SET_NUMBER_MEMBER_RETURN(env, jsObsInfo, &(request->obsInfo), obsId); 68 | NAPI_CALL_RETURN(env, 69 | napi_set_named_property(env, *result, "obsInfo", jsObsInfo)); 70 | 71 | C2J_SET_NUMBER_MEMBER_RETURN(env, *result, request, messageID); 72 | if (request->payload) { 73 | C2J_SET_PROPERTY_CALL_RETURN( 74 | env, *result, "payload", 75 | HELPER_CALL_RETURN(js_OCPayload(env, request->payload, &jsValue))); 76 | } 77 | 78 | // "rcvdVendorSpecificHeaderOptions" ignored 79 | 80 | return std::string(); 81 | } 82 | -------------------------------------------------------------------------------- /src/structures.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_STRUCTURES_H__ 18 | #define __IOTIVITY_NODE_STRUCTURES_H__ 19 | 20 | #include "common.h" 21 | 22 | extern "C" { 23 | #include 24 | } 25 | 26 | std::string js_OCEntityHandlerRequest(napi_env env, 27 | OCEntityHandlerRequest *request, 28 | napi_value *result); 29 | 30 | #endif /* __IOTIVITY_NODE_STRUCTURES_H__ */ 31 | -------------------------------------------------------------------------------- /src/structures/handles.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "handles.h" 18 | 19 | napi_value JSHandle_constructor(napi_env env, napi_callback_info info) { 20 | return 0; 21 | } 22 | 23 | std::map JSOCResourceHandle::handles; 24 | -------------------------------------------------------------------------------- /src/structures/oc-client-response.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "oc-client-response.h" 18 | #include "oc-dev-addr.h" 19 | #include "oc-identity.h" 20 | #include "oc-payload.h" 21 | 22 | extern "C" { 23 | #include 24 | } 25 | 26 | std::string js_OCClientResponse(napi_env env, OCClientResponse *source, 27 | napi_value *destination) { 28 | NAPI_CALL_RETURN(env, napi_create_object(env, destination)); 29 | 30 | C2J_SET_PROPERTY_CALL_RETURN( 31 | env, *destination, "devAddr", 32 | HELPER_CALL_RETURN(js_OCDevAddr(env, &(source->devAddr), &jsValue))); 33 | 34 | if (source->addr) { 35 | C2J_SET_PROPERTY_CALL_RETURN( 36 | env, *destination, "addr", 37 | HELPER_CALL_RETURN(js_OCDevAddr(env, source->addr, &jsValue))); 38 | } 39 | 40 | if (source->payload) { 41 | C2J_SET_PROPERTY_CALL_RETURN( 42 | env, *destination, "payload", 43 | HELPER_CALL_RETURN(js_OCPayload(env, source->payload, &jsValue))); 44 | } 45 | 46 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, connType); 47 | 48 | C2J_SET_PROPERTY_CALL_RETURN( 49 | env, *destination, "identity", 50 | HELPER_CALL_RETURN(js_OCIdentity(env, &(source->identity), &jsValue))); 51 | 52 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, result); 53 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, sequenceNumber); 54 | 55 | // FIXME - iotivity has a bug whereby these fields are left uninitialized in 56 | // a presence response 57 | if (!(source->payload && source->payload->type == PAYLOAD_TYPE_PRESENCE)) { 58 | C2J_SET_STRING_IF_NOT_NULL_RETURN(env, *destination, source, resourceUri); 59 | 60 | // vendor options are not set 61 | } 62 | return std::string(); 63 | } 64 | -------------------------------------------------------------------------------- /src/structures/oc-client-response.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_OCCLIENTRESPONSE_H__ 18 | #define __IOTIVITY_NODE_OCCLIENTRESPONSE_H__ 19 | 20 | #include "common.h" 21 | extern "C" { 22 | #include 23 | } 24 | 25 | std::string js_OCClientResponse(napi_env env, OCClientResponse *source, 26 | napi_value *destination); 27 | 28 | #endif /* __IOTIVITY_NODE_OCCLIENTRESPONSE_H__ */ 29 | -------------------------------------------------------------------------------- /src/structures/oc-dev-addr.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "oc-dev-addr.h" 18 | 19 | extern "C" { 20 | #include 21 | } 22 | 23 | std::string c_OCDevAddr(napi_env env, napi_value source, 24 | OCDevAddr *destination) { 25 | std::string returnValue; 26 | J2C_ASSIGN_MEMBER_VALUE_RETURN((env), destination, source, OCTransportAdapter, 27 | adapter, napi_number, "addr", uint32, 28 | uint32_t); 29 | J2C_ASSIGN_MEMBER_VALUE_RETURN((env), destination, source, OCTransportFlags, 30 | flags, napi_number, "addr", uint32, uint32_t); 31 | J2C_ASSIGN_MEMBER_VALUE_RETURN((env), destination, source, uint32_t, ifindex, 32 | napi_number, "addr", uint32, uint32_t); 33 | J2C_ASSIGN_MEMBER_VALUE_RETURN((env), destination, source, uint16_t, port, 34 | napi_number, "addr", uint32, uint32_t); 35 | char *addr = nullptr; 36 | J2C_GET_STRING_RETURN(env, addr, source, false, "addr"); 37 | if (strlen(addr) > MAX_ADDR_STR_SIZE) { 38 | returnValue = 39 | LOCAL_MESSAGE("OCDevAddr field 'addr' exceeds size MAX_ADDR_STR_SIZE"); 40 | } else { 41 | strcpy(destination->addr, addr); 42 | } 43 | delete addr; 44 | return returnValue; 45 | } 46 | 47 | std::string js_OCDevAddr(napi_env env, OCDevAddr *source, 48 | napi_value *destination) { 49 | NAPI_CALL_RETURN(env, napi_create_object(env, destination)); 50 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, adapter); 51 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, flags); 52 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, ifindex); 53 | C2J_SET_NUMBER_MEMBER_RETURN(env, *destination, source, port); 54 | C2J_SET_PROPERTY_RETURN(env, *destination, "addr", string_utf8, source->addr, 55 | strlen(source->addr)); 56 | return std::string(); 57 | } 58 | -------------------------------------------------------------------------------- /src/structures/oc-dev-addr.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_OCDEVADDR_H__ 18 | #define __IOTIVITY_NODE_OCDEVADDR_H__ 19 | 20 | #include "../common.h" 21 | 22 | extern "C" { 23 | #include 24 | } 25 | 26 | std::string c_OCDevAddr(napi_env env, napi_value source, 27 | OCDevAddr *destination); 28 | std::string js_OCDevAddr(napi_env env, OCDevAddr *source, 29 | napi_value *destination); 30 | 31 | #endif /* __IOTIVITY_NODE_OCDEVADDR_H__ */ 32 | -------------------------------------------------------------------------------- /src/structures/oc-entity-handler-response.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "oc-entity-handler-response.h" 18 | #include "../common.h" 19 | #include "handles.h" 20 | #include "oc-dev-addr.h" 21 | #include "oc-payload.h" 22 | 23 | extern "C" { 24 | #include 25 | #include 26 | } 27 | 28 | std::string c_OCEntityHandlerResponse(napi_env env, napi_value value, 29 | OCEntityHandlerResponse *response) { 30 | // requestHandle 31 | J2C_DECLARE_PROPERTY_JS_RETURN(requestHandle, env, value, "requestHandle"); 32 | JSOCRequestHandle *cRequestData; 33 | HELPER_CALL_RETURN(JSOCRequestHandle::Get(env, requestHandle, &cRequestData)); 34 | response->requestHandle = cRequestData->data; 35 | 36 | // resourceHandle 37 | response->resourceHandle = nullptr; 38 | J2C_DECLARE_PROPERTY_JS_RETURN(resourceHandle, env, value, "resourceHandle"); 39 | DECLARE_VALUE_TYPE(resHandleType, env, resourceHandle, FAIL_STATUS); 40 | if (!(resHandleType == napi_null || resHandleType == napi_undefined)) { 41 | JSOCResourceHandle *cResData; 42 | HELPER_CALL_RETURN(JSOCResourceHandle::Get(env, resourceHandle, &cResData)); 43 | response->resourceHandle = cResData->data; 44 | } 45 | 46 | // ehResult 47 | J2C_ASSIGN_MEMBER_VALUE_RETURN((env), response, value, OCEntityHandlerResult, 48 | ehResult, napi_number, "response", uint32, 49 | uint32_t); 50 | 51 | // header options are ignored 52 | response->numSendVendorSpecificHeaderOptions = 0; 53 | 54 | // resourceUri 55 | J2C_DECLARE_PROPERTY_JS_RETURN(resourceUri, env, value, "resourceUri"); 56 | J2C_VALIDATE_VALUE_TYPE_RETURN(env, resourceUri, napi_string, 57 | "response.resourceUri"); 58 | size_t len; 59 | NAPI_CALL_RETURN( 60 | env, napi_get_value_string_utf8(env, resourceUri, nullptr, 0, &len)); 61 | JS_ASSERT(len <= MAX_URI_LENGTH, 62 | "length of response.resourceUri exceeds MAX_URI_LENGTH", 63 | FAIL_STATUS); 64 | char *cResourceUri; 65 | J2C_GET_STRING_JS_RETURN(env, cResourceUri, resourceUri, false, 66 | "response.resourceUri"); 67 | strncpy(response->resourceUri, cResourceUri, MAX_URI_LENGTH - 1); 68 | free(cResourceUri); 69 | 70 | // persistent buffer flag is ignored 71 | response->persistentBufferFlag = false; 72 | 73 | // payload 74 | // This is the only deep property so we set it last. 75 | J2C_DECLARE_PROPERTY_JS_RETURN(jsPayload, env, value, "payload"); 76 | HELPER_CALL_RETURN(c_OCPayload(env, jsPayload, &(response->payload))); 77 | 78 | return std::string(); 79 | } 80 | -------------------------------------------------------------------------------- /src/structures/oc-entity-handler-response.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_OCENTITYHANDLERRESPONSE_H__ 18 | #define __IOTIVITY_NODE_OCENTITYHANDLERRESPONSE_H__ 19 | 20 | #include "../common.h" 21 | extern "C" { 22 | #include 23 | } 24 | 25 | std::string c_OCEntityHandlerResponse(napi_env env, napi_value value, 26 | OCEntityHandlerResponse *response); 27 | 28 | #endif /* __IOTIVITY_NODE_OCENTITYHANDLERRESPONSE_H__ */ 29 | -------------------------------------------------------------------------------- /src/structures/oc-identity.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "oc-identity.h" 18 | 19 | extern "C" { 20 | #include 21 | } 22 | 23 | std::string js_OCIdentity(napi_env env, OCIdentity *source, 24 | napi_value *destination) { 25 | HELPER_CALL_RETURN(js_ArrayFromBytes( 26 | env, source->id, (uint32_t)(source->id_length), destination)); 27 | return std::string(); 28 | } 29 | 30 | std::string c_OCIdentity(napi_env env, napi_value source, 31 | OCIdentity *destination) { 32 | uint32_t length; 33 | NAPI_CALL_RETURN(env, napi_get_array_length(env, source, &length)); 34 | if (length > MAX_IDENTITY_SIZE) { 35 | return LOCAL_MESSAGE("array length " + std::to_string(length) + 36 | " exceeds MAX_IDENTITY_SIZE(" + 37 | std::to_string(MAX_IDENTITY_SIZE) + ")"); 38 | } 39 | HELPER_CALL_RETURN(c_ArrayFromBytes(env, source, destination->id, length)); 40 | destination->id_length = (uint16_t)length; 41 | return std::string(); 42 | } 43 | -------------------------------------------------------------------------------- /src/structures/oc-identity.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_OCIDENTITY_H__ 18 | #define __IOTIVITY_NODE_OCIDENTITY_H__ 19 | 20 | #include "../common.h" 21 | extern "C" { 22 | #include 23 | } 24 | 25 | std::string c_OCIdentity(napi_env env, napi_value source, 26 | OCIdentity *destination); 27 | std::string js_OCIdentity(napi_env env, OCIdentity *source, 28 | napi_value *destination); 29 | 30 | #endif /* __IOTIVITY_NODE_OCIDENTITY_H__ */ 31 | -------------------------------------------------------------------------------- /src/structures/oc-payload-macros.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef _IOTIVITY_NODE_OC_PAYLOAD_MACROS_H_ 18 | #define _IOTIVITY_NODE_OC_PAYLOAD_MACROS_H_ 19 | 20 | #define C2J_SET_LL_PROPERTY(env, destination, source, name, type, createItem) \ 21 | if ((source)->name) { \ 22 | C2J_SET_PROPERTY_CALL_RETURN((env), (destination), #name, { \ 23 | uint32_t index; \ 24 | type current; \ 25 | napi_value item; \ 26 | NAPI_CALL_RETURN((env), napi_create_array((env), &jsValue)); \ 27 | for (index = 0, current = (source)->name; current; \ 28 | index++, current = current->next) { \ 29 | createItem; \ 30 | NAPI_CALL_RETURN((env), napi_set_element(env, jsValue, index, item)); \ 31 | } \ 32 | }); \ 33 | } 34 | 35 | #define C2J_SET_STRING_LL_PROPERTY(env, destination, source, name) \ 36 | C2J_SET_LL_PROPERTY( \ 37 | (env), (destination), (source), name, OCStringLL *, \ 38 | NAPI_CALL_RETURN( \ 39 | (env), napi_create_string_utf8((env), current->value, \ 40 | strlen(current->value), &item))); 41 | 42 | #define SET_TYPES_INTERFACES(env, destination, source, typeField, \ 43 | interfaceField) \ 44 | C2J_SET_STRING_LL_PROPERTY((env), (destination), (source), typeField); \ 45 | C2J_SET_STRING_LL_PROPERTY((env), (destination), (source), interfaceField); 46 | 47 | #endif /* ndef _IOTIVITY_NODE_OC_PAYLOAD_MACROS_H_ */ 48 | -------------------------------------------------------------------------------- /src/structures/oc-payload.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __IOTIVITY_NODE_OCPAYLOAD_H__ 18 | #define __IOTIVITY_NODE_OCPAYLOAD_H__ 19 | 20 | #include "../common.h" 21 | 22 | extern "C" { 23 | #include 24 | } 25 | 26 | std::string js_OCPayload(napi_env env, OCPayload *payload, napi_value *result); 27 | std::string c_OCPayload(napi_env env, napi_value source, 28 | OCPayload **destination); 29 | 30 | #endif /* __IOTIVITY_NODE_OCCLIENTRESPONSE_H__ */ 31 | -------------------------------------------------------------------------------- /src/structures/oc-rep-payload/to-c.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef _IOTIVITY_NODE_OC_REP_PAYLOAD_TO_C_H_ 18 | #define _IOTIVITY_NODE_OC_REP_PAYLOAD_TO_C_H_ 19 | 20 | #include "../../common.h" 21 | extern "C" { 22 | #include 23 | } 24 | 25 | std::string c_OCRepPayload(napi_env env, napi_value source, 26 | OCRepPayload **destination); 27 | 28 | #endif /* ndef _IOTIVITY_NODE_OC_REP_PAYLOAD_TO_C_H_ */ 29 | -------------------------------------------------------------------------------- /src/structures/oc-rep-payload/to-js.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef _IOTIVITY_NODE_OC_REP_PAYLOAD_TO_JS_H_ 18 | #define _IOTIVITY_NODE_OC_REP_PAYLOAD_TO_JS_H_ 19 | 20 | #include "../../common.h" 21 | extern "C" { 22 | #include 23 | } 24 | 25 | std::string js_OCRepPayload(napi_env env, OCRepPayload *payload, 26 | napi_value destination); 27 | 28 | #endif /* ndef _IOTIVITY_NODE_OC_REP_PAYLOAD_TO_JS_H_ */ 29 | -------------------------------------------------------------------------------- /tests/assert-to-console.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = { 16 | 17 | // Create an assertion and pass it to the parent process via stdout 18 | assert: function( assertion ) { 19 | var copyOfArguments; 20 | 21 | // Copy the arguments and remove the assertion 22 | copyOfArguments = Array.prototype.slice.call( arguments, 0 ); 23 | copyOfArguments.shift(); 24 | 25 | console.log( JSON.stringify( { 26 | assertion: assertion, 27 | arguments: copyOfArguments 28 | } ) ); 29 | }, 30 | 31 | info: function( message ) { 32 | console.log( JSON.stringify( { 33 | info: true, 34 | message: message 35 | } ) ); 36 | }, 37 | 38 | die: function( message ) { 39 | console.log( JSON.stringify( { teardown: true, message: message, isError: true } ) ); 40 | process.exit( 1 ); 41 | }, 42 | 43 | // ObjectName: A string describing the object - for example "OicDiscovery" 44 | // Object: The object to be examined 45 | // Properties: An array of objects containing two properties: 46 | // name: The name of the property which must be present on object 47 | // type: The name of the type the property must have 48 | // For example: 49 | // assertProperties( "OicDevice", device, [ 50 | // { name: "name", type: "string" }, 51 | // { name: "uuid", type: "string" }, 52 | // ... 53 | // ] ); 54 | assertProperties: function( objectName, object, properties ) { 55 | var index; 56 | for ( index in properties ) { 57 | this.assert( "ok", properties[ index ].name in object, 58 | objectName + " has " + properties[ index ].name ); 59 | if ( properties[ index ].type ) { 60 | this.assert( "strictEqual", 61 | properties[ index ].type === "array" ? 62 | ( Array.isArray( object[ properties[ index ].name ] ) ? 63 | "array" : "non-array" ) : 64 | typeof object[ properties[ index ].name ], 65 | properties[ index ].type, 66 | objectName + "." + properties[ index ].name + " is of type " + 67 | properties[ index ].type ); 68 | } 69 | 70 | } 71 | } 72 | }; 73 | -------------------------------------------------------------------------------- /tests/dlopennow.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016 Intel Corporation 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | extern "C" { 18 | #include 19 | } 20 | #include 21 | #include 22 | #include 23 | 24 | using namespace v8; 25 | 26 | NAN_METHOD( bind_dlopennow ) { 27 | void *theLibrary = 0; 28 | dlerror(); 29 | 30 | if ( !info[ 0 ]->IsString() ) { 31 | Nan::ThrowTypeError( "Argument must be a string" ); 32 | return; 33 | } 34 | 35 | theLibrary = dlopen( (const char *)*String::Utf8Value(info[0]), RTLD_NOW ); 36 | 37 | char *theError = dlerror(); 38 | 39 | if ( theError ) { 40 | if ( theLibrary ) { 41 | dlclose( theLibrary ); 42 | } 43 | info.GetReturnValue().Set( Nan::New( theError ).ToLocalChecked() ); 44 | return; 45 | } 46 | 47 | if ( theLibrary ) { 48 | dlclose( theLibrary ); 49 | } 50 | } 51 | 52 | NAN_MODULE_INIT(Init) { 53 | Nan::Set( target, Nan::New( "dlopennow" ).ToLocalChecked(), 54 | Nan::GetFunction( Nan::New( bind_dlopennow ) ).ToLocalChecked() ); 55 | } 56 | 57 | NODE_MODULE( dlopennow, Init ) 58 | -------------------------------------------------------------------------------- /tests/getresult.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var fs = require( "fs" ); 16 | var path = require( "path" ); 17 | 18 | var date = new Date(), 19 | caseList = [], 20 | setList = [], 21 | allList = [], 22 | test = {}, 23 | testInfo = {}; 24 | 25 | exports.getTestResult = function( status ) { 26 | testInfo = { 27 | "message": ( status.runtime + ": " + status.message ), 28 | "result": ( status.result ? "PASS" : "FAIL" ), 29 | "runtime": ( date.toLocaleTimeString() ) 30 | }; 31 | 32 | if ( setList.indexOf( status.name ) > -1 && ( "results" in test ) ) { 33 | test.results.push( testInfo ); 34 | caseList.push( test ); 35 | } else { 36 | setList.push( status.name ); 37 | test = { "test": status.name, "results": [ testInfo ] }; 38 | caseList.push( test ); 39 | allList.push( test ); 40 | } 41 | }; 42 | 43 | exports.saveResults = function( suiteName ) { 44 | fs.writeFileSync( 45 | path.join( __dirname, "results." + suiteName + ".json" ), 46 | JSON.stringify( { "output": allList }, null, 4 ) ); 47 | }; 48 | -------------------------------------------------------------------------------- /tests/istanbul.json: -------------------------------------------------------------------------------- 1 | { 2 | "hooks": { 3 | "handle-sigint": true 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /tests/provision/produceClientContent.js: -------------------------------------------------------------------------------- 1 | module.exports = function produceClientContent( item, creds ) { 2 | 3 | return { 4 | acl: { 5 | aclist2: [ 6 | { 7 | aceid: 1, 8 | subject: { conntype: "anon-clear" }, 9 | resources: [ 10 | { href: "/oic/res" }, 11 | { href: "/oic/d" }, 12 | { href: "/oic/p" }, 13 | { href: "/oic/sec/doxm" } 14 | ], 15 | permission: 2 16 | }, 17 | { 18 | aceid: 2, 19 | subject: { conntype: "auth-crypt" }, 20 | resources: [ 21 | { href: "/oic/res" }, 22 | { href: "/oic/d" }, 23 | { href: "/oic/p" }, 24 | { href: "/oic/sec/doxm" } 25 | ], 26 | permission: 2 27 | }, 28 | { 29 | aceid: 3, 30 | subject: { conntype: "anon-clear" }, 31 | resources: [ 32 | { href: "/oic/rd" } 33 | ], 34 | permission: 31 35 | }, 36 | { 37 | aceid: 4, 38 | subject: { conntype: "auth-crypt" }, 39 | resources: [ 40 | { href: "/oic/rd" } 41 | ], 42 | permission: 31 43 | } 44 | ], 45 | rowneruuid: item.deviceUuid 46 | }, 47 | pstat: { 48 | dos: { s: 3, p: false }, 49 | isop: true, 50 | rowneruuid: item.deviceUuid, 51 | cm: 0, 52 | tm: 0, 53 | om: 4, 54 | sm: 4 55 | }, 56 | doxm: { 57 | oxms: [ 0 ], 58 | oxmsel: 0, 59 | sct: 1, 60 | owned: true, 61 | deviceuuid: item.deviceUuid, 62 | devowneruuid: item.deviceUuid, 63 | rowneruuid: item.deviceUuid 64 | }, 65 | cred: { 66 | creds: creds 67 | } 68 | }; 69 | }; 70 | -------------------------------------------------------------------------------- /tests/provision/produceServerContent.js: -------------------------------------------------------------------------------- 1 | var produceClientContent = require( "./produceClientContent" ); 2 | 3 | // Create two ACEs from the given resources - one for plain text and one for encrypted 4 | function generateACEList( resources ) { 5 | return [ 6 | { subject: { "conntype": "anon-clear" }, resources: resources, "permission": 31 }, 7 | { subject: { "conntype": "auth-crypt" }, resources: resources, "permission": 31 } 8 | ]; 9 | } 10 | 11 | module.exports = function produceServerContent( item, creds, resourceUuid ) { 12 | var index; 13 | var result = produceClientContent( item, creds ); 14 | 15 | result.acl.aclist2 = result.acl.aclist2.concat( generateACEList( 16 | Array.isArray( resourceUuid ) ? resourceUuid : [ 17 | 18 | // Resource names used during testing 19 | // 1. iotivity-node 20 | { 21 | href: "/a/" + resourceUuid + "-xyzzy" 22 | }, 23 | 24 | // 2. iot-js-api 25 | { 26 | href: "/a/" + resourceUuid 27 | }, 28 | { 29 | href: "/direct" 30 | }, 31 | { 32 | href: "/target-resource" 33 | }, 34 | { 35 | href: "/disable-presence" 36 | }, 37 | { 38 | href: "/some/new/resource" 39 | } 40 | ] ) ); 41 | 42 | // Finalize aceid property 43 | for ( index = 0; index < result.acl.aclist2.length; index++ ) { 44 | result.acl.aclist2[ index ].aceid = index + 1; 45 | } 46 | 47 | return result; 48 | }; 49 | -------------------------------------------------------------------------------- /tests/security.boilerplate.json: -------------------------------------------------------------------------------- 1 | { 2 | "acl": { 3 | "aclist2": [ 4 | { 5 | "subject": { "conntype": "anon-clear" }, 6 | "resources": [ 7 | { "href": "/oic/res" }, 8 | { "href": "/oic/rd" }, 9 | { "href": "/oic/d" }, 10 | { "href": "/oic/p" } 11 | ], 12 | "permission": 2 13 | }, 14 | { 15 | "subject": { "conntype": "auth-crypt" }, 16 | "resources": [ 17 | { "href": "/oic/res" }, 18 | { "href": "/oic/rd" }, 19 | { "href": "/oic/d" }, 20 | { "href": "/oic/p"} 21 | ], 22 | "permission": 2 23 | }, 24 | { 25 | "subject": { "conntype": "anon-clear" }, 26 | "resources": [ 27 | { "href": "/oic/sec/doxm" } 28 | ], 29 | "permission": 14 30 | }, 31 | { 32 | "subject": { "conntype": "auth-crypt" }, 33 | "resources": [ 34 | { "href": "/oic/sec/doxm" }, 35 | { "href": "/oic/sec/roles" } 36 | ], 37 | "permission": 14 38 | } 39 | ] 40 | }, 41 | "pstat": { 42 | "dos": { "s": 1, "p": false }, 43 | "isop": false, 44 | "cm": 2, 45 | "tm": 0, 46 | "om": 4, 47 | "sm": 4 48 | }, 49 | "doxm": { 50 | "oxms": [ 0 ], 51 | "oxmsel": 0, 52 | "sct": 1, 53 | "owned": false, 54 | "devowneruuid": "" 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/setup.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var success = "\x1b[42;30m✓\x1b[0m", 16 | failure = "\x1b[41;30m✗\x1b[0m", 17 | QUnit = require( "qunitjs" ), 18 | results = require( "./getresult" ); 19 | 20 | // Right-align runtime in a field that's 10 columns wide 21 | function formatRuntime( runtime ) { 22 | var index, 23 | str = "" + runtime, 24 | indent = ""; 25 | 26 | for ( index = 0; index < Math.max( 0, 10 - str.length ); index++ ) { 27 | indent += " "; 28 | } 29 | 30 | return indent + str; 31 | } 32 | 33 | QUnit.load(); 34 | QUnit.config.requireExpects = true; 35 | QUnit.config.testTimeout = 90000; 36 | QUnit.config.callbacks.moduleStart.push( function( status ) { 37 | 38 | // Parameters: status: { name, tests } 39 | 40 | if ( status.name ) { 41 | console.log( "\n### " + status.name ); 42 | } 43 | } ); 44 | QUnit.config.callbacks.testStart.push( function( status ) { 45 | 46 | // Parameters: status: { name, module, testId } 47 | 48 | if ( status.name ) { 49 | console.log( "\n" + status.name ); 50 | } 51 | } ); 52 | QUnit.config.callbacks.log.push( function( status ) { 53 | 54 | // Parameters: status: { module, result(t/f), message, actual, expected, testId, runtime } 55 | 56 | results.getTestResult( status ); 57 | 58 | console.log( 59 | ( status.result ? success : failure ) + 60 | " @" + formatRuntime( status.runtime ) + ": " + 61 | status.message ); 62 | if ( !status.result ) { 63 | console.log( "Actual: " ); 64 | console.log( QUnit.dump.parse( status.actual ) ); 65 | console.log( "Expected: " ); 66 | console.log( QUnit.dump.parse( status.expected ) ); 67 | } 68 | } ); 69 | 70 | QUnit.config.callbacks.done.push( function( status ) { 71 | var passed = "\x1b[42;30m " + status.passed + " \x1b[0m", 72 | failed = "\x1b[41;30m " + status.failed + " \x1b[0m"; 73 | 74 | console.log( "Total assertions: " + 75 | "(" + passed + ( status.failed > 0 ? "+" + failed : "" ) + ") / " + status.total ); 76 | 77 | results.saveResults( "lowlevel" ); 78 | 79 | process.exit( status.failed > 0 ? 1 : 0 ); 80 | } ); 81 | 82 | module.exports = QUnit; 83 | -------------------------------------------------------------------------------- /tests/tests/API Presence.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var csdk = require( process.argv[ 3 ] + "/lib/csdk" ); 16 | var client = require( process.argv[ 3 ] ).client; 17 | var util = require( "../assert-to-console" ); 18 | var handles = require( process.argv[ 3 ] + "/lib/ClientHandles" ); 19 | 20 | var eventName; 21 | 22 | function devicelost() {} 23 | 24 | console.log( JSON.stringify( { assertionCount: 3 } ) ); 25 | 26 | handles.on( "newListener", function( event ) { 27 | util.assert( "deepEqual", JSON.parse( event ), { 28 | requestUri: csdk.OC_RSRVD_PRESENCE_URI, 29 | method: "OC_REST_DISCOVER" 30 | }, "Global presence listener is correct" ); 31 | eventName = event; 32 | } ); 33 | 34 | client.on( "devicelost", devicelost ); 35 | 36 | util.assert( "strictEqual", handles.listeners( eventName ).length, 1, 37 | "One global presence listener present when first 'devicelost' listener is added" ); 38 | 39 | client.removeListener( "devicelost", devicelost ); 40 | 41 | util.assert( "strictEqual", handles.listeners( eventName ).length, 0, 42 | "No global presence listeners present when last 'devicelost' listener is removed" ); 43 | 44 | process.exit( 0 ); 45 | -------------------------------------------------------------------------------- /tests/tests/API Retrieve Secure Resource/client.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var client = require( process.argv[ 3 ] ).client; 16 | var url = require( "url" ); 17 | 18 | console.log( JSON.stringify( { assertionCount: 5 } ) ); 19 | 20 | function resourcefound( resource ) { 21 | 22 | // Find the first secure endpoint. 23 | var endpoint = resource.endpoints.reduce( function findSecureEndpoint( current, candidate ) { 24 | return ( null === current ? 25 | ( url.parse( candidate.origin ).protocol.substr( -1 ) ? candidate : null ) : 26 | current ); 27 | }, null ); 28 | 29 | console.log( JSON.stringify( { "assertion": "notStrictEqual", arguments: [ 30 | endpoint, null, "Client: Resource has at least one secure endpoint" 31 | ] } ) ); 32 | 33 | console.log( JSON.stringify( { "assertion": "strictEqual", arguments: [ 34 | resource.secure, true, "Client: Resource is marked as secure" 35 | ] } ) ); 36 | 37 | resource.endpoint = endpoint; 38 | 39 | client 40 | .removeListener( "resourcefound", resourcefound ) 41 | .retrieve( resource ) 42 | .then( 43 | function( retrievedResource ) { 44 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 45 | retrievedResource === resource, 46 | "Client: Retrieved resource is the discovered resource" 47 | ] } ) ); 48 | console.log( JSON.stringify( { assertion: "deepEqual", arguments: [ 49 | retrievedResource.properties, { value: 42 }, 50 | "Client: Retrieved resource properties are as expected" 51 | ] } ) ); 52 | }, 53 | function( error ) { 54 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 55 | false, "Client: retrieve() failed unexpectedly: " + 56 | ( "" + error ) + "\n" + JSON.stringify( error, null, 4 ) 57 | ] } ) ); 58 | } ) 59 | .then( function() { 60 | 61 | // Retrieve the resource again, this time with query options 62 | return client.retrieve( resource, { scale: -1 } ); 63 | } ) 64 | .then( 65 | function( retrievedResource ) { 66 | console.log( JSON.stringify( { assertion: "deepEqual", arguments: [ 67 | retrievedResource.properties, { value: -42 }, 68 | "Client: Retrieved resouce properties change based on query options" 69 | ] } ) ); 70 | }, 71 | function( error ) { 72 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 73 | false, "Client: retrieve() with options failed unexpectedly: " + 74 | ( "" + error ) + "\n" + JSON.stringify( error, null, 4 ) 75 | ] } ) ); 76 | } ) 77 | .then( function() { 78 | console.log( JSON.stringify( { killPeer: true } ) ); 79 | process.exit( 0 ); 80 | } ); 81 | } 82 | 83 | client 84 | .on( "resourcefound", resourcefound ) 85 | .findResources( { resourcePath: "/a/" + process.argv[ 2 ] } ) 86 | .catch( function( error ) { 87 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 88 | false, "Client: Starting device discovery failed: " + 89 | ( "" + error ) + "\n" + JSON.stringify( error, null, 4 ) 90 | ] } ) ); 91 | } ); 92 | -------------------------------------------------------------------------------- /tests/tests/API Retrieve Secure Resource/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var ocf = require( process.argv[ 3 ] ); 16 | var server = ocf.server; 17 | 18 | ocf.device.coreSpecVersion = "ocf.1.1.0"; 19 | 20 | console.log( JSON.stringify( { assertionCount: 5 } ) ); 21 | 22 | // Multiply a value by a scale given in the options 23 | function transformSensorData( options ) { 24 | var scale = ( options && "scale" in options ) ? ( +options.scale ) : 1; 25 | 26 | if ( isNaN( scale ) ) { 27 | scale = 1; 28 | } 29 | 30 | return { value: this.properties.value * scale }; 31 | } 32 | 33 | server 34 | .register( { 35 | resourcePath: "/a/" + process.argv[ 2 ], 36 | resourceTypes: [ "core.light" ], 37 | interfaces: [ "oic.if.baseline" ], 38 | discoverable: true, 39 | secure: true 40 | } ) 41 | .then( 42 | function( resource ) { 43 | var requestCount = 0; 44 | 45 | resource.properties = { 46 | value: 42 47 | }; 48 | resource.ontranslate( transformSensorData ).onretrieve( function( request ) { 49 | if ( requestCount++ > 1 ) { 50 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 51 | false, "Server: Unexpected extra request" 52 | ] } ) ); 53 | } 54 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 55 | request.target === resource, 56 | "Server: Resource passed to retrieve request is the one that was registered" 57 | ] } ) ); 58 | request.respond() 59 | .then( 60 | function() { 61 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 62 | true, "Server: Successful response to retrieve request" 63 | ] } ) ); 64 | }, 65 | function( error ) { 66 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 67 | false, "Server: Failed to respond to retrieve request: " + 68 | ( "" + error.message ) + "\n" + 69 | JSON.stringify( error, null, 4 ) 70 | ] } ) ); 71 | } ); 72 | } ); 73 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 74 | true, "Server: Registering resource succeeded" 75 | ] } ) ); 76 | console.log( JSON.stringify( { ready: true } ) ); 77 | }, 78 | function( error ) { 79 | console.log( JSON.stringify( { assertion: "ok", arguments: [ 80 | false, "Server: Registering resource failed unexpectedly: " + 81 | ( "" + error ) + "\n" + JSON.stringify( error, null, 4 ) 82 | ] } ) ); 83 | } ); 84 | process.on( "message", function() { 85 | process.exit( 0 ); 86 | } ); 87 | -------------------------------------------------------------------------------- /tests/tests/Callback Exception/client.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var result, 16 | processCallCount = 0, 17 | processLoop = null, 18 | discoverHandleReceptacle = {}, 19 | iotivity = require( process.argv[ 3 ] + "/lowlevel" ), 20 | testUtils = require( "../../utils" )( iotivity ); 21 | 22 | function cleanup() { 23 | var cleanupResult; 24 | 25 | if ( processLoop ) { 26 | clearInterval( processLoop ); 27 | processLoop = null; 28 | } 29 | 30 | testUtils.assert( "ok", true, "Client: OCProcess succeeded " + processCallCount + " times" ); 31 | 32 | cleanupResult = iotivity.OCStop(); 33 | if ( testUtils.stackOKOrDie( "Client", "OCStop", cleanupResult ) ) { 34 | console.log( JSON.stringify( { killPeer: true } ) ); 35 | process.exit( 0 ); 36 | } 37 | } 38 | 39 | process.on( "uncaughtException", function( exception ) { 40 | testUtils.assert( "strictEqual", exception.message, "Something", 41 | "Client: Caught the correct exception" ); 42 | cleanup(); 43 | } ); 44 | 45 | console.log( JSON.stringify( { assertionCount: 5 } ) ); 46 | 47 | // Initialize 48 | result = iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 49 | testUtils.stackOKOrDie( "Client", "OCInit", result ); 50 | 51 | // Set up OCProcess loop 52 | processLoop = setInterval( function() { 53 | var processResult = iotivity.OCProcess(); 54 | 55 | if ( processResult === iotivity.OCStackResult.OC_STACK_OK ) { 56 | processCallCount++; 57 | } else { 58 | testUtils.stackOKOrDie( 59 | "Client", 60 | "OCProcess(after " + processCallCount + " successful calls)", 61 | processResult ); 62 | } 63 | }, 100 ); 64 | 65 | // Discover 66 | result = iotivity.OCDoResource( 67 | discoverHandleReceptacle, 68 | iotivity.OCMethod.OC_REST_DISCOVER, 69 | iotivity.OC_MULTICAST_DISCOVERY_URI, 70 | null, 71 | null, 72 | iotivity.OCConnectivityType.CT_DEFAULT, 73 | iotivity.OCQualityOfService.OC_HIGH_QOS, 74 | function() { 75 | throw new Error( "Something" ); 76 | }, 77 | null ); 78 | 79 | testUtils.stackOKOrDie( "Client", "OCDoResource(discovery)", result ); 80 | -------------------------------------------------------------------------------- /tests/tests/Callback Exception/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var result, 16 | uuid = process.argv[ 2 ], 17 | processCallCount = 0, 18 | processLoop = null, 19 | resourceHandleReceptacle = {}, 20 | iotivity = require( process.argv[ 3 ] + "/lowlevel" ), 21 | testUtils = require( "../../utils" )( iotivity ); 22 | 23 | function cleanup() { 24 | var cleanupResult; 25 | 26 | if ( processLoop ) { 27 | clearInterval( processLoop ); 28 | processLoop = null; 29 | } 30 | 31 | testUtils.assert( "ok", true, "Server: OCProcess succeeded " + processCallCount + " times" ); 32 | 33 | cleanupResult = iotivity.OCDeleteResource( resourceHandleReceptacle.handle ); 34 | testUtils.stackOKOrDie( "Server", "OCDeleteResource", cleanupResult ); 35 | 36 | cleanupResult = iotivity.OCStop(); 37 | if ( testUtils.stackOKOrDie( "Server", "OCStop", cleanupResult ) ) { 38 | process.exit( 0 ); 39 | } 40 | } 41 | 42 | console.log( JSON.stringify( { assertionCount: 6 } ) ); 43 | 44 | // Initialize 45 | result = iotivity.OCRegisterPersistentStorageHandler( require( "../../../lib/StorageHandler" )() ); 46 | testUtils.stackOKOrDie( "Server", "OCRegisterPersistentStorageHandler", result ); 47 | 48 | result = iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 49 | testUtils.stackOKOrDie( "Server", "OCInit", result ); 50 | 51 | // Set up process loop 52 | processLoop = setInterval( function() { 53 | var processResult = iotivity.OCProcess(); 54 | 55 | if ( processResult === iotivity.OCStackResult.OC_STACK_OK ) { 56 | processCallCount++; 57 | } else { 58 | testUtils.stackOKOrDie( 59 | "Server", 60 | "OCProcess(after " + processCallCount + " successful calls)", 61 | processResult ); 62 | } 63 | }, 100 ); 64 | 65 | // Create resource 66 | result = iotivity.OCCreateResource( 67 | resourceHandleReceptacle, 68 | "core.fan", 69 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 70 | "/a/" + uuid, 71 | function() { 72 | 73 | // The entity handler should not receive any calls 74 | console.log( JSON.stringify( { 75 | teardown: true, 76 | message: "Server: Entity handler should not get called" 77 | } ) ); 78 | return iotivity.OCEntityHandlerResult.OC_EH_ERROR; 79 | }, 80 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 81 | testUtils.stackOKOrDie( "Server", "OCCreateResource", result ); 82 | 83 | // Report that the server has successfully created its resource(s). 84 | console.log( JSON.stringify( { ready: true } ) ); 85 | 86 | // Exit gracefully when interrupted 87 | process.on( "message", cleanup ); 88 | -------------------------------------------------------------------------------- /tests/tests/Discovery/client.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var result, 16 | uuid = process.argv[ 2 ], 17 | processCallCount = 0, 18 | processLoop = null, 19 | staleHandleCheckLoop = null, 20 | discoverHandleReceptacle = {}, 21 | iotivity = require( process.argv[ 3 ] + "/lowlevel" ), 22 | testUtils = require( "../../utils" )( iotivity ); 23 | 24 | function cleanup() { 25 | var cleanupResult; 26 | 27 | if ( processLoop ) { 28 | clearInterval( processLoop ); 29 | processLoop = null; 30 | } 31 | 32 | if ( staleHandleCheckLoop ) { 33 | clearInterval( staleHandleCheckLoop ); 34 | staleHandleCheckLoop = null; 35 | } 36 | 37 | testUtils.assert( "ok", true, "Client: OCProcess succeeded " + processCallCount + " times" ); 38 | 39 | cleanupResult = iotivity.OCStop(); 40 | if ( testUtils.stackOKOrDie( "Client", "OCStop", cleanupResult ) ) { 41 | console.log( JSON.stringify( { killPeer: true } ) ); 42 | process.exit( 0 ); 43 | } 44 | } 45 | 46 | console.log( JSON.stringify( { assertionCount: 6 } ) ); 47 | 48 | // Initialize 49 | result = iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT ); 50 | testUtils.stackOKOrDie( "Client", "OCInit", result ); 51 | 52 | // Set up OCProcess loop 53 | processLoop = setInterval( function() { 54 | var processResult = iotivity.OCProcess(); 55 | 56 | if ( processResult === iotivity.OCStackResult.OC_STACK_OK ) { 57 | processCallCount++; 58 | } else { 59 | testUtils.stackOKOrDie( 60 | "Client", 61 | "OCProcess(after " + processCallCount + " successful calls)", 62 | processResult ); 63 | } 64 | }, 100 ); 65 | 66 | staleHandleCheckLoop = setInterval( function() { 67 | if ( discoverHandleReceptacle.handle.stale ) { 68 | testUtils.assert( "ok", true, "Client: Handle found stale after deleting transaction" ); 69 | cleanup(); 70 | } 71 | }, 500 ); 72 | 73 | // Discover 74 | result = iotivity.OCDoResource( 75 | discoverHandleReceptacle, 76 | iotivity.OCMethod.OC_REST_DISCOVER, 77 | iotivity.OC_MULTICAST_DISCOVERY_URI, 78 | null, 79 | null, 80 | iotivity.OCConnectivityType.CT_DEFAULT, 81 | iotivity.OCQualityOfService.OC_HIGH_QOS, 82 | function( handle, response ) { 83 | 84 | // We retain the discovery callback until we've found the resource identified by the uuid. 85 | var returnValue = iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION; 86 | 87 | if ( testUtils.findResource( response, uuid ) ) { 88 | 89 | // We've successfully completed the test so let's kill the server and test the cleanup. 90 | testUtils.assert( "ok", true, "Client: Resource found" ); 91 | returnValue = iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 92 | 93 | } 94 | 95 | return returnValue; 96 | }, 97 | null ); 98 | testUtils.stackOKOrDie( "Client", "OCDoResource(discovery)", result ); 99 | -------------------------------------------------------------------------------- /tests/tests/Discovery/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var result, 16 | uuid = process.argv[ 2 ], 17 | processCallCount = 0, 18 | processLoop = null, 19 | resourceHandleReceptacle = {}, 20 | iotivity = require( process.argv[ 3 ] + "/lowlevel" ), 21 | testUtils = require( "../../utils" )( iotivity ); 22 | 23 | function cleanup() { 24 | var cleanupResult; 25 | 26 | if ( processLoop ) { 27 | clearInterval( processLoop ); 28 | processLoop = null; 29 | } 30 | 31 | testUtils.assert( "ok", true, "Server: OCProcess succeeded " + processCallCount + " times" ); 32 | 33 | cleanupResult = iotivity.OCDeleteResource( resourceHandleReceptacle.handle ); 34 | testUtils.stackOKOrDie( "Server", "OCDeleteResource", cleanupResult ); 35 | 36 | cleanupResult = iotivity.OCStop(); 37 | if ( testUtils.stackOKOrDie( "Server", "OCStop", cleanupResult ) ) { 38 | process.exit( 0 ); 39 | } 40 | } 41 | 42 | console.log( JSON.stringify( { assertionCount: 6 } ) ); 43 | 44 | // Initialize 45 | result = iotivity.OCRegisterPersistentStorageHandler( require( "../../../lib/StorageHandler" )() ); 46 | testUtils.stackOKOrDie( "Server", "OCRegisterPersistentStorageHandler", result ); 47 | 48 | result = iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 49 | testUtils.stackOKOrDie( "Server", "OCInit", result ); 50 | 51 | // Set up process loop 52 | processLoop = setInterval( function() { 53 | var processResult = iotivity.OCProcess(); 54 | 55 | if ( processResult === iotivity.OCStackResult.OC_STACK_OK ) { 56 | processCallCount++; 57 | } else { 58 | testUtils.stackOKOrDie( 59 | "Server", 60 | "OCProcess(after " + processCallCount + " successful calls)", 61 | processResult ); 62 | } 63 | }, 100 ); 64 | 65 | // Create resource 66 | result = iotivity.OCCreateResource( 67 | resourceHandleReceptacle, 68 | "core.fan", 69 | iotivity.OC_RSRVD_INTERFACE_DEFAULT, 70 | "/a/" + uuid, 71 | function() { 72 | 73 | // The entity handler should not receive any calls 74 | console.log( JSON.stringify( { 75 | teardown: true, 76 | message: "Server: Entity handler should not get called" 77 | } ) ); 78 | return iotivity.OCEntityHandlerResult.OC_EH_ERROR; 79 | }, 80 | iotivity.OCResourceProperty.OC_DISCOVERABLE ); 81 | testUtils.stackOKOrDie( "Server", "OCCreateResource", result ); 82 | 83 | // Report that the server has successfully created its resource(s). 84 | console.log( JSON.stringify( { ready: true } ) ); 85 | 86 | // Exit gracefully when interrupted 87 | process.on( "message", cleanup ); 88 | -------------------------------------------------------------------------------- /tests/tests/Interactive Server Startup.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var utils = require( "../assert-to-console" ); 16 | 17 | console.log( JSON.stringify( { assertionCount: 4 } ) ); 18 | 19 | var stderr = ""; 20 | var stdout = ""; 21 | 22 | var childArguments = [ "-e", 23 | "try { require( '" + process.argv[ 3 ].replace( /[\\]/g, "\\\\" ) + "' ); } " + 24 | "catch( anError ) { " + 25 | "console.error( anError.stack ); process.exit( 1 ); " + 26 | "}" + 27 | "process.exit( 0 );" 28 | ]; 29 | 30 | var theChild = require( "child_process" ).spawn( "node", childArguments ) 31 | .on( "exit", function( code, signal ) { 32 | utils.assert( "strictEqual", code, 0, "require() from interactive shell succeeded" ); 33 | utils.assert( "strictEqual", signal, null, 34 | "require() from interactive shell did not receive a signal" ); 35 | utils.assert( "strictEqual", stdout, "", "Process stdout is empty" ); 36 | utils.assert( "strictEqual", stderr, "", "Process stderr is empty" ); 37 | } ); 38 | 39 | theChild.stdout.on( "data", function( data ) { 40 | stdout += data.toString(); 41 | } ); 42 | theChild.stderr.on( "data", function( data ) { 43 | stderr += data.toString(); 44 | } ); 45 | -------------------------------------------------------------------------------- /tests/tests/Local Device And Platform.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var iotivity = require( process.argv[ 3 ] + "/lowlevel" ); 16 | var testUtils = require( "../utils" )( iotivity ); 17 | var isequal = require( "lodash.isequal" ); 18 | 19 | // Report assertion count 20 | console.log( JSON.stringify( { assertionCount: 22 } ) ); 21 | 22 | // Init 23 | testUtils.stackOKOrDie( "OCInit", iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ) ); 24 | 25 | function getAndSet( message, payloadType, property, value ) { 26 | var result = {}; 27 | testUtils.stackOKOrDie( "Set " + message + " to " + JSON.stringify( value ), 28 | iotivity.OCSetPropertyValue( iotivity.OCPayloadType[ payloadType ], 29 | iotivity[ property ], value ) ); 30 | testUtils.stackOKOrDie( "Get " + message, 31 | iotivity.OCGetPropertyValue( iotivity.OCPayloadType[ payloadType ], 32 | iotivity[ property ], result ) ); 33 | 34 | return result.value; 35 | } 36 | 37 | function testProperty( message, payloadType, property, value ) { 38 | testUtils.assert( "ok", isequal( getAndSet( message, payloadType, property, value ), value ), 39 | message + ": retrieved value is strictly equal to set value" ); 40 | } 41 | 42 | // string properties 43 | testProperty( "platform manufacturer url", "PAYLOAD_TYPE_PLATFORM", "OC_RSRVD_MFG_URL", 44 | "http://" + Math.round( Math.random() * 1048576 ) ); 45 | 46 | testProperty( "device name", "PAYLOAD_TYPE_DEVICE", "OC_RSRVD_DEVICE_NAME", 47 | "" + Math.round( Math.random() * 1048576 ) ); 48 | 49 | testProperty( "spec version", "PAYLOAD_TYPE_DEVICE", "OC_RSRVD_SPEC_VERSION", 50 | Math.round( Math.random() * 9 ) + "." + 51 | Math.round( Math.random() * 9 ) + "." + 52 | Math.round( Math.random() * 9 ) ); 53 | 54 | testProperty( "manufacturer name", "PAYLOAD_TYPE_PLATFORM", "OC_RSRVD_MFG_NAME", 55 | [ "Abra", "Cadabra", "Csiribu", "Csiriba", "Simsalabim" ][ Math.round( Math.random() * 4 ) ] ); 56 | 57 | var sampleDMV = "res." + 58 | Math.round( Math.random() * 9 ) + "." + 59 | Math.round( Math.random() * 9 ) + "." + 60 | Math.round( Math.random() * 9 ); 61 | var dmvSetResult = getAndSet( "data model version", "PAYLOAD_TYPE_DEVICE", 62 | "OC_RSRVD_DATA_MODEL_VERSION", sampleDMV ); 63 | 64 | testUtils.assert( "strictEqual", sampleDMV, dmvSetResult.join( "," ), 65 | "data model version: retrieved value is strictly equal to set value" ); 66 | 67 | // date properties 68 | testProperty( "manufacture date", "PAYLOAD_TYPE_PLATFORM", "OC_RSRVD_MFG_DATE", 69 | new Date( 1299752880000 ) ); 70 | 71 | testProperty( "system time", "PAYLOAD_TYPE_PLATFORM", "OC_RSRVD_SYSTEM_TIME", 72 | 73 | // Looks like iotivity doesn't have millisecond resolution 74 | new Date( Math.round( Date.now() / 1000 ) * 1000 ) ); 75 | 76 | process.exit( 0 ); 77 | -------------------------------------------------------------------------------- /tests/tests/Resource Directory/cleanupRequest.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | module.exports = function cleanupRequest( prefix, ocf, testUtils, destination, uri ) { 16 | testUtils.stackOKOrDie( prefix, "OCDoRequest(cleanup)", 17 | ocf.OCDoResource( 18 | {}, 19 | ocf.OCMethod.OC_REST_POST, 20 | uri, 21 | destination, 22 | { 23 | type: ocf.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION, 24 | values: { 25 | killPeer: true 26 | } 27 | }, 28 | ocf.OCConnectivityType.CT_DEFAULT, 29 | ocf.OCQualityOfService.OC_HIGH_QOS, 30 | function cleanupResponse() { 31 | return ocf.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 32 | }, 33 | null ) ); 34 | }; 35 | -------------------------------------------------------------------------------- /tests/tests/Resource Directory/client1.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var result, 16 | uuid = process.argv[ 2 ], 17 | processCallCount = 0, 18 | processLoop = null, 19 | iotivity = require( process.argv[ 3 ] + "/lowlevel" ), 20 | testUtils = require( "../../utils" )( iotivity ), 21 | cleanupRequest = require( "./cleanupRequest" ); 22 | 23 | function cleanup() { 24 | if ( processLoop ) { 25 | clearInterval( processLoop ); 26 | processLoop = null; 27 | } 28 | testUtils.assert( "ok", true, "Server: OCProcess succeeded " + processCallCount + " times" ); 29 | testUtils.stackOKOrDie( "Server", "OCStop", iotivity.OCStop() ); 30 | process.exit( 0 ); 31 | } 32 | 33 | console.log( JSON.stringify( { assertionCount: 8 } ) ); 34 | 35 | // Initialize 36 | result = iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT_SERVER ); 37 | testUtils.stackOKOrDie( "Server", "OCInit", result ); 38 | 39 | // Set up OCProcess loop 40 | processLoop = setInterval( function() { 41 | var processResult = iotivity.OCProcess(); 42 | 43 | if ( processResult === iotivity.OCStackResult.OC_STACK_OK ) { 44 | processCallCount++; 45 | } else { 46 | testUtils.stackOKOrDie( 47 | "Server", 48 | "OCProcess(after " + processCallCount + " successful calls)", 49 | processResult ); 50 | } 51 | }, 100 ); 52 | 53 | // Discover 54 | result = iotivity.OCRDDiscover( 55 | {}, 56 | iotivity.OCConnectivityType.CT_DEFAULT, 57 | function OCRDDiscoverResponse( handle, response ) { 58 | var resourceHandleReceptacle = {}; 59 | 60 | testUtils.stackOKOrDie( "Server", "OCCreateResource", 61 | iotivity.OCCreateResource( resourceHandleReceptacle, "core.light", "oic.if.baseline", 62 | "/a/" + uuid, function ResourceEntityHandler() { 63 | return iotivity.OCEntityHandlerResponse.OC_EH_OK; 64 | }, iotivity.OCResourceProperty.OC_DISCOVERABLE ) ); 65 | 66 | testUtils.stackOKOrDie( "Server", "OCRDPublish", 67 | iotivity.OCRDPublish( 68 | {}, 69 | response.addr.addr + ":" + response.addr.port, 70 | iotivity.OCConnectivityType.CT_DEFAULT, 71 | [ resourceHandleReceptacle.handle ], 72 | 86400, 73 | function OCRDPublishResponse( handle, response ) { 74 | var index; 75 | var links = response.payload.values.links; 76 | 77 | for ( index in links ) { 78 | if ( links[ index ].href === "/a/" + uuid ) { 79 | break; 80 | } 81 | } 82 | 83 | testUtils.assert( "ok", index < links.length, 84 | "Server: Posted resource found in OCRDPublish response" ); 85 | 86 | cleanupRequest( "Server", iotivity, testUtils, response.addr, 87 | "/a/" + uuid + "-xyzzy" ); 88 | 89 | return iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 90 | }, 91 | iotivity.OCQualityOfService.OC_HIGH_QOS ) ); 92 | 93 | return iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION; 94 | }, 95 | iotivity.OCQualityOfService.OC_HIGH_QOS ); 96 | testUtils.stackOKOrDie( "Server", "OCRDDiscover", result ); 97 | 98 | process.on( "message", cleanup ); 99 | -------------------------------------------------------------------------------- /tests/tests/Resource Directory/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var result, 16 | cleanupPrerequisiteCount = 0, 17 | uuid = process.argv[ 2 ], 18 | terminationResourceHandleReceptacle = {}, 19 | processCallCount = 0, 20 | processLoop = null, 21 | iotivity = require( process.argv[ 3 ] + "/lowlevel" ), 22 | testUtils = require( "../../utils" )( iotivity ); 23 | 24 | function cleanup() { 25 | if ( ++cleanupPrerequisiteCount < 2 ) { 26 | return; 27 | } 28 | 29 | if ( processLoop ) { 30 | clearInterval( processLoop ); 31 | processLoop = null; 32 | } 33 | 34 | testUtils.assert( "ok", true, "RD Server: OCProcess succeeded " + processCallCount + 35 | " times" ); 36 | 37 | if ( terminationResourceHandleReceptacle.handle && 38 | !terminationResourceHandleReceptacle.handle.stale ) { 39 | testUtils.stackOKOrDie( "RD Server", "OCDeleteResource", 40 | iotivity.OCDeleteResource( terminationResourceHandleReceptacle.handle ) ); 41 | } 42 | 43 | testUtils.stackOKOrDie( "RD Server", "OCRDStop", iotivity.OCRDStop() ); 44 | testUtils.stackOKOrDie( "RD Server", "OCStop", iotivity.OCStop() ); 45 | console.log( JSON.stringify( { killPeer: true } ) ); 46 | process.exit( 0 ); 47 | } 48 | 49 | console.log( JSON.stringify( { assertionCount: 8 } ) ); 50 | 51 | // Initialize 52 | result = iotivity.OCRegisterPersistentStorageHandler( require( "../../../lib/StorageHandler" )() ); 53 | testUtils.stackOKOrDie( "RD Server", "OCRegisterPersistentStorageHandler", result ); 54 | 55 | result = iotivity.OCInit( null, 0, iotivity.OCMode.OC_SERVER ); 56 | testUtils.stackOKOrDie( "RD Server", "OCInit", result ); 57 | 58 | result = iotivity.OCRDStart(); 59 | testUtils.stackOKOrDie( "RD Server", "OCRDStart", result ); 60 | 61 | // Set up process loop 62 | processLoop = setInterval( function() { 63 | var processResult = iotivity.OCProcess(); 64 | 65 | if ( processResult === iotivity.OCStackResult.OC_STACK_OK ) { 66 | processCallCount++; 67 | } else { 68 | testUtils.stackOKOrDie( 69 | "RD Server", 70 | "OCProcess(after " + processCallCount + " successful calls)", 71 | processResult ); 72 | } 73 | }, 100 ); 74 | 75 | result = iotivity.OCCreateResource( terminationResourceHandleReceptacle, 76 | "core.light", "oic.if.baseline", "/a/" + uuid + "-xyzzy", 77 | function terminationResourceEntityHandler( flag, request ) { 78 | if ( request.resource === terminationResourceHandleReceptacle.handle && 79 | request.method === iotivity.OCMethod.OC_REST_POST && 80 | request.payload && 81 | request.payload.type === iotivity.OCPayloadType.PAYLOAD_TYPE_REPRESENTATION && 82 | request.payload.values.killPeer === true ) { 83 | cleanup(); 84 | } 85 | return iotivity.OCEntityHandlerResult.OC_EH_OK; 86 | }, iotivity.OCResourceProperty.OC_DISCOVERABLE ); 87 | testUtils.stackOKOrDie( "RD Server", "OCCreateResource", result ); 88 | 89 | // Report that the server has successfully created its resource(s). 90 | console.log( JSON.stringify( { ready: true } ) ); 91 | -------------------------------------------------------------------------------- /tests/utils.js: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Intel Corporation 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | var assignIn = require( "lodash.assignin" ), 16 | TestUtils = function( iotivity ) { 17 | if ( !( this instanceof TestUtils ) ) { 18 | return new TestUtils( iotivity ); 19 | } 20 | 21 | this._iotivity = iotivity; 22 | process.on( "message", function() { 23 | setTimeout( process.exit, 1000, 0 ); 24 | } ); 25 | }; 26 | 27 | assignIn( TestUtils.prototype, require( "./assert-to-console" ), { 28 | lookupEnumValueName: function( enumName, value ) { 29 | var index, 30 | enumeration = this._iotivity[ enumName ]; 31 | 32 | for ( index in enumeration ) { 33 | if ( enumeration[ index ] === value ) { 34 | return index; 35 | } 36 | } 37 | }, 38 | lookupBitfieldValueNames: function( enumName, value ) { 39 | var index, 40 | enumeration = this._iotivity[ enumName ], 41 | bits = {}; 42 | 43 | for ( index in enumeration ) { 44 | if ( value & enumeration[ index ] ) { 45 | bits[ index ] = true; 46 | } 47 | } 48 | return bits; 49 | }, 50 | 51 | stackOKOrDie: function( module, nameOfStep, result ) { 52 | 53 | // Two-argument configuration means module was skipped 54 | if ( arguments.length === 2 ) { 55 | result = nameOfStep; 56 | nameOfStep = module; 57 | module = ""; 58 | } 59 | 60 | console.log( JSON.stringify( { 61 | assertion: "strictEqual", 62 | arguments: [ 63 | this.lookupEnumValueName( "OCStackResult", result ), 64 | "OC_STACK_OK", 65 | ( module ? module + ": " : "" ) + nameOfStep + " successful" 66 | ] 67 | } ) ); 68 | if ( result === this._iotivity.OCStackResult.OC_STACK_OK ) { 69 | return true; 70 | } else { 71 | this.die( module + ": " + nameOfStep + " failed" ); 72 | return false; 73 | } 74 | }, 75 | findResource: function( response, uuid ) { 76 | var index, resources, 77 | returnValue = false; 78 | 79 | if ( response && 80 | response.payload && 81 | response.payload.resources && 82 | response.payload.resources.length ) { 83 | 84 | resources = response.payload.resources; 85 | 86 | for ( index in resources ) { 87 | if ( resources[ index ].uri === "/a/" + uuid ) { 88 | return response.addr; 89 | } 90 | } 91 | } 92 | 93 | return returnValue; 94 | } 95 | } ); 96 | 97 | module.exports = TestUtils; 98 | --------------------------------------------------------------------------------