├── .gitignore ├── .npmignore ├── Gruntfile.js ├── LICENSE ├── README.md ├── ThirdPartyLicenses.txt ├── admin ├── components.js ├── configurator.js ├── device-info.js └── operational.js ├── api ├── cloud.proxy.js ├── control.proxy.js ├── mqtt │ └── connector.js ├── rest │ ├── actuations.def.js │ ├── admin.def.js │ ├── component.def.js │ ├── device.def.js │ ├── index.js │ ├── iot.admin.js │ ├── iot.auth.js │ ├── iot.connection.def.js │ └── iot.devices.js └── ws │ ├── connector.js │ └── errors.js ├── bin ├── admin.js └── agent.js ├── buildscripts ├── ci_code_validation.sh ├── ci_packaging.sh ├── ci_upload.sh ├── generate_package.sh └── jshint │ └── config.json ├── certs └── AddTrust_External_Root.pem ├── config ├── global.json └── index.js ├── data ├── device.json ├── deviceTest.json ├── sensorTest-list.json └── user.js ├── doc └── gettingStarted.pdf ├── gettingStarted.pdf ├── images └── agent-topo.png ├── iotkit-admin.js ├── iotkit-agent.js ├── iotkit-agent.service ├── lib ├── agent-message.js ├── cloud-message.js ├── commander │ ├── Readme.md │ ├── index.js │ └── package.json ├── common.js ├── comp.registration.js ├── data.submission.js ├── data │ ├── Attributes.data.js │ ├── Components.js │ └── Metric.data.js ├── httpClient.js ├── logger.js ├── proxies │ ├── index.js │ ├── iot.control.mqtt.js │ ├── iot.control.rest.js │ ├── iot.control.ws.js │ ├── iot.mqtt.js │ └── iot.rest.js ├── schema-validator │ ├── index.js │ ├── schema-validator.js │ └── schemas │ │ ├── component.json │ │ ├── data.json │ │ ├── index.js │ │ └── routing.json ├── sensors-store.js ├── server │ ├── udp.js │ └── upd.table.js └── utils.js ├── listeners ├── index.js ├── mqtt.js ├── rest.js └── tcp.js ├── migrate.js ├── package.json ├── send_udp.js ├── set-time.sh ├── sonar-project.properties ├── start-agent.sh ├── stop-agent.sh └── test ├── api_device.defTests.js ├── api_iot.devicesTests.js ├── lib_Metric.dataTests.js ├── lib_agentTests.js ├── lib_comp.registrationTests.js ├── lib_data.submissionTests.js ├── lib_httpClientTests.js ├── lib_mqtt-connector_connectorTests.js └── lib_sensors-storeTests.js /.gitignore: -------------------------------------------------------------------------------- 1 | lib-cov 2 | *.seed 3 | *.log 4 | *.csv 5 | *.dat 6 | *.out 7 | *.pid 8 | *.gz 9 | pids 10 | logs 11 | results 12 | node_modules 13 | *.idea/* 14 | *.orig 15 | */coverage/* 16 | */dist/* -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | tests/ 2 | images/ 3 | buildscripts/ 4 | *.idea/* 5 | *.orig 6 | */coverage/* 7 | */dist/* 8 | *.log 9 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | module.exports = function(grunt) { 26 | // Project configuration. 27 | var buildID = grunt.option('buildID') || 'local'; 28 | grunt.initConfig({ 29 | pkg: grunt.file.readJSON('package.json'), 30 | dirs: { 31 | jshint: 'buildscripts/jshint', 32 | jsfiles: ['Gruntfile.js', 33 | 'lib/**/*.js', 34 | 'api/**/*.js', 35 | 'admin/**/*.js', 36 | 'listeners/**/*.js'] 37 | }, 38 | license_finder: { 39 | default_options: { 40 | options: { 41 | production: false, 42 | directory: process.cwd(), 43 | csv: true, 44 | out: 'licenses.csv' 45 | } 46 | }, 47 | production : { 48 | options: { 49 | production: true, 50 | directory: process.cwd(), 51 | csv: true, 52 | out: 'licenses_production.csv' 53 | } 54 | } 55 | }, 56 | jshint: { 57 | options: { 58 | jshintrc: '<%= dirs.jshint %>/config.json', 59 | ignores: ['lib/deprected/*.js'] 60 | }, 61 | local: { 62 | src: ['<%= dirs.jsfiles %>'], 63 | options: { 64 | force: true 65 | } 66 | }, 67 | teamcity: { 68 | src: ['<%= dirs.jsfiles %>'], 69 | options: { 70 | force: true, 71 | reporter: require('jshint-teamcity') 72 | } 73 | } 74 | }, 75 | compress: { 76 | teamcity: { 77 | options: { 78 | archive: 'dist/'+'<%= pkg.name %>_' + buildID + ".tgz", 79 | mode: 'tgz' 80 | }, 81 | files: [{cwd: '.', 82 | expand: true, 83 | src: ['**/*.js', '**/*.sh', 'config.json', '!node_modules/**', '!dist/**', '!test/**', '!Gruntfile.js'], 84 | /* this is the root folder of untar file */ 85 | dest: '<%= pkg.name %>/' 86 | } 87 | ] 88 | } 89 | }, 90 | mocha_istanbul: { 91 | local: { 92 | src: 'test/', // the folder, not the files 93 | options: { 94 | ui: 'bdd', 95 | coverage: true, 96 | recursive: true, 97 | reporter: 'list', 98 | timeout: 20000, 99 | mask: '*Tests.js', 100 | check: { 101 | lines: 60, 102 | statements: 60, 103 | function: 60 104 | }, 105 | root: '.', // define where the cover task should consider the root of libraries that are covered by tests 106 | coverageFolder: 'dist/coverage', 107 | reportFormats: ['lcov'] 108 | } 109 | }, 110 | teamcity: { 111 | src: 'test/', // the folder, not the files 112 | options: { 113 | ui: 'bdd', 114 | coverage: true, 115 | recursive: true, 116 | reporter: 'mocha-teamcity-reporter', 117 | timeout: 20000, 118 | mask: '*Tests.js', 119 | /*check: { 120 | lines: 70, 121 | statements: 70, 122 | function: 70 123 | },*/ 124 | root: '.', // define where the cover task should consider the root of libraries that are covered by tests 125 | coverageFolder: 'dist/coverage', 126 | reportFormats: ['lcov', 'teamcity'] 127 | } 128 | } 129 | } 130 | }); 131 | 132 | grunt.event.on('coverage', function(lcovFileContents, done){ 133 | // Check below 134 | done(); 135 | }); 136 | 137 | grunt.loadNpmTasks('grunt-mocha-istanbul'); 138 | grunt.loadNpmTasks('grunt-license-finder'); 139 | 140 | // Load the plugin that provides the "uglify" task. 141 | grunt.loadNpmTasks('grunt-contrib-jshint'); 142 | grunt.loadNpmTasks('grunt-contrib-compress'); 143 | 144 | // Default task(s). 145 | grunt.registerTask('default', ['jshint:local', 'mocha_istanbul:local']); 146 | 147 | grunt.registerTask('teamcity_codevalidation', ['jshint:teamcity', 148 | 'mocha_istanbul:teamcity']); 149 | grunt.registerTask('packaging', ['compress:teamcity']); 150 | }; 151 | 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 - 2015, Intel Corporation 2 | 3 | Redistribution and use in source and binary forms, with or without modification, 4 | are permitted provided that the following conditions are met: 5 | 6 | * Redistributions of source code must retain the above copyright notice, 7 | this list of conditions and the following disclaimer. 8 | * Redistributions in binary form must reproduce the above copyright notice, 9 | this list of conditions and the following disclaimer in the documentation 10 | and/or other materials provided with the distribution. 11 | 12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | -------------------------------------------------------------------------------- /ThirdPartyLicenses.txt: -------------------------------------------------------------------------------- 1 | ========================================================================= 2 | IoT Kit Agent 3 | 4 | BSD-2 5 | ========================================================================= 6 | 7 | Copyright (c) 2015, Intel 8 | All rights reserved. 9 | 10 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 11 | 12 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 13 | 14 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 17 | 18 | ========================================================================= 19 | commander.js 20 | 21 | MIT 22 | ========================================================================= 23 | 24 | Copyright (c) 2011 TJ Holowaychuk 25 | 26 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 27 | 28 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 29 | 30 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 31 | -------------------------------------------------------------------------------- /admin/components.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var Cloud = require("../api/cloud.proxy"), 26 | Message = require('../lib/agent-message'), 27 | utils = require("../lib/utils").init(), 28 | logger = require("../lib/logger").init(), 29 | Component = require('../lib/data/Components'), 30 | common = require('../lib/common'), 31 | schemaValidation = require('../lib/schema-validator'); 32 | 33 | var configFileKey = { 34 | accountId : 'account_id', 35 | gatewayId : 'gateway_id', 36 | deviceId: 'device_id', 37 | deviceName: 'device_name', 38 | deviceToken: 'device_token', 39 | sensorList: 'sensor_list' 40 | }; 41 | 42 | var resetComponents = function () { 43 | var data = []; 44 | common.saveToDeviceConfig(configFileKey.sensorList, data); 45 | }; 46 | 47 | var resetToken = function () { 48 | common.saveToDeviceConfig(configFileKey.accountId, false); 49 | common.saveToDeviceConfig(configFileKey.deviceToken, false); 50 | }; 51 | 52 | var registerComponents = function (comp, catalogid) { 53 | logger.info("Starting registration ..." ); 54 | utils.getDeviceId(function (id) { 55 | var cloud = Cloud.init(logger, id); 56 | cloud.activate(function (status) { 57 | var r = 0; 58 | if (status === 0) { 59 | var agentMessage = Message.init(cloud, logger); 60 | var msg = { 61 | "n": comp, 62 | "t": catalogid 63 | }; 64 | agentMessage.handler(msg, function (stus) { 65 | if (stus.status === 0) { 66 | logger.info("Component registered", stus); 67 | } else { 68 | logger.error("Component Not registered: ", stus); 69 | } 70 | process.exit(r); 71 | }, schemaValidation.schemas.component.REG); 72 | 73 | } else { 74 | logger.error("Error in the registration process ...", status); 75 | process.exit(1); 76 | } 77 | 78 | }); 79 | }); 80 | }; 81 | 82 | function registerObservation (comp, value) { 83 | utils.getDeviceId(function (id) { 84 | var cloud = Cloud.init(logger, id); 85 | if (cloud.isActivated()) { 86 | cloud.setDeviceCredentials(); 87 | var r = 0; 88 | var agentMessage = Message.init(cloud, logger); 89 | var msg = { 90 | "n": comp, 91 | "v": value 92 | }; 93 | agentMessage.handler(msg, function (stus) { 94 | logger.info("Observation Sent", stus); 95 | process.exit(r); 96 | }); 97 | } else { 98 | logger.error("Error in the Observation Device is not activated ..."); 99 | process.exit(1); 100 | } 101 | }); 102 | } 103 | 104 | function pullActuations() { 105 | logger.info("Pulling actuations from IoT Cloud"); 106 | utils.getDeviceId(function (id) { 107 | var cloud = Cloud.init(logger, id); 108 | if (cloud.isActivated()) { 109 | cloud.setDeviceCredentials(); 110 | cloud.pullActuations(); 111 | } else { 112 | logger.error("Error when pulling Actuations. Device is not activated ..."); 113 | process.exit(1); 114 | } 115 | }); 116 | } 117 | 118 | function updateMetadata() { 119 | utils.getDeviceId(function (id) { 120 | var cloud = Cloud.init(logger, id); 121 | if(cloud.isActivated()) { 122 | cloud.update(); 123 | } else { 124 | logger.error("Error in updating Device is not activated ..."); 125 | process.exit(1); 126 | } 127 | }); 128 | } 129 | 130 | function getComponentsList () { 131 | var storeFile = common.getDeviceConfig(); 132 | if(storeFile) { 133 | var com = storeFile[configFileKey.sensorList]; 134 | var table = new Component.Register(com); 135 | console.log(table.toString()); 136 | } 137 | } 138 | function getCatalogList () { 139 | utils.getDeviceId(function (id) { 140 | var cloud = Cloud.init(logger, id); 141 | cloud.catalog(function (catalog) { 142 | if (catalog) { 143 | var table = new Component.Table(catalog); 144 | logger.info("# of Component @ Catalog : ", catalog.length); 145 | console.log(table.toString()); 146 | } 147 | process.exit(0); 148 | }); 149 | }); 150 | } 151 | 152 | module.exports = { 153 | addCommand : function (program) { 154 | program 155 | .command('register ') 156 | .description('Registers a component in the device.') 157 | .action(registerComponents); 158 | program 159 | .command('reset-components') 160 | .description('Clears the component list.') 161 | .action(resetComponents); 162 | program 163 | .command('observation ') 164 | .description('Sends an observation for the device, for the specific component.') 165 | .action(registerObservation); 166 | program 167 | .command('catalog') 168 | .description("Displays the Catalog from the device's account.") 169 | .action(getCatalogList); 170 | program 171 | .command('components') 172 | .description('Displays components registered for this device.') 173 | .action(getComponentsList); 174 | program 175 | .command('initialize') 176 | .description("Resets both the token and the component's list.") 177 | .action(function() { 178 | resetComponents(); 179 | resetToken(); 180 | logger.info("Initialized"); 181 | }); 182 | program 183 | .command('update') 184 | .description('Send update device request to dashboard') 185 | .action(updateMetadata); 186 | program 187 | .command('pull-actuations') 188 | .description('Fetches actuations from last time action was executed or 24h if never and executes them one by one') 189 | .action(pullActuations); 190 | } 191 | }; 192 | -------------------------------------------------------------------------------- /admin/device-info.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var utils = require("./../lib/utils").init(); 26 | 27 | utils.getExternalInfo(function(data){ 28 | console.dir(data); 29 | }); 30 | -------------------------------------------------------------------------------- /admin/operational.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var logger = require("../lib/logger").init(), 26 | Cloud = require("../api/cloud.proxy"), 27 | utils = require("../lib/utils").init(), 28 | common = require('../lib/common'), 29 | configurator = require('../admin/configurator'), 30 | WebSocket = require('../api/ws/connector'), 31 | wsErrors = require('../api/ws/errors'), 32 | exec = require('child_process').exec, 33 | exitMessageCode = { 34 | "OK": 0, 35 | "ERROR": 1 36 | }; 37 | 38 | var activate = function (code) { 39 | logger.debug("Activation started ..."); 40 | utils.getDeviceId(function (id) { 41 | var cloud = Cloud.init(logger, id); 42 | cloud.activate(code, function (err) { 43 | var exitCode = exitMessageCode.OK; 44 | cloud.disconnect(); 45 | if (err) { 46 | logger.error("Error in the activation process ...", err); 47 | exitCode = exitMessageCode.ERROR; 48 | } 49 | else{ 50 | configurator.setDeviceId(id); 51 | } 52 | process.exit(exitCode); 53 | }); 54 | }); 55 | }; 56 | 57 | function testConnection () { 58 | var conf = common.getConfig(); 59 | var host; 60 | if(conf.default_connector === 'rest+ws') { 61 | host = conf.connector['rest'].host; 62 | } else { 63 | host = conf.connector[conf.default_connector].host; 64 | } 65 | utils.getDeviceId(function (id) { 66 | var cloud = Cloud.init(logger, id); 67 | cloud.test(function (res) { 68 | var exitCode = exitMessageCode.OK; 69 | if (res) { 70 | logger.info("Connected to %s", host); 71 | logger.info("Environment: %s", res.currentSetting); 72 | logger.info("Build: %s", res.build); 73 | logger.debug("Full response %j", res ); 74 | } else { 75 | logger.error("Connection failed to %s", host); 76 | exitCode = exitMessageCode.ERROR; 77 | } 78 | if(conf.default_connector === 'rest+ws') { 79 | var WS = WebSocket.singleton(conf, logger); 80 | WS.client.on('connect', function(connection) { 81 | connection.on('close', function(reasonCode, description) { 82 | logger.info('Websocket connection closed. Reason: ' + reasonCode + ' ' + description); 83 | process.exit(exitCode); 84 | }); 85 | connection.on('message', function(message) { 86 | var messageObject; 87 | try { 88 | messageObject = JSON.parse(message.utf8Data); 89 | } catch (err) { 90 | logger.error('Received unexpected message from WS server: ' + message.utf8Data); 91 | exitCode = exitMessageCode.ERROR; 92 | } 93 | if (messageObject.code === wsErrors.Success.ReceivedPong.code) { 94 | logger.info('Connection to Web Socket Server successful'); 95 | connection.close(); 96 | } 97 | }); 98 | var pingMessageObject = { 99 | "type": "ping" 100 | }; 101 | connection.sendUTF(JSON.stringify(pingMessageObject)); 102 | }); 103 | logger.info("Trying to connect to WS server ..."); 104 | WS.connect(); 105 | setTimeout(function() { 106 | logger.error("Timeout exceeded. Program will exit."); 107 | process.exit(exitCode); 108 | }, conf.connector.ws.testTimeout); 109 | } 110 | 111 | }); 112 | }); 113 | } 114 | 115 | function setActualTime () { 116 | utils.getDeviceId(function (id) { 117 | var cloud = Cloud.init(logger, id); 118 | cloud.getActualTime(function (time) { 119 | var exitCode = exitMessageCode.OK; 120 | if (time) { 121 | var command = 'date -u "' + time + '"'; 122 | exec(command, function (error, stdout, stderr) { 123 | if (error) { 124 | logger.error("Error changing data: ", stderr); 125 | logger.debug("Date error: ", error); 126 | exitCode = exitMessageCode.ERROR; 127 | } else { 128 | logger.info("UTC time changed for: ", stdout); 129 | } 130 | process.exit(exitCode); 131 | }); 132 | } else { 133 | logger.error("Failed to receive actual time"); 134 | exitCode = exitMessageCode.ERROR; 135 | process.exit(exitCode); 136 | } 137 | }); 138 | }); 139 | } 140 | 141 | module.exports = { 142 | addCommand : function (program) { 143 | program 144 | .command('test') 145 | .description('Tries to reach the server (using the current protocol).') 146 | .action(function() { 147 | testConnection(); 148 | }); 149 | 150 | program 151 | .command('activate ') 152 | .description('Activates the device.') 153 | .action(activate); 154 | 155 | program 156 | .command('set-time') 157 | .description('Sets actual UTC time on your device.') 158 | .action(function() { 159 | setActualTime(); 160 | }); 161 | } 162 | }; 163 | -------------------------------------------------------------------------------- /api/control.proxy.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var Sensor = require('../lib/sensors-store'), 27 | proxyConnector = require('../lib/proxies'); 28 | 29 | function IoTKitControl(conf, logger, deviceId, customProxy){ 30 | var me = this; 31 | me.logger = logger; 32 | me.proxy = customProxy || proxyConnector; 33 | me.deviceId = deviceId; 34 | me.store = Sensor.init("device.json", logger); 35 | me.gatewayId = conf.gateway_id || deviceId; 36 | me.logger.debug('Cloud Proxy Created with Cloud Handler ', me.proxy.type); 37 | me.receiverInfo = {port: conf.receivers.udp_port, address: conf.receivers.udp_address}; 38 | 39 | } 40 | 41 | IoTKitControl.prototype.send = function (actuation) { 42 | var me = this; 43 | if(me.dispatcher) { 44 | me.dispatcher.send(me.receiverInfo, actuation); 45 | } 46 | 47 | return true; 48 | }; 49 | 50 | IoTKitControl.prototype.controlAction = function () { 51 | var me = this; 52 | var handler = function(message) { 53 | var comp = me.store.byCid(message.content.componentId); 54 | if (comp) { 55 | var actuation = { 56 | component: comp.name, 57 | command: message.content.command, 58 | argv: message.content.params 59 | }; 60 | me.logger.info("Sending actuation: " + JSON.stringify(actuation)); 61 | return me.send(actuation); 62 | } 63 | }; 64 | return handler; 65 | }; 66 | 67 | IoTKitControl.prototype.bind = function (dispatcher, callback) { 68 | var me = this; 69 | var data = {deviceId: me.deviceId}; 70 | me.dispatcher = dispatcher; 71 | me.proxy.controlCommandListen(data, me.controlAction(), function() { 72 | if (callback) { 73 | callback(); 74 | } 75 | }); 76 | }; 77 | 78 | exports.init = function(conf, logger, deviceId) { 79 | if(conf.default_connector === 'rest+ws') { 80 | proxyConnector = proxyConnector.geControlConnector('ws'); 81 | } else { 82 | proxyConnector = proxyConnector.geControlConnector('mqtt'); 83 | } 84 | return new IoTKitControl(conf, logger, deviceId); 85 | }; 86 | -------------------------------------------------------------------------------- /api/rest/actuations.def.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var config = require('../../config'); 27 | var common = require('../../lib/common'); 28 | 29 | var ConnectionOptions = require('./iot.connection.def.js'); 30 | var GET_METHOD = 'GET'; 31 | 32 | var apiconf = config.connector.rest; 33 | //variable to be returned 34 | var IoTKiT = {}; 35 | /** 36 | */ 37 | function ActuationsOption(data) { 38 | this.pathname = common.buildPath(common.buildPath(apiconf.path.device.actuations, data.accountId), data.deviceId); 39 | if(data.from) { 40 | this.query = { from: data.from }; 41 | } 42 | this.token = data.deviceToken; 43 | ConnectionOptions.call(this); 44 | this.method = GET_METHOD; 45 | } 46 | ActuationsOption.prototype = new ConnectionOptions(); 47 | ActuationsOption.prototype.constructor = ActuationsOption; 48 | IoTKiT.ActuationsOption = ActuationsOption; 49 | 50 | module.exports = IoTKiT; 51 | -------------------------------------------------------------------------------- /api/rest/admin.def.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var config = require('../../config'); 27 | var url = require('url'); 28 | 29 | var ConnectionOptions = require('./iot.connection.def.js'); 30 | var GET_METHOD = 'GET'; 31 | 32 | var apiconf = config.connector.rest; 33 | 34 | //variable to be returned 35 | var IoTKiT = {}; 36 | /** 37 | * Connection attributes to redirect to Intel Itendtity Main Page 38 | */ 39 | function HealthOption() { 40 | this.pathname = apiconf.path.health; 41 | this.token = null; 42 | ConnectionOptions.call(this); 43 | this.method = GET_METHOD; 44 | } 45 | HealthOption.prototype = new ConnectionOptions(); 46 | HealthOption.prototype.constructor = HealthOption; 47 | IoTKiT.HealthOption = HealthOption; 48 | 49 | function ExternalInfoOption() { 50 | this.pathname = ''; 51 | this.token = null; 52 | ConnectionOptions.call(this); 53 | var urlT = { 54 | hostname: 'ipinfo.io', 55 | port: 80, 56 | protocol: 'http' 57 | }; 58 | this.url = url.format(urlT); 59 | this.method = GET_METHOD; 60 | } 61 | ExternalInfoOption.prototype = new ConnectionOptions(); 62 | ExternalInfoOption.prototype.constructor = ExternalInfoOption; 63 | IoTKiT.ExternalInfoOption = ExternalInfoOption; 64 | 65 | function TimeOption() { 66 | this.pathname = apiconf.path.time; 67 | this.token = null; 68 | ConnectionOptions.call(this); 69 | this.method = GET_METHOD; 70 | } 71 | TimeOption.prototype = new ConnectionOptions(); 72 | TimeOption.prototype.constructor = TimeOption; 73 | IoTKiT.TimeOption = TimeOption; 74 | 75 | module.exports = IoTKiT; 76 | -------------------------------------------------------------------------------- /api/rest/component.def.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var config = require('../../config'); 27 | 28 | var ConnectionOptions = require('./iot.connection.def.js'); 29 | var GET_METHOD = 'GET'; 30 | 31 | var apiconf = config.connector.rest; 32 | //variable to be returned 33 | var IoTKiT = {}; 34 | /** 35 | */ 36 | function CatalogOption(data) { 37 | this.pathname = apiconf.path.cmpcatalog.catalog; 38 | this.token = data.deviceToken; 39 | ConnectionOptions.call(this); 40 | this.method = GET_METHOD; 41 | } 42 | CatalogOption.prototype = new ConnectionOptions(); 43 | CatalogOption.prototype.constructor = CatalogOption; 44 | IoTKiT.CatalogOption = CatalogOption; 45 | 46 | module.exports = IoTKiT; 47 | -------------------------------------------------------------------------------- /api/rest/device.def.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var config = require('../../config'); 27 | var common = require('../../lib/common'); 28 | 29 | var ConnectionOptions = require('./iot.connection.def.js'); 30 | 31 | var GET_METHOD = 'GET'; 32 | var PUT_METHOD = 'PUT'; 33 | var POST_METHOD = 'POST'; 34 | 35 | var apiconf = config.connector.rest; 36 | 37 | //variable to be returned 38 | var IoTKiT = {}; 39 | /** 40 | * Connection attributes to redirect to Intel Itendtity Main Page 41 | */ 42 | function DeviceActivateOption(data) { 43 | this.pathname = common.buildPath(apiconf.path.device.act, data.deviceId); 44 | this.token = null; 45 | ConnectionOptions.call(this); 46 | this.method = PUT_METHOD; 47 | this.body = JSON.stringify(data.body); 48 | } 49 | DeviceActivateOption.prototype = new ConnectionOptions(); 50 | DeviceActivateOption.prototype.constructor = DeviceActivateOption; 51 | IoTKiT.DeviceActivateOption = DeviceActivateOption; 52 | 53 | 54 | 55 | function DeviceGetOption (data) { 56 | this.pathname = common.buildPath(apiconf.path.device.get, data.deviceId); 57 | this.token = data.deviceToken; 58 | ConnectionOptions.call(this); 59 | this.method = GET_METHOD; 60 | 61 | } 62 | DeviceGetOption.prototype = new ConnectionOptions(); 63 | DeviceGetOption.prototype.constructor = DeviceGetOption; 64 | IoTKiT.DeviceGetOption = DeviceGetOption; 65 | 66 | 67 | 68 | function DeviceMetadataOption (data) { 69 | this.pathname = common.buildPath(apiconf.path.device.update, data.deviceId); 70 | this.token = data.deviceToken; 71 | ConnectionOptions.call(this); 72 | this.method = PUT_METHOD; 73 | this.body = JSON.stringify(data.body); 74 | } 75 | DeviceMetadataOption.prototype = new ConnectionOptions(); 76 | DeviceMetadataOption.prototype.constructor = DeviceMetadataOption; 77 | IoTKiT.DeviceMetadataOption = DeviceMetadataOption; 78 | /** 79 | * Build an object option for Request package. 80 | * @param data 81 | * @constructor 82 | * */ 83 | function DeviceComponentOption (data) { 84 | this.pathname = common.buildPath(apiconf.path.device.components, data.deviceId); 85 | this.token = data.deviceToken; 86 | ConnectionOptions.call(this); 87 | this.method = POST_METHOD; 88 | this.body = JSON.stringify(data.body); 89 | } 90 | DeviceComponentOption.prototype = new ConnectionOptions(); 91 | DeviceComponentOption.prototype.constructor = DeviceComponentOption; 92 | IoTKiT.DeviceComponentOption = DeviceComponentOption; 93 | 94 | 95 | /** 96 | * @description Build an object option for Request package. 97 | * @param data 98 | * @constructor 99 | */ 100 | function DeviceSubmitDataOption (data) { 101 | this.pathname = common.buildPath(apiconf.path.submit.data, data.deviceId); 102 | ConnectionOptions.call(this); 103 | this.method = POST_METHOD; 104 | this.headers = { 105 | "Content-type" : "application/json", 106 | "Authorization" : "Bearer " + data.deviceToken 107 | }; 108 | if (data.forwarded) { 109 | this.headers["forwarded"] = true; 110 | delete data.forwarded; 111 | } 112 | this.body = JSON.stringify(data.body); 113 | } 114 | DeviceSubmitDataOption.prototype = new ConnectionOptions(); 115 | DeviceSubmitDataOption.prototype.constructor = DeviceSubmitDataOption; 116 | IoTKiT.DeviceSubmitDataOption = DeviceSubmitDataOption; 117 | 118 | module.exports = IoTKiT; 119 | -------------------------------------------------------------------------------- /api/rest/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | module.exports = { 27 | devices: require('./iot.devices'), 28 | admin: require('./iot.admin') 29 | }; -------------------------------------------------------------------------------- /api/rest/iot.admin.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var httpClient = require('../../lib/httpClient'); 27 | var AdminDef = require('./admin.def'); 28 | var CatalogDef = require('./component.def'); 29 | var ActuationsDef = require('./actuations.def'); 30 | 31 | /** 32 | * It passes to a callback the access token 33 | */ 34 | module.exports.health = function(callback) { 35 | var health = new AdminDef.HealthOption(); 36 | return httpClient.httpRequest(health, callback); 37 | }; 38 | module.exports.getCatalog = function (data, callback) { 39 | var catalog = new CatalogDef.CatalogOption(data); 40 | return httpClient.httpRequest(catalog, callback); 41 | }; 42 | module.exports.pullActuations = function (data, callback) { 43 | var actuations = new ActuationsDef.ActuationsOption(data); 44 | return httpClient.httpRequest(actuations, callback); 45 | }; 46 | module.exports.getExternalInfo = function (callback) { 47 | var external = new AdminDef.ExternalInfoOption(); 48 | return httpClient.httpRequest(external, callback); 49 | }; 50 | module.exports.getActualTime = function (callback) { 51 | var time = new AdminDef.TimeOption(); 52 | return httpClient.httpRequest(time, callback); 53 | }; -------------------------------------------------------------------------------- /api/rest/iot.auth.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var config = require('../../config'); 26 | 27 | var ConnectionOptions = require('./iot.connection.def.js'); 28 | var apiconf = config.connector.rest; 29 | 30 | var IoTKiT = {}; 31 | /** 32 | * Connection attributes to redirect to Intel Identity Main Page 33 | */ 34 | function GetTokenOption () { 35 | this.pathname = apiconf.auth.token; 36 | this.token = null; 37 | ConnectionOptions.call(this); 38 | this.method = 'POST'; 39 | this.body = JSON.stringify({username: apiconf.auth.usr, 40 | password: apiconf.auth.pass}); 41 | } 42 | GetTokenOption.prototype = new ConnectionOptions(); 43 | GetTokenOption.prototype.constructor = GetTokenOption; 44 | IoTKiT.GetTokenOption = GetTokenOption; 45 | module.exports = IoTKiT; 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /api/rest/iot.connection.def.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var url = require('url'), 27 | config = require('../../config'); 28 | 29 | 30 | var apiconf = config.connector.rest; 31 | /** 32 | * Top of the hierarchy. Common attributes to every 33 | * Connection Options 34 | */ 35 | function ConnectionOptions() { 36 | if (apiconf.proxy && apiconf.proxy.host) { 37 | if(apiconf.proxy.host.indexOf('://') < 0) { 38 | apiconf.proxy.host = 'http://' + apiconf.proxy.host; 39 | } 40 | this.proxy = apiconf.proxy.host + ":" + apiconf.proxy.port; 41 | } else if(process.env.https_proxy) { 42 | this.proxy = process.env.https_proxy; 43 | } else if(process.env.http_proxy) { 44 | this.proxy = process.env.http_proxy; 45 | } 46 | var urlT = { 47 | hostname: apiconf.host, 48 | port: apiconf.port, 49 | pathname: this.pathname, 50 | protocol: apiconf.protocol, 51 | query: this.query 52 | }; 53 | if (apiconf.strictSSL === false) { 54 | this.strictSSL = false; 55 | } 56 | this.timeout = apiconf.timeout; 57 | this.url = url.format(urlT); 58 | this.headers = { 59 | "Content-type" : "application/json" 60 | }; 61 | if (this.token) { 62 | this.headers["Authorization"] = "Bearer " + this.token; 63 | } 64 | delete this.token; 65 | } 66 | 67 | module.exports = ConnectionOptions; -------------------------------------------------------------------------------- /api/rest/iot.devices.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var httpClient = require('../../lib/httpClient'); 27 | var DeviceDef = require('./device.def'); 28 | var AuthDef = require('./iot.auth'); 29 | var async = require('async'); 30 | /** 31 | * It passes to a callback the access token 32 | */ 33 | module.exports.registerDevice = function(data, callback) { 34 | var devOpt = new DeviceDef.DeviceActivateOption(data); 35 | return httpClient.httpRequest(devOpt, callback); 36 | }; 37 | /** 38 | * @description It will put a data to analytics UI using device id at data. 39 | * @param data the data contain the device id and metadata at body to sent 40 | * @param callback 41 | */ 42 | module.exports.updateMetadataDevice = function(data, callback) { 43 | var metaDataOpt = new DeviceDef.DeviceMetadataOption(data); 44 | return httpClient.httpRequest(metaDataOpt, callback); 45 | }; 46 | 47 | module.exports.submitData = function (data, callback) { 48 | var submitDataOpt = new DeviceDef.DeviceSubmitDataOption(data); 49 | return httpClient.httpRequest(submitDataOpt, callback); 50 | }; 51 | 52 | /** 53 | * @description Gets a device from analytics UI using device id in data. 54 | * @param data contains device id and metadata in body to sent 55 | * @param callback 56 | */ 57 | 58 | module.exports.getDevice = function(data, callback) { 59 | var metaDataOpt = new DeviceDef.DeviceGetOption(data); 60 | return httpClient.httpRequest(metaDataOpt, callback); 61 | }; 62 | 63 | 64 | 65 | /** 66 | * The function will Register all components to Analytics using POST 67 | * if the body is an Array it will send individual post since the bulk api is 68 | * not ready 69 | * @param data 70 | * @param callback 71 | */ 72 | module.exports.registerComponents = function (data, callback){ 73 | var tmp = data.body; 74 | delete data.body; 75 | //TODO this shall be replace with Parallel 76 | // when the bulk operation be ready. 77 | if (!Array.isArray(tmp)) { 78 | tmp = [tmp]; 79 | } 80 | async.parallel(tmp.map(function (comp) { 81 | var tempData = JSON.parse(JSON.stringify(data)); 82 | tempData.body = comp; 83 | return function (done) { 84 | var compOpt = new DeviceDef.DeviceComponentOption(tempData); 85 | httpClient.httpRequest(compOpt, function(err, response){ 86 | done(err, response); 87 | }); 88 | }; 89 | }), function (err, response) { 90 | console.info("Attributes sent"); 91 | callback(err, response); 92 | } 93 | ); 94 | }; 95 | /** 96 | * 97 | * @param callback 98 | */ 99 | module.exports.getCredential = function (callback) { 100 | var authOption = new AuthDef.GetTokenOption(); 101 | return httpClient.httpRequest(authOption, callback); 102 | }; 103 | -------------------------------------------------------------------------------- /api/ws/errors.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2015, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 'use strict'; 25 | 26 | module.exports = { 27 | Errors: { 28 | DatabaseError: {code: 500, content: "Internal server error, unable to set authorization data for device"}, 29 | InvalidToken: {code: 401, content: "Invalid device token for device"}, 30 | WrongDataFormat: {code: 401, content: "Wrong message format"} 31 | }, 32 | Success: { 33 | Subscribed: {code: 200, content: "Record in database update for device"}, 34 | ReceivedActuation: {code: 1024}, 35 | ReceivedPong: {code: 202, content: "Pong received"} 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /bin/admin.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | Copyright (c) 2014, Intel Corporation 5 | 6 | Redistribution and use in source and binary forms, with or without modification, 7 | are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, 10 | this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 19 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 22 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | 27 | "use strict"; 28 | var admin= require('../lib/commander'), 29 | pkgJson = require('../package.json'), 30 | auth = require('../admin/operational'), 31 | components = require('../admin/components'), 32 | configurator = require('../admin/configurator'), 33 | fs = require('fs'), 34 | path = require('path'), 35 | logger = require("../lib/logger").init(); 36 | 37 | admin.version(pkgJson.version) 38 | .option('-C, --config [path]', "Set the config file path", function(userConfDirectory){ 39 | process.userConfigPath = path.resolve(userConfDirectory , "user.js"); 40 | if (fs.existsSync(process.userConfigPath)) { 41 | logger.info("\'" + process.userConfigPath + "\'" + 42 | ' will be used as user config file.'); 43 | } 44 | else{ 45 | logger.error("\'" + process.userConfigPath + "\'" + 46 | ' not contains user.js config file.'); 47 | process.exit(1); 48 | } 49 | }); 50 | /* 51 | /* 52 | * Add commando as option 53 | */ 54 | auth.addCommand(admin); 55 | components.addCommand(admin); 56 | configurator.addCommand(admin); 57 | 58 | admin.command('*') 59 | .description('Error message for non valid command') 60 | .action(function(){ 61 | console.log("\'" + admin.args[0] + "\'" + 62 | ' is not a valid command.'); 63 | }); 64 | if(process.argv[2] === 'observation') { 65 | if(process.argv.length === 5) { 66 | if(process.argv[4][0] === '-') { 67 | var args = []; 68 | var unknown = []; 69 | for(var i = 2; i <= 4; i++) { 70 | args.push(process.argv[i]); 71 | } 72 | var parsed = {args: args, unknown: unknown}; 73 | admin.rawArgs = process.argv; 74 | admin.args = args; 75 | var result = admin.parseArgs(admin.args, parsed.unknown); 76 | } 77 | else { 78 | admin.parse(process.argv); 79 | } 80 | } 81 | else { 82 | console.log("\'" + process.argv[2] + "\'" + 83 | ' should contains component_name value.'); 84 | process.exit(1); 85 | } 86 | } 87 | else { 88 | admin.parse(process.argv); 89 | } 90 | /* 91 | * Run if the command were specified at parameter 92 | */ 93 | /* 94 | * Help and versions also as commands 95 | */ 96 | if (!admin.args.length || admin.args[0] === 'help') { 97 | admin.help(); 98 | } 99 | admin.command('version') 100 | .description('output the version number') 101 | .action(admin.version(pkgJson.version)); 102 | 103 | 104 | -------------------------------------------------------------------------------- /bin/agent.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | Copyright (c) 2014, Intel Corporation 4 | 5 | Redistribution and use in source and binary forms, with or without modification, 6 | are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, 9 | this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 15 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 16 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 17 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 18 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 19 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 20 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 21 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 22 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 23 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 24 | */ 25 | "use strict"; 26 | var utils = require("../lib/utils").init(), 27 | logger = require("../lib/logger").init(), 28 | Cloud = require("../api/cloud.proxy"), 29 | Control = require ("../api/control.proxy"), 30 | Message = require('../lib/agent-message'), 31 | udpServer = require('../lib/server/udp'), 32 | Listener = require("../listeners/"), 33 | admin= require('../lib/commander'), 34 | pkgJson = require('../package.json'), 35 | path = require('path'), 36 | fs = require('fs'), 37 | conf = require('../config'); 38 | 39 | process.on("uncaughtException", function(err) { 40 | logger.error("UncaughtException:", err.message); 41 | logger.error(err.stack); 42 | // let the process exit so that forever can restart it 43 | process.exit(1); 44 | }); 45 | 46 | admin.version(pkgJson.version) 47 | .option('-C, --config [path]', "Set the config file path", function(userConfDirectory){ 48 | process.userConfigPath = path.resolve(userConfDirectory , "user.js"); 49 | if (fs.existsSync(process.userConfigPath)) { 50 | logger.info("\'" + process.userConfigPath + "\'" + 51 | ' will be used as user config file.'); 52 | conf = require(process.userConfigPath); 53 | } 54 | else{ 55 | logger.error("\'" + process.userConfigPath + "\'" + 56 | ' not contains user.js config file.'); 57 | process.exit(1); 58 | } 59 | }); 60 | 61 | admin.parse(process.argv); 62 | 63 | utils.getDeviceId(function (id) { 64 | var cloud = Cloud.init(logger, id); 65 | cloud.activate(function (status) { 66 | if (status === 0) { 67 | var udp = udpServer.singleton(conf.listeners.udp_port, logger); 68 | 69 | var agentMessage = Message.init(cloud, logger); 70 | logger.info("Starting listeners..."); 71 | udp.listen(agentMessage.handler); 72 | //TODO only allow for mqtt Connector, until rest will be implemented 73 | if (conf.default_connector === 'mqtt' || conf.default_connector === 'rest+ws'){ 74 | var ctrl = Control.init(conf, logger, id); 75 | ctrl.bind(udp); 76 | } 77 | Listener.TCP.init(conf.listeners, logger, agentMessage.handler); 78 | 79 | } else { 80 | logger.error("Error in activation... err # : ", status); 81 | process.exit(status); 82 | } 83 | }); 84 | }); 85 | -------------------------------------------------------------------------------- /buildscripts/ci_code_validation.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | ROOT_PATH=`pwd` 26 | buildscript_dir=${ROOT_PATH}/buildscripts 27 | 28 | BUILD_PREFIX="SCRIPT: " 29 | BUILD_PREFIX_ERROR="SCRIPT-ERROR: " 30 | GRUNT=${ROOT_PATH}/node_modules/grunt-cli/bin/grunt 31 | DIST=dist 32 | 33 | 34 | cd ${buildscript_dir}/.. 35 | 36 | 37 | npm config set proxy http://proxy-mu.intel.com:911 38 | npm config set https-proxy http://proxy-mu.intel.com:911 39 | npm install 40 | if [ $? -ne 0 ]; then 41 | echo "${BUILD_PREFIX_ERROR}You had an error installing Node Packages. Aborting." 42 | exit 1 43 | fi 44 | 45 | echo "${BUILD_PREFIX}I'll run grunt teamcity" 46 | 47 | ${GRUNT} teamcity_codevalidation 48 | 49 | if [ $? -ne 0 ]; then 50 | echo "${BUILD_PREFIX_ERROR}Your grunt test failed again. Last command didn't work. Aborting now." 51 | exit 1 52 | fi 53 | 54 | echo "${BUILD_PREFIX}grunt test was executed without errors. You're lucky ... so far ..." 55 | -------------------------------------------------------------------------------- /buildscripts/ci_packaging.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | BUILD=$1 26 | ROOT_PATH=`pwd` 27 | buildscript_dir=${ROOT_PATH}/buildscripts 28 | 29 | BUILD_PREFIX="SCRIPT: " 30 | BUILD_PREFIX_ERROR="SCRIPT-ERROR: " 31 | GRUNT=${ROOT_PATH}/node_modules/grunt-cli/bin/grunt 32 | DIST=dist 33 | 34 | cd ${buildscript_dir}/.. 35 | 36 | echo "${BUILD_PREFIX}I'll package the code" 37 | 38 | ${GRUNT} packaging --buildID=${BUILD} 39 | 40 | if [ $? -ne 0 ]; then 41 | echo "${BUILD_PREFIX_ERROR}Your grunt test failed again. Last command didn't work. Aborting now." 42 | exit 1 43 | fi 44 | 45 | echo "${BUILD_PREFIX}grunt test was executed without errors. You're lucky ... so far ..." 46 | -------------------------------------------------------------------------------- /buildscripts/ci_upload.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | BUILD=$1 26 | ROOT_PATH=`pwd` 27 | buildscript_dir=${ROOT_PATH}/buildscripts 28 | 29 | BUILD_PREFIX="SCRIPT: " 30 | BUILD_PREFIX_ERROR="SCRIPT-ERROR: " 31 | GRUNT=${ROOT_PATH}/node_modules/grunt-cli/bin/grunt 32 | DIST=dist 33 | 34 | cd ${buildscript_dir}/.. 35 | 36 | echo "${BUILD_PREFIX}I'll package the code" 37 | 38 | ${GRUNT} packaging --buildID=${BUILD} 39 | 40 | if [ $? -ne 0 ]; then 41 | echo "${BUILD_PREFIX_ERROR}Your grunt test failed again. Last command didn't work. Aborting now." 42 | exit 1 43 | fi 44 | 45 | echo "${BUILD_PREFIX}grunt test was executed without errors. You're lucky ... so far ..." 46 | -------------------------------------------------------------------------------- /buildscripts/generate_package.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | buildscript_dir=`pwd` 26 | 27 | BUILD_PREFIX="SCRIPT: " 28 | BUILD_PREFIX_ERROR="SCRIPT-ERROR: " 29 | COMPONENT="iotkit-ui" 30 | export http_proxy=http://proxy-us.intel.com:911 31 | export https_proxy=https://proxy-us.intel.com:911 32 | 33 | # getopt 34 | help() { 35 | echo "$0: build and upload package" 36 | echo "Usage: $0 -e ENVIRONMENT" 37 | } 38 | 39 | OPTS=$(getopt -o he: -l environment: -- "$@") 40 | eval set -- "$OPTS" 41 | 42 | while true; do 43 | case "$1" in 44 | -h) help; shift;; 45 | -e) ENV=$2; shift 2;; 46 | --environment) ENV=$2; shift 2;; 47 | --) shift; break;; 48 | esac 49 | done 50 | 51 | if [ "x$ENV" == "x" ] 52 | then 53 | help 54 | exit 1 55 | fi 56 | 57 | # main 58 | 59 | cd $buildscript_dir/.. 60 | 61 | echo "${BUILD_PREFIX}I'll generate ${COMPONENT} deployment package for you. I'm so good .." 62 | echo Building ${COMPONENT} for $ENV environment 63 | 64 | tar -zcvf ${COMPONENT}.tar.gz package.json app.js config.js dashboard engine iot-entities lib templates 65 | if [ $? -ne 0 ] 66 | then 67 | echo "${BUILD_PREFIX_ERROR}Failed again. Package generation failed. Aborting." 68 | exit 1 69 | else 70 | if [ ! -d buildscripts/build ] 71 | then 72 | mkdir buildscripts/build 73 | fi 74 | mv ${COMPONENT}.tar.gz buildscripts/build 75 | fi 76 | 77 | echo "${BUILD_PREFIX}Created tar file ${COMPONENT} for you. I'm so good .." 78 | echo "${BUILD_PREFIX}Now upload to S3. I'm so good .." 79 | 80 | s3cmd sync buildscripts/build/${COMPONENT}.tar.gz s3://dpeak/artifacts/$ENV/${COMPONENT}.tar.gz 81 | if [ $? -ne 0 ] 82 | then 83 | echo "${BUILD_PREFIX_ERROR}Failed again. S3 upload failed. Aborting." 84 | exit 1 85 | fi 86 | 87 | echo "${BUILD_PREFIX}${COMPONENT} package was generated and uploaded to S3 without errors. You're lucky ... so far ..." 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /buildscripts/jshint/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "curly": true, 3 | "eqeqeq": true, 4 | "immed": true, 5 | "latedef": true, 6 | "newcap": true, 7 | "noarg": true, 8 | "sub": true, 9 | "undef": true, 10 | "eqnull": true, 11 | "browser": true, 12 | "unused": true, 13 | "indent": false, 14 | "node" : true, 15 | "globals": { "angular": true, 16 | "Rickshaw": true, 17 | "iotApp": true, 18 | "iotController": true, 19 | "iotServices": true} 20 | } 21 | -------------------------------------------------------------------------------- /certs/AddTrust_External_Root.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEU 3 | MBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFs 4 | IFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290 5 | MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFowbzELMAkGA1UEBhMCU0Ux 6 | FDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRUcnVzdCBFeHRlcm5h 7 | bCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0EgUm9v 8 | dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvt 9 | H7xsD821+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9 10 | uMq/NzgtHj6RQa1wVsfwTz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzX 11 | mk6vBbOmcZSccbNQYArHE504B4YCqOmoaSYYkKtMsE8jqzpPhNjfzp/haW+710LX 12 | a0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy2xSoRcRdKn23tNbE7qzN 13 | E0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv77+ldU9U0 14 | WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYD 15 | VR0PBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0 16 | Jvf6xCZU7wO94CTLVBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRU 17 | cnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx 18 | IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN 19 | AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH 20 | YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 21 | 6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC 22 | Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX 23 | c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a 24 | mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= 25 | -----END CERTIFICATE----- 26 | -------------------------------------------------------------------------------- /config/global.json: -------------------------------------------------------------------------------- 1 | { 2 | "data_directory": "./data", 3 | "listeners": { 4 | "mqtt_port": 1884, 5 | "rest_port": 9090, 6 | "udp_port": 41234, 7 | "tcp_port": 7070 8 | }, 9 | "receivers": { 10 | "udp_port": 41235, 11 | "udp_address": "0.0.0.0" 12 | }, 13 | "logger": { 14 | "LEVEL": "info", 15 | "PATH": "/tmp/", 16 | "MAX_SIZE": 134217728 17 | }, 18 | "default_connector": "rest+ws", 19 | "connector": { 20 | "mqtt": { 21 | "host": "broker.us.enableiot.com", 22 | "port": 8883, 23 | "qos": 1, 24 | "retain": false, 25 | "secure": true, 26 | "strictSSL": true, 27 | "retries": 5, 28 | "topic": { 29 | "device_status": "device/{deviceid}/activation", 30 | "device_activation": "server/devices/{deviceid}/activation", 31 | "device_metadata": "server/devices/{deviceid}/metadata", 32 | "metric_topic": "server/metric/{accountid}/{deviceid}", 33 | "device_component_add": "server/devices/{deviceid}/components/add", 34 | "device_component_status": "device/{deviceid}/components", 35 | "device_component_del": "server/devices/{deviceid}/components/delete", 36 | "health": "server/devices/{deviceid}/health", 37 | "health_status": "device/{deviceid}/health", 38 | "cmpcatalog": "server/devices/{deviceid}/cmpcatalog", 39 | "cmpcatalog_status": "device/{deviceid}/cmpcatalog", 40 | "control_command": "device/{gwid}/control" 41 | } 42 | }, 43 | "rest": { 44 | "host": "dashboard.us.enableiot.com", 45 | "port": 443, 46 | "protocol": "https", 47 | "strictSSL": true, 48 | "timeout": 30000, 49 | "proxy": { 50 | "host": false, 51 | "port": false 52 | }, 53 | "path": { 54 | "device": { 55 | "act": "/v1/api/devices/{deviceid}/activation", 56 | "get": "/v1/api/devices/{deviceid}", 57 | "update": "/v1/api/devices/{deviceid}", 58 | "components": "/v1/api/devices/{deviceid}/components", 59 | "actuations": "/v1/api/accounts/{accountId}/control/devices/{deviceId}" 60 | }, 61 | "submit": { 62 | "data": "/v1/api/data/{deviceid}" 63 | }, 64 | "cmpcatalog": { 65 | "catalog": "/v1/api/cmpcatalog", 66 | "component": "/v1/api/cmpcatalog/{componentId}" 67 | }, 68 | "health": "/v1/api/health", 69 | "time": "/v1/api/time" 70 | } 71 | }, 72 | "ws": { 73 | "host": "ws.us.enableiot.com", 74 | "port": 443, 75 | "minRetryTime": 2500, 76 | "maxRetryTime": 600000, 77 | "testTimeout": 40000, 78 | "pingPongIntervalMs": 30000, 79 | "enablePingPong": true, 80 | "secure": true, 81 | "proxy": { 82 | "host": false, 83 | "port": false 84 | } 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /config/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var fs = require('fs'), 26 | path = require('path'), 27 | localConf = "./global.json"; 28 | 29 | var config = {}; 30 | var userConfig = ''; 31 | 32 | function isAbsolutePath(location) { // Change to path.isAbsolute when upgrading Node.js 33 | return path.resolve(location) === path.normalize(location); 34 | } 35 | 36 | if (fs.existsSync(path.join(__dirname, localConf))) { 37 | config = require(localConf); 38 | if(isAbsolutePath(config['data_directory'])) { 39 | userConfig = path.resolve(config['data_directory'], 'user.js'); 40 | } else { 41 | userConfig = path.resolve(__dirname, "..", config['data_directory'], 'user.js'); 42 | } 43 | if(fs.existsSync(userConfig)){ 44 | config = require(userConfig); 45 | } 46 | } else { 47 | console.error("Failed to find config file"); 48 | process.exit(0); 49 | } 50 | 51 | /* override for local development if NODE_ENV is defined to local */ 52 | if (process.env.NODE_ENV && (process.env.NODE_ENV.toLowerCase().indexOf("local") !== -1)) { 53 | config.connector.mqtt.host = "127.0.0.1"; 54 | config.connector.mqtt.port = 61613; 55 | config.connector.mqtt.secure = false; 56 | config.connector.rest.host = "127.0.0.1"; 57 | config.connector.rest.port = 80; 58 | config.connector.rest.protocol= "http"; 59 | config.logger.PATH = './'; 60 | } 61 | module.exports = config; 62 | -------------------------------------------------------------------------------- /data/device.json: -------------------------------------------------------------------------------- 1 | { 2 | "activation_retries": 10, 3 | "activation_code": null, 4 | "device_id": false, 5 | "device_name": false, 6 | "device_loc": [ 7 | 88.34, 8 | 64.22047, 9 | 0 10 | ], 11 | "gateway_id": false, 12 | "device_token": false, 13 | "account_id": false, 14 | "sensor_list": [] 15 | } -------------------------------------------------------------------------------- /data/deviceTest.json: -------------------------------------------------------------------------------- 1 | { 2 | "activation_retries": 10, 3 | "activation_code": null, 4 | "device_id": false, 5 | "device_name": false, 6 | "device_loc": [ 7 | 88.34, 8 | 64.22047, 9 | 0 10 | ], 11 | "gateway_id": false, 12 | "deviceToken": "", 13 | "accountId": "", 14 | "sensor_list": [ 15 | { 16 | "name": 1, 17 | "type": 2, 18 | "cid": 3 19 | }, 20 | { 21 | "name": 21, 22 | "type": 22, 23 | "cid": 23 24 | }, 25 | { 26 | "name": 31, 27 | "type": 32, 28 | "cid": 33 29 | } 30 | ] 31 | } -------------------------------------------------------------------------------- /data/sensorTest-list.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": 1, 4 | "type": 2, 5 | "cid": 3 6 | }, 7 | { 8 | "name": 21, 9 | "type": 22, 10 | "cid": 23 11 | }, 12 | { 13 | "name": 31, 14 | "type": 32, 15 | "cid": 33 16 | } 17 | ] -------------------------------------------------------------------------------- /data/user.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 26 | var fs = require('fs'), 27 | path = require('path'), 28 | localConf = path.resolve(fs.realpathSync(process.argv[1]), "../config/global.json"); 29 | 30 | if (!fs.existsSync(localConf)) { 31 | localConf = path.resolve("config/global.json"); 32 | } 33 | 34 | var config = {}; 35 | 36 | if (fs.existsSync(localConf)) { 37 | config = require(localConf); 38 | } else { 39 | console.error("Failed to find config file in ", localConf); 40 | console.error("Run your command from directory", path.dirname(fs.realpathSync(process.argv[1]))); 41 | process.exit(0); 42 | } 43 | 44 | module.exports = config; 45 | 46 | /* Example usage: 47 | * config.default_connector = "mqtt"; 48 | * config.connector.rest.timeout = 60000; 49 | * 50 | * config.connector.rest.proxy.host = "example.com"; 51 | * config.connector.rest.proxy.port = 1180; 52 | * 53 | * // For HTTPS proxy specify protocol https:// in host 54 | * config.connector.ws.proxy.host = "example.com"; 55 | * config.connector.ws.proxy.port = 911; 56 | * 57 | * Please write your changes for config below. 58 | */ 59 | 60 | -------------------------------------------------------------------------------- /doc/gettingStarted.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enableiot/iotkit-agent/0e1624fb5bf90eb30ddd1e9e2b50b11de0cf7d91/doc/gettingStarted.pdf -------------------------------------------------------------------------------- /gettingStarted.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enableiot/iotkit-agent/0e1624fb5bf90eb30ddd1e9e2b50b11de0cf7d91/gettingStarted.pdf -------------------------------------------------------------------------------- /images/agent-topo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enableiot/iotkit-agent/0e1624fb5bf90eb30ddd1e9e2b50b11de0cf7d91/images/agent-topo.png -------------------------------------------------------------------------------- /iotkit-admin.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | Copyright (c) 2014, Intel Corporation 5 | 6 | Redistribution and use in source and binary forms, with or without modification, 7 | are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, 10 | this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 19 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 22 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | "use strict"; 27 | var admin = require("./bin/admin"); 28 | -------------------------------------------------------------------------------- /iotkit-agent.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | Copyright (c) 2014, Intel Corporation 5 | 6 | Redistribution and use in source and binary forms, with or without modification, 7 | are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, 10 | this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 19 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 22 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | "use strict"; 27 | var utils = require("./bin/agent"); 28 | 29 | -------------------------------------------------------------------------------- /iotkit-agent.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=iotkit-agent 3 | After=network.target 4 | 5 | [Service] 6 | ExecStart=/usr/bin/iotkit-agent 7 | Restart=always 8 | RestartSec=10s 9 | Environment=NODE_ENV=production 10 | 11 | [Install] 12 | WantedBy=multi-user.target 13 | -------------------------------------------------------------------------------- /lib/agent-message.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 'use strict'; 25 | var Comp = require('./comp.registration'), 26 | Data = require('./data.submission'), 27 | Sensor = require('./sensors-store'), 28 | schemaValidation = require('./schema-validator'), 29 | updTable = require('./server/upd.table').singleton(); 30 | 31 | var MessageHandler = function(connector, logger) { 32 | var me = this; 33 | me.store = Sensor.init("device.json", logger); 34 | me.comp = Comp.init(connector, me.store, logger); 35 | me.data = Data.init(connector, me.store, logger); 36 | 37 | me.handler = function (msg, callback, msgSchema) { 38 | if (msgSchema) { 39 | me.validator = schemaValidation.validate(msg, msgSchema); 40 | } else { 41 | me.validator = schemaValidation.validate(msg, schemaValidation.schemas.routing.ROUTE); 42 | } 43 | 44 | var msgResult = []; 45 | 46 | if (me.validator.length === 0) { 47 | updTable.add(msg.n, msg.r); 48 | delete msg.r; 49 | me.data.submission(msg, function (status_sub) { 50 | if (status_sub === false) { 51 | msgResult.push(new Error("None Submit data matching")); 52 | me.comp.registration(msg, function (status_reg) { 53 | if (status_reg === false) { 54 | msgResult.push(new Error("None Registration Component Matching")); 55 | logger.error('Invalid message received (empty) : ', msg, msgResult); 56 | } 57 | if (callback) { 58 | return callback(status_reg); 59 | } 60 | }); 61 | return; 62 | } 63 | if (callback) { 64 | callback(status_sub); 65 | } 66 | 67 | }); 68 | } else { 69 | schemaValidation.parseErrors(me.validator, callback); 70 | } 71 | }; 72 | }; 73 | 74 | var init = function(connector, logger) { 75 | return new MessageHandler(connector, logger); 76 | }; 77 | module.exports = { 78 | init : init 79 | }; 80 | -------------------------------------------------------------------------------- /lib/cloud-message.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | "use strict"; 25 | var util = require('./utils').init(); 26 | 27 | /** 28 | * 29 | * @param deviceId 30 | * @param gatewayId 31 | * @constructor 32 | */ 33 | module.exports.Metadata = function Metadata (gatewayId) { 34 | this.gatewayId = gatewayId ; 35 | this.loc = util.getLocation(); 36 | this.attributes = util.getAgentAttr(); 37 | }; 38 | 39 | module.exports.metadataExtended = function (gatewayId, callback) { 40 | /* 41 | It's retrieve the external info. 42 | */ 43 | var att = { 44 | attributes : util.getAgentAttr(), 45 | gatewayId : gatewayId 46 | }; 47 | callback(att); 48 | /* util.externalInfo(function (data) { 49 | if (data) { 50 | att.loc = data.loc.split(','); 51 | att.loc = att.loc.map(function (od){ 52 | return parseInt(od); 53 | }); 54 | //att.tags = [data.region, data.country]; 55 | } else { 56 | att.loc = util.getLocation(); 57 | } 58 | callback(att); 59 | }); 60 | */ 61 | }; 62 | -------------------------------------------------------------------------------- /lib/commander/Readme.md: -------------------------------------------------------------------------------- 1 | # Commander.js 2 | 3 | The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). 4 | 5 | [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js) 6 | 7 | ## Installation 8 | 9 | $ npm install commander 10 | 11 | ## Option parsing 12 | 13 | Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. 14 | 15 | ```js 16 | #!/usr/bin/env node 17 | 18 | /** 19 | * Module dependencies. 20 | */ 21 | 22 | var program = require('commander'); 23 | 24 | program 25 | .version('0.0.1') 26 | .option('-p, --peppers', 'Add peppers') 27 | .option('-P, --pineapple', 'Add pineapple') 28 | .option('-b, --bbq', 'Add bbq sauce') 29 | .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') 30 | .parse(process.argv); 31 | 32 | console.log('you ordered a pizza with:'); 33 | if (program.peppers) console.log(' - peppers'); 34 | if (program.pineapple) console.log(' - pineapple'); 35 | if (program.bbq) console.log(' - bbq'); 36 | console.log(' - %s cheese', program.cheese); 37 | ``` 38 | 39 | Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. 40 | 41 | ## Automated --help 42 | 43 | The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: 44 | 45 | ``` 46 | $ ./examples/pizza --help 47 | 48 | Usage: pizza [options] 49 | 50 | Options: 51 | 52 | -V, --version output the version number 53 | -p, --peppers Add peppers 54 | -P, --pineapple Add pineapple 55 | -b, --bbq Add bbq sauce 56 | -c, --cheese Add the specified type of cheese [marble] 57 | -h, --help output usage information 58 | 59 | ``` 60 | 61 | ## Coercion 62 | 63 | ```js 64 | function range(val) { 65 | return val.split('..').map(Number); 66 | } 67 | 68 | function list(val) { 69 | return val.split(','); 70 | } 71 | 72 | function collect(val, memo) { 73 | memo.push(val); 74 | return memo; 75 | } 76 | 77 | function increaseVerbosity(v, total) { 78 | return total + 1; 79 | } 80 | 81 | program 82 | .version('0.0.1') 83 | .usage('[options] ') 84 | .option('-i, --integer ', 'An integer argument', parseInt) 85 | .option('-f, --float ', 'A float argument', parseFloat) 86 | .option('-r, --range ..', 'A range', range) 87 | .option('-l, --list ', 'A list', list) 88 | .option('-o, --optional [value]', 'An optional value') 89 | .option('-c, --collect [value]', 'A repeatable value', []) 90 | .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) 91 | .parse(process.argv); 92 | 93 | console.log(' int: %j', program.integer); 94 | console.log(' float: %j', program.float); 95 | console.log(' optional: %j', program.optional); 96 | program.range = program.range || []; 97 | console.log(' range: %j..%j', program.range[0], program.range[1]); 98 | console.log(' list: %j', program.list); 99 | console.log(' collect: %j', program.collect); 100 | console.log(' verbosity: %j', program.verbose); 101 | console.log(' args: %j', program.args); 102 | ``` 103 | 104 | ## Custom help 105 | 106 | You can display arbitrary `-h, --help` information 107 | by listening for "--help". Commander will automatically 108 | exit once you are done so that the remainder of your program 109 | does not execute causing undesired behaviours, for example 110 | in the following executable "stuff" will not output when 111 | `--help` is used. 112 | 113 | ```js 114 | #!/usr/bin/env node 115 | 116 | /** 117 | * Module dependencies. 118 | */ 119 | 120 | var program = require('../'); 121 | 122 | function list(val) { 123 | return val.split(',').map(Number); 124 | } 125 | 126 | program 127 | .version('0.0.1') 128 | .option('-f, --foo', 'enable some foo') 129 | .option('-b, --bar', 'enable some bar') 130 | .option('-B, --baz', 'enable some baz'); 131 | 132 | // must be before .parse() since 133 | // node's emit() is immediate 134 | 135 | program.on('--help', function(){ 136 | console.log(' Examples:'); 137 | console.log(''); 138 | console.log(' $ custom-help --help'); 139 | console.log(' $ custom-help -h'); 140 | console.log(''); 141 | }); 142 | 143 | program.parse(process.argv); 144 | 145 | console.log('stuff'); 146 | ``` 147 | 148 | yielding the following help output: 149 | 150 | ``` 151 | 152 | Usage: custom-help [options] 153 | 154 | Options: 155 | 156 | -h, --help output usage information 157 | -V, --version output the version number 158 | -f, --foo enable some foo 159 | -b, --bar enable some bar 160 | -B, --baz enable some baz 161 | 162 | Examples: 163 | 164 | $ custom-help --help 165 | $ custom-help -h 166 | 167 | ``` 168 | 169 | ## .outputHelp() 170 | 171 | Output help information without exiting. 172 | 173 | ## .help() 174 | 175 | Output help information and exit immediately. 176 | 177 | ## Links 178 | 179 | - [API documentation](http://visionmedia.github.com/commander.js/) 180 | - [ascii tables](https://github.com/LearnBoost/cli-table) 181 | - [progress bars](https://github.com/visionmedia/node-progress) 182 | - [more progress bars](https://github.com/substack/node-multimeter) 183 | - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) 184 | 185 | ## License 186 | 187 | (The MIT License) 188 | 189 | Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> 190 | 191 | Permission is hereby granted, free of charge, to any person obtaining 192 | a copy of this software and associated documentation files (the 193 | 'Software'), to deal in the Software without restriction, including 194 | without limitation the rights to use, copy, modify, merge, publish, 195 | distribute, sublicense, and/or sell copies of the Software, and to 196 | permit persons to whom the Software is furnished to do so, subject to 197 | the following conditions: 198 | 199 | The above copyright notice and this permission notice shall be 200 | included in all copies or substantial portions of the Software. 201 | 202 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, 203 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 204 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 205 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 206 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 207 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 208 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 209 | -------------------------------------------------------------------------------- /lib/commander/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "commander", 3 | "version": "2.2.0", 4 | "description": "the complete solution for node.js command-line programs", 5 | "keywords": [ 6 | "command", 7 | "option", 8 | "parser", 9 | "prompt", 10 | "stdin" 11 | ], 12 | "author": { 13 | "name": "TJ Holowaychuk", 14 | "email": "tj@vision-media.ca" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/visionmedia/commander.js.git" 19 | }, 20 | "devDependencies": { 21 | "should": ">= 0.0.1" 22 | }, 23 | "scripts": { 24 | "test": "make test" 25 | }, 26 | "main": "index", 27 | "engines": { 28 | "node": ">= 0.6.x" 29 | }, 30 | "files": [ 31 | "index.js" 32 | ], 33 | "bugs": { 34 | "url": "https://github.com/visionmedia/commander.js/issues" 35 | }, 36 | "homepage": "https://github.com/visionmedia/commander.js", 37 | "_id": "commander@2.2.0", 38 | "dist": { 39 | "shasum": "175ad4b9317f3ff615f201c1e57224f55a3e91df", 40 | "tarball": "http://registry.npmjs.org/commander/-/commander-2.2.0.tgz" 41 | }, 42 | "_from": "commander@2.2.0", 43 | "_npmVersion": "1.3.15", 44 | "_npmUser": { 45 | "name": "tjholowaychuk", 46 | "email": "tj@vision-media.ca" 47 | }, 48 | "maintainers": [ 49 | { 50 | "name": "tjholowaychuk", 51 | "email": "tj@vision-media.ca" 52 | } 53 | ], 54 | "directories": {}, 55 | "_shasum": "175ad4b9317f3ff615f201c1e57224f55a3e91df", 56 | "_resolved": "https://registry.npmjs.org/commander/-/commander-2.2.0.tgz", 57 | "readme": "ERROR: No README data found!" 58 | } 59 | -------------------------------------------------------------------------------- /lib/comp.registration.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 'use strict'; 26 | var schemaValidation = require('./schema-validator'); 27 | 28 | /** 29 | * Sample Message the will be built in order to registrate component to IOT Analytics 30 | * @type {{cid: string, name: string, type: string}} 31 | */ 32 | var sampleCompReg = { 33 | "n": "Temperature Sensor 1", 34 | "t": "temperature.v1.0" 35 | }; 36 | 37 | var Component = function (connector, SensorStore, logT) { 38 | var me = this; 39 | var logger = logT || {}; 40 | me.connector = connector; 41 | me.store = SensorStore; 42 | schemaValidation.setLogger(logger); 43 | me.regValidator = schemaValidation.validateSchema(schemaValidation.schemas.component.REG); 44 | 45 | /** 46 | * It will process a component registration if it is not a componet registration will return false 47 | * @param msg 48 | * @returns {boolean} 49 | */ 50 | 51 | me.registration = function (msg, callback) { 52 | if (me.regValidator(msg)) { 53 | logger.debug ("Component Registration detected ", msg); 54 | var sen = {name: msg.n, 55 | type: msg.t}; 56 | var comp = me.store.exist(sen); 57 | /** 58 | * if Component Exist an has different type 59 | */ 60 | if (!comp) { 61 | sen = me.store.createId(sen); 62 | me.connector.regComponent(sen, function (com) { 63 | if (com.status === 0) { 64 | sen = com[0] || com; 65 | me.store.add(sen); 66 | me.store.save(); 67 | } else { 68 | me.store.del(sen.cid); 69 | } 70 | return callback(com); 71 | }); 72 | } else { 73 | logger.error("Component already Exist at Agent ", comp); 74 | return callback(true); 75 | } 76 | 77 | } else { 78 | logger.debug('Comp. registration - Invalid message format. Expected %j got %j', sampleCompReg, msg, {}); 79 | return callback(false); 80 | } 81 | 82 | }; 83 | me.deregister = function (msg) { 84 | if (me.desregValidator(msg)) { 85 | var sen = {name: msg.n, 86 | type: msg.t}; 87 | var comp = me.store.delete(sen); 88 | /** 89 | * if Component Exist an has different type 90 | */ 91 | if (!comp) { 92 | me.connector.desRegComponent(sen); 93 | me.store.save(); 94 | } 95 | return true; 96 | } else { 97 | logger.info('Invalid message format. Expected %j got %j', sampleCompReg, msg, {}); 98 | return false; 99 | } 100 | }; 101 | 102 | }; 103 | var init = function(connector, SensorStore, logger) { 104 | return new Component(connector, SensorStore, logger); 105 | }; 106 | module.exports.init = init; 107 | -------------------------------------------------------------------------------- /lib/data.submission.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 'use strict'; 26 | var schemaValidation = require('./schema-validator'), 27 | Metric = require('./data/Metric.data').init(); 28 | 29 | /** 30 | * 31 | * @type {{n: string, v: number}} 32 | */ 33 | var sampleMetric = {"n": "temp-sensor", 34 | "v": 26.7 }; 35 | 36 | 37 | 38 | var Data = function (connector, SensorStore, logT) { 39 | var me = this; 40 | me.logger = logT || {}; 41 | me.connector = connector; 42 | me.store = SensorStore; 43 | me.validator = schemaValidation.validateSchema(schemaValidation.schemas.data.SUBMIT); 44 | 45 | /** 46 | * It will process a component registration if 47 | * it is not a component registration will return false 48 | * @param msg 49 | * @returns {boolean} 50 | */ 51 | me.submission = function (msg, callback) { 52 | if (me.validator(msg)) { 53 | me.logger.info ("Submitting: ", msg); 54 | var cid = me.store.byName(msg.n); 55 | var metric = new Metric(); 56 | if (cid) { 57 | msg.cid = cid.cid; //Add component id to convert to Proper Data ingestion message 58 | metric.set(msg); 59 | me.connector.dataSubmit(metric, function(dat){ 60 | me.logger.info("Response received: ", dat); 61 | return callback(dat); 62 | }); 63 | } else { 64 | me.logger.error('Data submission - could not find time series with the name: %s.', msg.n); 65 | return callback(true); 66 | } 67 | } else { 68 | me.logger.debug('Data submission - No detected Expected %j got %j', sampleMetric, msg, {}); 69 | return callback(false); 70 | } 71 | }; 72 | 73 | }; 74 | var init = function(connector, SensorStore, logger) { 75 | return new Data(connector, SensorStore, logger); 76 | }; 77 | module.exports.init = init; -------------------------------------------------------------------------------- /lib/data/Attributes.data.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var dataAttrUtil; 27 | 28 | /** 29 | * Interface to manage the Metric Payload require by Advances Analytics. 30 | * @constructor 31 | */ 32 | function Attributes () { 33 | this.on = Date.now(); 34 | this.gatewayId = null; 35 | this.deviceId = null; 36 | this.loc = dataAttrUtil.getLocation(); 37 | this.attributes = dataAttrUtil.getAgentAttr(); 38 | } 39 | 40 | 41 | Attributes.prototype.forToMQTTPayload = function () { 42 | 43 | }; 44 | 45 | Attributes.prototype.fromMQTTToRest = function () { 46 | 47 | }; 48 | 49 | 50 | 51 | 52 | module.exports.init = function (dataExtComp) { 53 | dataAttrUtil = dataExtComp; 54 | return Attributes; 55 | }; 56 | -------------------------------------------------------------------------------- /lib/data/Components.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | "use strict"; 25 | var Table = require('cli-table'); 26 | function ComponentTable (data) { 27 | if (data) { 28 | this.table = new Table({head: ['id : t', 'kind', 'measure']}); 29 | var i, 30 | l = data.length; 31 | for (i = 0 ; i < l ; ++i) { 32 | var o = data[i]; 33 | this.table.push([o.id, o.type, o.dimension]); 34 | } 35 | } 36 | } 37 | ComponentTable.prototype.toString = function () { 38 | return this.table.toString(); 39 | }; 40 | 41 | module.exports.Table = ComponentTable; 42 | 43 | 44 | function ComponentList (data) { 45 | this.table = new Table({head: ['id : t', 'Name', 'cID']}); 46 | var i, 47 | l = data.length; 48 | for (i = 0 ; i < l ; ++i) { 49 | var o = data[i]; 50 | this.table.push([o.type, o.name, o.cid]); 51 | } 52 | } 53 | ComponentList.prototype.toString = function () { 54 | return this.table.toString(); 55 | }; 56 | 57 | module.exports.Register = ComponentList; 58 | -------------------------------------------------------------------------------- /lib/data/Metric.data.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | 27 | /** 28 | * Interface to manage the Metric Payload require by Advances Analytics. 29 | * @constructor 30 | */ 31 | function Metric () { 32 | this.accountId = null; 33 | this.did = null; 34 | this.on = Date.now(); 35 | this.count = 0; 36 | this.data = []; 37 | } 38 | Metric.prototype.dataAsRoot = function (value) { 39 | 40 | var cid = this.nameOfComponentId || "cid"; 41 | var theValue = value.v || value.value || "0"; 42 | var dataTemporal = { 43 | "on": value.on || this.on, 44 | "value": theValue.toString() //Conversion since JSON schema required. 45 | }; 46 | dataTemporal[cid] = value.componentId || value.cid || this.globalCid; 47 | if (value.loc) { 48 | dataTemporal.loc = value.loc; 49 | } 50 | if (value.attributes) { 51 | dataTemporal.attributes = value.attributes; 52 | } 53 | this.data.push(dataTemporal); 54 | }; 55 | Metric.prototype.dataAsArray = function (msg) { 56 | var l = msg.data.length; 57 | this.globalCid = msg.cid || this.componentId ; 58 | for (var i = 0; i < l; i++) { 59 | var value = msg.data[i]; 60 | this.dataAsRoot(value); 61 | } 62 | }; 63 | Metric.prototype.dataProcess = function (datoArr) { 64 | if (datoArr) { 65 | if (Array.isArray(datoArr.data)) { 66 | this.dataAsArray(datoArr); 67 | } else { 68 | this.dataAsRoot(datoArr); 69 | } 70 | } 71 | }; 72 | Metric.prototype.set = function (data) { 73 | this.accountId = data.accountId || data.domainId; 74 | this.did = data.deviceId; 75 | this.on = data.on || this.on; 76 | this.data = []; 77 | this.dataProcess(data); 78 | this.count = this.data.length; 79 | }; 80 | /** 81 | * This convert the Message at Analitics RT to Adavance Analytics Data Injection Payload 82 | * @param msg 83 | * @returns {Metric} 84 | */ 85 | Metric.prototype.convertToMQTTPayload = function() { 86 | this.dataProcess(); 87 | this.count = this.data.length; 88 | return this; 89 | }; 90 | Metric.prototype.convertToRestPayload = function() { 91 | this.nameOfComponentId = "componentId"; 92 | this.dataProcess(); 93 | /** 94 | * Since the schema validation of Rest Interface if so hard 95 | * it is removed the none require parameter 96 | */ 97 | this.data.forEach(function (ob){ 98 | if (ob.cid) { 99 | ob.componentId = ob.cid; 100 | delete ob.cid; 101 | } 102 | }); 103 | 104 | delete this.did; 105 | delete this.count; 106 | delete this.nameOfComponentId; 107 | delete this.globalCid; 108 | return this; 109 | }; 110 | /* 111 | Metric.prototype.fromMQTTToRestPayload = function(msg) { 112 | this.on = msg.on || this.on; 113 | this.accountId = msg.accountId; 114 | this.data = []; 115 | this.nameOfComponentId = "componentId"; 116 | if (Array.isArray(msg.data)) { 117 | this.dataAsArray(msg); 118 | } else { 119 | this.dataAsRoot(msg); 120 | } 121 | *//* 122 | Since the health require de account id it will not delete 123 | *//* 124 | 125 | *//** 126 | * Since the schema validation of Rest Interface if so hard 127 | * it is removed the none require parameter 128 | *//* 129 | delete this.did; 130 | delete this.count; 131 | delete this.nameOfComponentId; 132 | return this; 133 | };*/ 134 | module.exports.init = function () { 135 | return Metric; 136 | }; 137 | -------------------------------------------------------------------------------- /lib/httpClient.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | /** 27 | * 28 | * @param options object that contains attributes of the connection 29 | * @param callback function to be called at the end of the request 30 | * @param useHttp if true, it sends a HTTP request, If not, it uses a 31 | * HTTPS request 32 | */ 33 | var request = require('request'); 34 | 35 | function processResponse(res, body, callback) { 36 | var data = null; 37 | if (res.statusCode === 200 || res.statusCode === 201) { 38 | if (res.headers['content-type'] && res.headers['content-type'].indexOf('application/json') > -1) { 39 | try { 40 | data = JSON.parse(body); 41 | } catch (e) { 42 | data = null; 43 | } 44 | } else { 45 | data = null; 46 | } 47 | } else if (res.statusCode === 204) { 48 | data = { 49 | status: "Done" 50 | }; 51 | } 52 | return callback(data); 53 | } 54 | 55 | module.exports.httpRequest = function createRequest (options, callback) { 56 | return request(options, function (error, response, body) { 57 | if (!error && (response.statusCode === 200 || 58 | response.statusCode === 201 || 59 | response.statusCode === 204)) { 60 | processResponse(response, body, function (data) { 61 | return callback(null, data); 62 | }); 63 | } else { 64 | error = error || body; 65 | return callback(error); 66 | } 67 | }); 68 | }; -------------------------------------------------------------------------------- /lib/logger.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | "use strict"; 25 | var winston = require('winston'), 26 | path = require('path'), 27 | conf = require('../config').logger; 28 | 29 | exports.init = function() { 30 | 31 | var logTransports = [ 32 | new (winston.transports.Console)({ 33 | level: conf.LEVEL || 'debug', 34 | colorize: true, 35 | timestamp: true 36 | }), 37 | new (winston.transports.File)({ 38 | filename: path.join((process.platform ==='win32' ? process.env.temp : conf.PATH), 'agent.log'), 39 | level: conf.LEVEL || 'info', 40 | timestamp: true, 41 | maxsize: conf.MAX_SIZE, //128 MB 42 | maxFiles: 1 43 | }) 44 | ]; 45 | 46 | return new (winston.Logger)({ 47 | transports: logTransports, 48 | exitOnError: false 49 | }); 50 | 51 | }; 52 | -------------------------------------------------------------------------------- /lib/proxies/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 'use strict'; 26 | 27 | var config = require("../../config"), 28 | logger = require("../../lib/logger").init(); 29 | 30 | var currentProxy; 31 | 32 | exports.getProxyConnector = function(proxy) { 33 | try { 34 | if(!currentProxy){ 35 | var protocol = (proxy || config.default_connector); 36 | logger.debug("Proxy Connector : %s ", protocol , "to be Set"); 37 | var Proxy; 38 | if(protocol === 'rest+ws') { 39 | protocol = 'rest'; 40 | } 41 | Proxy = require("./iot." + protocol); 42 | currentProxy = Proxy.init(config, logger); 43 | } 44 | return currentProxy; 45 | } 46 | catch(err) { 47 | logger.error("Proxy Connector does not exist: ", err); 48 | } 49 | }; 50 | 51 | var currentControl; 52 | exports.geControlConnector = function(proxy) { 53 | try { 54 | if(!currentControl){ 55 | var protocol = (proxy || config.default_connector); 56 | logger.debug("Proxy Connector : %s ", protocol , "to be Set"); 57 | var Proxy = require("./iot.control." + protocol); 58 | currentControl = Proxy.init(config, logger); 59 | } 60 | return currentControl; 61 | } 62 | catch(err) { 63 | logger.error("Proxy Connector does not exist: ", err); 64 | } 65 | }; 66 | -------------------------------------------------------------------------------- /lib/proxies/iot.control.mqtt.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var common = require('../common'), 27 | Broker = require("../../api/mqtt/connector"); 28 | 29 | 30 | 31 | function IoTKitMQTTControl(conf, logger, broker) { 32 | var me = this; 33 | me.logger = logger; 34 | me.client = broker; 35 | me.type = 'mqtt'; 36 | me.topics = conf.connector[me.type].topic; 37 | me.pubArgs = { 38 | qos: 0, 39 | retain: false 40 | }; 41 | me.logger.debug(me.type.toUpperCase(), 'Control Proxy Created'); 42 | } 43 | IoTKitMQTTControl.prototype.controlCommandListen = function (data, handlerCb, syncCall) { 44 | var me = this; 45 | var controlTopic = common.buildPath(me.topics.control_command, data.deviceId); 46 | var handler = function (topic, message) { 47 | me.logger.debug('controlCommandListen Topic %s , Message Recv : %s', topic, message); 48 | handlerCb(message); 49 | }; 50 | return me.client.bind(controlTopic, handler, syncCall); 51 | }; 52 | 53 | 54 | module.exports.init = function(conf, logger) { 55 | var brokerConnector = Broker.singleton(conf.connector.mqtt, logger); 56 | return new IoTKitMQTTControl(conf, logger, 57 | brokerConnector); 58 | }; 59 | -------------------------------------------------------------------------------- /lib/proxies/iot.control.rest.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var rest = require("../../api/rest"); 27 | 28 | function IoTKitRestControl(conf, logger, restCtrl) { 29 | var me = this; 30 | me.config = conf; 31 | me.logger = logger; 32 | me.type = 'rest'; 33 | me.client = restCtrl; 34 | me.logger.debug(me.type.toUpperCase() , ' Control Proxy Created'); 35 | } 36 | IoTKitRestControl.prototype.controlCommandListen = function (data, callback, syncCall) { 37 | if (syncCall) { 38 | syncCall(); 39 | } 40 | }; 41 | module.exports.init = function(conf, logger) { 42 | return new IoTKitRestControl(conf, logger, rest); 43 | }; 44 | -------------------------------------------------------------------------------- /lib/proxies/iot.control.ws.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | var Websocket = require("../../api/ws/connector"); 27 | 28 | 29 | function IoTKitWSControl(conf, logger, ws) { 30 | var me = this; 31 | me.logger = logger; 32 | me.client = ws; 33 | me.type = 'ws'; 34 | me.logger.debug(me.type.toUpperCase(), 'Control Proxy Created'); 35 | } 36 | 37 | IoTKitWSControl.prototype.controlCommandListen = function (data, handlerCb, syncCall) { 38 | var me = this; 39 | var handler = function (message) { 40 | me.logger.debug('Message Recv : %s', message); 41 | handlerCb(message); 42 | }; 43 | return me.client.bind(data.deviceId, handler, syncCall); 44 | }; 45 | 46 | 47 | module.exports.init = function(conf, logger) { 48 | var wsConnector = Websocket.singleton(conf, logger); 49 | return new IoTKitWSControl(conf, logger, wsConnector); 50 | }; 51 | -------------------------------------------------------------------------------- /lib/schema-validator/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 'use strict'; 26 | 27 | var schemaValidator = require('./schema-validator'); 28 | module.exports = schemaValidator; 29 | module.exports.schemas = require('./schemas'); -------------------------------------------------------------------------------- /lib/schema-validator/schema-validator.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 'use strict'; 26 | var validator = require('json-schema'); 27 | var logger = require("../logger").init(); 28 | /** 29 | * 30 | * @param obj 31 | * @param schema 32 | * @returns {Array} 33 | */ 34 | var validate = function(obj, schema){ 35 | return validator.validate(obj, schema).errors.map(function(e){ 36 | e.customMessage = e.property + ' ' + e.message; 37 | logger.debug("Scheme Error : ", e.customMessage); 38 | return e; 39 | }); 40 | }; 41 | 42 | var parseErrors = function(result, cb) { 43 | var msg = ''; 44 | if (result.length > 0) { 45 | for (var i = 0; i < result.length; i++) { 46 | //validate method from schema-validator returns error message in which on first place there is filed 47 | //identifier (n - for name; t - for type) 48 | msg += result[i].customMessage.replace(new RegExp(/^n/), 'name').replace(/^t/, 'type') + 49 | ((i + 1) < result.length ? ', ' : ''); 50 | } 51 | } 52 | cb(msg); 53 | }; 54 | 55 | /** 56 | * @description it will validate the json schema 57 | * @param schema 58 | * @returns {Function} 59 | */ 60 | var validateSchema = function(schema){ 61 | /** 62 | * @description it will validate the json schema 63 | * @param data 64 | * @return {bool} 65 | */ 66 | return function(data) { 67 | var errors = validate(data, schema); 68 | return (errors.length === 0); 69 | }; 70 | }; 71 | module.exports = { 72 | validate: validate, 73 | validateSchema: validateSchema, 74 | setLogger: function (log) { 75 | logger = log; 76 | }, 77 | parseErrors: parseErrors 78 | }; 79 | -------------------------------------------------------------------------------- /lib/schema-validator/schemas/component.json: -------------------------------------------------------------------------------- 1 | { 2 | "REG" : { 3 | "name": "component", 4 | "type": "object", 5 | "additionalProperties": false, 6 | "properties": { 7 | "n": { 8 | "type": "string", 9 | "required": true, 10 | "minLength": 4 11 | }, 12 | "t": { 13 | "type": "string", 14 | "required": true, 15 | "minLength": 4 16 | } 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /lib/schema-validator/schemas/data.json: -------------------------------------------------------------------------------- 1 | { 2 | "SUBMIT": { 3 | "name": "data", 4 | "type": "object", 5 | "additionalProperties": true, 6 | "properties": { 7 | "v": { 8 | "required": true 9 | }, 10 | "n": { 11 | "type": "string", 12 | "required": true, 13 | "minLength": 4 14 | }, 15 | "loc": { 16 | "type": "array", 17 | "minItems": 2, 18 | "maxItems": 3, 19 | "items": { 20 | "type": "number" 21 | }, 22 | "required": false 23 | }, 24 | "att" :{ 25 | "type": "object", 26 | "required": false 27 | }, 28 | "on": { 29 | "type": "number", 30 | "required": false 31 | } 32 | } 33 | } 34 | } -------------------------------------------------------------------------------- /lib/schema-validator/schemas/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 'use strict'; 26 | var component = require('./component.json'), 27 | routing = require('./routing.json'), 28 | data = require('./data.json'); 29 | 30 | module.exports = { 31 | component: component, 32 | data: data, 33 | routing: routing 34 | }; -------------------------------------------------------------------------------- /lib/schema-validator/schemas/routing.json: -------------------------------------------------------------------------------- 1 | { 2 | "ROUTE": { 3 | "name": "rinfo", 4 | "type": "object", 5 | "properties": { 6 | "n": { 7 | "type": "string", 8 | "required": true, 9 | "minLength": 4 10 | }, 11 | "r": { 12 | "type": "object", 13 | "required": false 14 | } 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /lib/sensors-store.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | "use strict"; 25 | require('es6-shim'); 26 | var common = require("./common"), 27 | uuid = require('node-uuid'); 28 | 29 | function Sensor (store, logT) { 30 | var me = this; 31 | me.logger = logT || []; 32 | me.filename = store || "device.json"; 33 | 34 | var deviceConfig = common.getDeviceConfig(); 35 | if(deviceConfig) { 36 | me.data = deviceConfig['sensor_list']; 37 | } 38 | else { 39 | me.data = []; 40 | } 41 | } 42 | /** 43 | * It return a component looking by component id 44 | * @param cid 45 | */ 46 | Sensor.prototype.byCid = function (cid) { 47 | 48 | return this.data.find(function (obj) { 49 | return (obj.cid === cid); 50 | }); 51 | }; 52 | Sensor.prototype.byName = function (name) { 53 | 54 | return this.data.find(function (obj) { 55 | return (obj.name === name); 56 | }); 57 | }; 58 | Sensor.prototype.byType = function (type) { 59 | return this.data.find(function (obj){ 60 | return (obj.type === type); 61 | }); 62 | }; 63 | Sensor.prototype.add = function (sensor) { 64 | var me = this; 65 | sensor.cid = sensor.cid || uuid.v4(); 66 | me.data.push(sensor); 67 | return sensor; 68 | }; 69 | Sensor.prototype.createId = function (sensor) { 70 | sensor.cid = uuid.v4(); 71 | return sensor; 72 | }; 73 | 74 | Sensor.prototype.del = function (cid) { 75 | var me = this; 76 | var index = me.data.findIndex(function (obj) { 77 | return (obj.cid === cid); 78 | }); 79 | if (index !== -1) { 80 | me.data.splice(index, 1); 81 | } 82 | }; 83 | Sensor.prototype.exist = function (obj) { 84 | 85 | return this.data.find(function (t) { 86 | return ((t.name === obj.name) && (t.type === obj.type)); 87 | }); 88 | }; 89 | Sensor.prototype.save = function(){ 90 | var me = this; 91 | common.saveToDeviceConfig("sensor_list", me.data); 92 | }; 93 | 94 | var init = function(store, loggerObj) { 95 | return new Sensor(store, loggerObj); 96 | }; 97 | module.exports.init = init; 98 | -------------------------------------------------------------------------------- /lib/server/udp.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var dgram = require("dgram"); 26 | 27 | function Server(udpServerPort, logger) { 28 | var me = this; 29 | me.logger = logger; 30 | me.server = dgram.createSocket("udp4"); 31 | 32 | me.server.on("error", function (err) { 33 | me.logger.error('UDP Error: ', err.stack); 34 | }); 35 | me.server.on('close', function(rinfo){ 36 | console.log('UDP Closing from ', rinfo); 37 | }); 38 | me.server.on("message", function (msg, rinfo) { 39 | me.logger.debug('UDP message from %s:%d', rinfo.address, rinfo.port); 40 | if(rinfo.address !== "127.0.0.1") { 41 | me.logger.debug('Ignoring external UDP message from %s', rinfo.address); 42 | return; 43 | } 44 | try { 45 | if (me.handleronMessage) { 46 | var data = JSON.parse(msg); 47 | data.r = rinfo; 48 | me.handleronMessage(data); 49 | } 50 | } catch (ex) { 51 | me.logger.error('UDP Error on message: %s', ex.message); 52 | me.logger.error(ex.stack); 53 | } 54 | }); 55 | me.server.on("listening", function () { 56 | var addr = me.server.address(); 57 | me.logger.info("UDP listener started on port: ", addr.port); 58 | }); 59 | me.server.bind(udpServerPort); 60 | } 61 | 62 | Server.prototype.listen = function (handler) { 63 | var me = this; 64 | me.handleronMessage = handler; 65 | }; 66 | Server.prototype.send = function (toClient, data) { 67 | var me = this; 68 | var msg = new Buffer(JSON.stringify(data)); 69 | me.server.send(msg, 0, msg.length, toClient.port, toClient.address, function(err, bytes){ 70 | me.logger.debug("Response Send", err , " bytes ", bytes); 71 | }); 72 | }; 73 | Server.prototype.close = function () { 74 | var me = this; 75 | me.server.close(); 76 | }; 77 | var server; 78 | module.exports.singleton = function (port, logger) { 79 | if (!server) { 80 | server = new Server(port, logger); 81 | } 82 | return server; 83 | }; 84 | 85 | 86 | -------------------------------------------------------------------------------- /lib/server/upd.table.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | function UdpTable (server, port) { 26 | this.server = server; 27 | this.port = port; 28 | this.data = {}; 29 | } 30 | 31 | UdpTable.prototype.add = function (id, record) { 32 | var me = this; 33 | me.data[id] = record; 34 | }; 35 | UdpTable.prototype.del = function (id) { 36 | var me = this; 37 | delete me.data[id]; 38 | }; 39 | 40 | UdpTable.prototype.getRinfo = function (id) { 41 | var me = this; 42 | return me.data[id]; 43 | }; 44 | var table = null; 45 | 46 | module.exports.singleton = function (server, port) { 47 | if (table === null) { 48 | table = new UdpTable(server, port); 49 | } 50 | return table; 51 | }; 52 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | "use strict"; 25 | var mac = require("getmac"), 26 | os = require("os"), 27 | http = require("http"), 28 | admin = require('../api/rest').admin, 29 | pkgJson = require('../package.json'), 30 | config = require ('../config'), 31 | common = require('../lib/common'); 32 | 33 | function IoTKitUtils(cfg){ 34 | var me = this; 35 | common.initializeDataDirectory(); 36 | me.deviceConf = common.getDeviceConfig(); 37 | me.config = cfg; 38 | me.did = me.deviceConf.device_id; 39 | } 40 | IoTKitUtils.prototype.getLocation = function () { 41 | //TODO Need to implement location gather info 42 | if (this.deviceConf.device_loc) { 43 | return this.deviceConf.device_loc; 44 | } 45 | return null; 46 | }; 47 | IoTKitUtils.prototype.getAgentAttr = function () { 48 | return { 49 | "agent_version": pkgJson.version, 50 | "hardware_vendor": os.cpus()[0].model, 51 | "hardware_model": os.platform(), 52 | "Model Name": os.arch(), 53 | "Firmware Version": os.release() 54 | }; 55 | }; 56 | IoTKitUtils.prototype.externalInfo = function(cb) { 57 | var me = this; 58 | if (!cb) { 59 | throw "Callback required"; 60 | } 61 | admin.getExternalInfo(function (err, data){ 62 | if (!err) { 63 | data.ip_local = me.getIPs()[0]; 64 | cb(data); 65 | } else { 66 | cb(null); 67 | } 68 | }); 69 | }; 70 | IoTKitUtils.prototype.getExternalInfo = function(cb) { 71 | var me = this; 72 | if (!cb) { 73 | throw "Callback required"; 74 | } 75 | 76 | var options = { 77 | host: 'ipinfo.io', 78 | port: 80, 79 | method: 'GET' 80 | }; 81 | http.request(options, function(res) { 82 | if (res.statusCode === 200) { 83 | res.setEncoding('utf8'); 84 | res.on('data', function (chunk) { 85 | var data = JSON.parse(chunk); 86 | data.ip_local = me.getIPs()[0]; 87 | cb(data); 88 | }); 89 | } else { 90 | cb(null); 91 | } 92 | }).end(); 93 | }; 94 | IoTKitUtils.prototype.getDeviceId = function(cb) { 95 | var me = this; 96 | if (!cb) { 97 | throw "Callback required"; 98 | } 99 | // if use explicit Id if one was defined in the configuration file 100 | // account for the different ways people could spell it ;) 101 | if (me.did) { 102 | cb(me.did); 103 | return; 104 | } 105 | 106 | mac.getMac(function(err, macAddress){ 107 | var result = null; 108 | if (err) { 109 | //Unable to get MAC address 110 | result = os.hostname().toLowerCase(); 111 | } else { 112 | result = macAddress.replace(/:/g, '-'); 113 | } 114 | me.did = result; 115 | cb(result); 116 | }); 117 | }; 118 | IoTKitUtils.prototype.getIPs = function() { 119 | var addresses = []; 120 | var interfaces = os.networkInterfaces(); 121 | for (var k in interfaces) { 122 | if (interfaces.hasOwnProperty(k)) { 123 | for (var k2 in interfaces[k]) { 124 | if (interfaces[k].hasOwnProperty(k2)) { 125 | var address = interfaces[k][k2]; 126 | if (address.family === 'IPv4' && !address.internal) { 127 | addresses.push(address.address); 128 | } 129 | } 130 | } 131 | } 132 | } 133 | 134 | return addresses; 135 | 136 | }; 137 | 138 | IoTKitUtils.prototype.getGatewayId = function(key, cb) { 139 | var me = this; 140 | if (!cb) { 141 | throw "Callback required"; 142 | } 143 | 144 | if (me.config[key]) { 145 | cb(me.config[key]); 146 | } else { 147 | (me.getDeviceId(cb)); 148 | } 149 | }; 150 | 151 | IoTKitUtils.prototype.getDataDirectory = function(key, cb) { 152 | var me = this; 153 | if (!cb) { 154 | throw "Callback required"; 155 | } 156 | 157 | if (me.config[key]) { 158 | cb(me.config[key]); 159 | } else { 160 | throw "Config for data directory not found"; 161 | } 162 | }; 163 | 164 | IoTKitUtils.prototype.getValueFromDeviceConfig = function(key) { 165 | var me = this; 166 | return me.deviceConf[key]; 167 | }; 168 | 169 | IoTKitUtils.prototype.getMinutesAndSecondsFromMiliseconds = function(miliseconds) { 170 | var minutes = Math.floor(miliseconds / 60000), 171 | seconds = ((miliseconds % 60000) / 1000).toFixed(0); 172 | return {m: minutes, s: seconds}; 173 | }; 174 | 175 | exports.init = function() { 176 | var utils = new IoTKitUtils(config); 177 | return utils; 178 | }; 179 | -------------------------------------------------------------------------------- /listeners/index.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | "use strict"; 26 | 27 | module.exports = { 28 | MQTT: require('./mqtt'), 29 | REST: require('./rest'), 30 | TCP: require('./tcp') 31 | }; -------------------------------------------------------------------------------- /listeners/mqtt.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var mqtt = require('mqtt'), 26 | fs = require('fs'), 27 | common = require('../lib/common'), 28 | path = require("path"); 29 | 30 | /** 31 | * @description Build a path replacing patter {} by the data arguments 32 | * if more the one {} pattern is present it shall be use Array 33 | * @param path string the represent a URL path 34 | * @param data Array or string, 35 | * @returns {*} 36 | */ 37 | var buildPath = function (path, data) { 38 | var re = /{\w+}/; 39 | var pathReplace = path; 40 | if (Array.isArray(data)) { 41 | data.forEach(function (value) { 42 | pathReplace = pathReplace.replace(re, value); 43 | }); 44 | } else { 45 | pathReplace = pathReplace.replace(re, data); 46 | } 47 | return pathReplace; 48 | }; 49 | 50 | exports.init = function(conf, logger, onMessage, deviceId) { 51 | 52 | var mqttServerPort = conf.listeners.mqtt_port || 1883; 53 | 54 | var filename = conf.token_file || "token.json"; 55 | var fullFilename = path.join(__dirname, '../data/' + filename); 56 | var secret = { }; 57 | if (fs.existsSync(fullFilename)) { 58 | secret = common.readFileToJson(fullFilename); 59 | } else { 60 | //consider from system folder /usr/share/iotkit-agent/certs 61 | fullFilename = '/usr/share/iotkit-agent/data/' + filename; 62 | secret = common.readFileToJson(fullFilename); 63 | } 64 | 65 | var metric_topic = conf.connector.mqtt.topic.metric_topic || "server/metric/{accountid}/{deviceid}"; 66 | 67 | var tlsArgs = { }; 68 | var verifyCertKeyPath = conf.connector.mqtt.key || './certs/client.key'; 69 | if (fs.existsSync(verifyCertKeyPath)) { 70 | tlsArgs = { 71 | keyPath: conf.connector.mqtt.key || './certs/client.key', 72 | certPath: conf.connector.mqtt.crt || './certs/client.crt', 73 | keepalive: 59000 74 | }; 75 | } else { 76 | // load from /usr/share 77 | tlsArgs = { 78 | keyPath: '/usr/share/iotkit-agent/certs/enableiot_agent.key', 79 | certPath: '/usr/share/iotkit-agent/certs/enableiot_agent.crt', 80 | keepalive: 59000 81 | }; 82 | } 83 | 84 | var mqttServer = mqtt.createServer(function(client) { 85 | 86 | client.on('connect', function(packet) { 87 | client.connack({returnCode: 0}); 88 | client.id = packet.clientId; 89 | logger.debug('MQTT Client connected: ', packet.clientId); 90 | }); 91 | 92 | client.on('publish', function(packet) { 93 | logger.debug('MQTT Topic: %s Payload: %s', packet.topic, packet.payload); 94 | try { 95 | onMessage(JSON.parse(packet.payload)); 96 | } catch (ex) { 97 | logger.error('MQTT Error on message: %s', ex); 98 | } 99 | }); 100 | 101 | client.on('subscribe', function(packet) { 102 | try { 103 | // create a new client object to the new online broker 104 | // subscribe 105 | 106 | var newclient; 107 | var topic = packet.subscriptions[0].topic; 108 | 109 | if(conf.connector.mqtt.secure){ 110 | newclient = mqtt.createSecureClient(conf.connector.mqtt.port, conf.connector.mqtt.host, tlsArgs); 111 | } else { 112 | newclient = mqtt.createClient(conf.connector.mqtt.port, conf.connector.mqtt.host); 113 | } 114 | 115 | if(topic === 'data'){ 116 | newclient.subscribe(buildPath(metric_topic, [secret.accountId, deviceId])); 117 | logger.info('Subscribed to topic:' + buildPath(metric_topic, [secret.accountId, deviceId])); 118 | } else { 119 | newclient.subscribe(buildPath(metric_topic, [secret.accountId, deviceId]) + '/' + topic); 120 | logger.info('Subscribing to topic:' + buildPath(metric_topic, [secret.accountId, deviceId]) + '/' + topic); 121 | } 122 | 123 | newclient.on('message', function (topic, message) { 124 | logger.info('Received a message on subscribed topic: ' + topic); 125 | client.publish({"topic": topic, "payload": message}); 126 | }); 127 | } catch (ex) { 128 | logger.error('Error on message: %s', ex.message); 129 | logger.error(ex.stack); 130 | } 131 | }); 132 | 133 | client.on('pingreq', function() { 134 | client.pingresp(); 135 | }); 136 | 137 | client.on('disconnect', function() { 138 | client.stream.end(); 139 | }); 140 | 141 | client.on('error', function(err) { 142 | //client.stream.end(); 143 | logger.error('MQTT Error: ', err); 144 | }); 145 | 146 | }).listen(mqttServerPort); 147 | 148 | logger.info("MQTT listener started on port: ", mqttServerPort); 149 | 150 | return mqttServer; 151 | 152 | }; 153 | 154 | 155 | -------------------------------------------------------------------------------- /listeners/rest.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var express = require("express"); 26 | 27 | exports.init = function(conf, logger, onMessage) { 28 | 29 | var httpServerPort = conf.listeners.rest_port || 9090; 30 | var rest = express(); 31 | rest.configure(function() { 32 | rest.use(express.favicon()); 33 | rest.use(express.json()); 34 | rest.use(express.urlencoded()); 35 | rest.use(express.methodOverride()); 36 | rest.use(express.errorHandler()); 37 | }); 38 | 39 | rest.put('/', function (request, response) { 40 | var msg = request.body; 41 | logger.debug('REST Payload: ', msg); 42 | try { 43 | onMessage(msg); 44 | response.send(201); 45 | } catch (ex) { 46 | logger.error('REST Error: ', ex.message); 47 | logger.error(ex.stack); 48 | response.send(500); 49 | } 50 | }); 51 | 52 | rest.listen(httpServerPort); 53 | 54 | logger.info("REST listener started on port: ", httpServerPort); 55 | return rest; 56 | }; 57 | 58 | -------------------------------------------------------------------------------- /listeners/tcp.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var net = require('net'), 26 | JsonSocket = require('json-socket'); 27 | 28 | exports.init = function(conf, logger, onMessage) { 29 | 30 | var tcpServerPort = conf.tcp_port || 7070; 31 | var tcpServerHost = "127.0.0.1"; 32 | 33 | function processMessage(data) { 34 | try { 35 | logger.debug("Message to process:" + JSON.stringify(data)); 36 | onMessage(data); 37 | } catch (ex) { 38 | logger.error('TCP Error on message: %s', ex.message); 39 | logger.error(ex.stack); 40 | } 41 | } 42 | 43 | var server = net.createServer(); 44 | server.listen(tcpServerPort, tcpServerHost); 45 | 46 | server.on('connection', function(socket) { 47 | logger.debug('TCP connection from %s:%d', socket.remoteAddress, socket.remotePort); 48 | if(socket.remoteAddress !== "127.0.0.1") { 49 | logger.debug("Ignoring remote message from", socket.remoteAddress); 50 | return; 51 | } 52 | 53 | socket = new JsonSocket(socket); 54 | socket.on('message', function(message) { 55 | logger.debug("Data arrived: " + JSON.stringify(message)); 56 | processMessage(message); 57 | }); 58 | }); 59 | 60 | logger.info("TCP listener started on port: ", tcpServerPort); 61 | 62 | return server; 63 | 64 | }; -------------------------------------------------------------------------------- /migrate.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* 4 | Copyright (c) 2014, Intel Corporation 5 | 6 | Redistribution and use in source and binary forms, with or without modification, 7 | are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, 10 | this list of conditions and the following disclaimer. 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 16 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 17 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 18 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 19 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 20 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 21 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 22 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 24 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | */ 26 | "use strict"; 27 | var fs = require ('fs'); 28 | 29 | var backupDir = process.argv[2]; 30 | 31 | var oldConfigFile = backupDir + '/config.json'; 32 | var oldSensorFile = backupDir + '/sensor-list.json'; 33 | var oldTokenFile = backupDir + '/token.json'; 34 | 35 | var dataDir = './data'; 36 | 37 | // Import old values 38 | var oldconfig = require(oldConfigFile); 39 | var oldsensors = require(oldSensorFile); 40 | var oldtoken = require(oldTokenFile); 41 | 42 | // Locate and find new config 43 | var globalConfigFile = './config/global.json'; 44 | var global = require(globalConfigFile); 45 | 46 | var configFile = dataDir + '/device.json' 47 | if (global['data_directory']) { 48 | configFile = global['data_directory'] + '/device.json'; 49 | } 50 | var config = require(configFile); 51 | 52 | // Migrate config settings 53 | var configKeys = ['device_id', 'gateway_id', 'device_name', 'device_loc']; 54 | function setValue(key, newconfig, oldconfig) { 55 | if (oldconfig[configKeys[key]]) { 56 | newconfig[configKeys[key]] = oldconfig[configKeys[key]]; 57 | } 58 | console.log(configKeys[key] + ": " + oldconfig[configKeys[key]]); 59 | } 60 | 61 | for (var key in configKeys) { 62 | setValue(key, config, oldconfig); 63 | } 64 | 65 | // Migrate sensor list 66 | config['sensor_list'] = oldsensors; 67 | console.log("Sensor list: " + oldsensors); 68 | // migrate token 69 | config['device_token'] = oldtoken['deviceToken']; 70 | console.log("Token: " + oldtoken['deviceToken']); 71 | config['account_id'] = oldtoken['accountId']; 72 | console.log("Account Id: " + oldtoken['accountId']); 73 | 74 | // Save new config 75 | fs.writeFile(configFile, JSON.stringify(config, null, 4), function(err) { 76 | if(err) { 77 | console.log(err); 78 | } else { 79 | console.log("JSON saved to " + configFile); 80 | } 81 | }); 82 | 83 | 84 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "iotkit-agent", 3 | "version": "1.8.3", 4 | "description": "Edge agent to abstract complexities", 5 | "main": "server.js", 6 | "dependencies": { 7 | "express": "^3.5.2", 8 | "getmac": "^1.0.6", 9 | "json-schema": "^0.2.2", 10 | "mqtt": "^0.3.8", 11 | "node-uuid": "^1.4.1", 12 | "request": "^2.36.0", 13 | "async": "^0.9.0", 14 | "winston": "^0.7.3", 15 | "cli-table": "^0.3.0", 16 | "json-socket": "^0.1.2", 17 | "websocket": "^1.0.18", 18 | "tunnel": "0.0.3", 19 | "es6-shim": "0.34.0" 20 | }, 21 | "bin": { 22 | "iotkit-admin": "./iotkit-admin.js", 23 | "iotkit-agent": "./iotkit-agent.js" 24 | }, 25 | "scripts": { 26 | "start": "node agent", 27 | "test": "mocha" 28 | }, 29 | "repository": { 30 | "type": "git", 31 | "url": "git://github.com/enableiot/iotkit-agent.git" 32 | }, 33 | "keywords": [ 34 | "iotkit", 35 | "agent" 36 | ], 37 | "author": "Intel, CPG", 38 | "license": "BSD-2-Clause", 39 | "bugs": { 40 | "url": "https://github.com/enableiot/iotkit-agent/issues" 41 | }, 42 | "homepage": "https://github.com/enableiot/iotkit-agent", 43 | "devDependencies": { 44 | "grunt": "^0.4.4", 45 | "mocha": "^1.18.2", 46 | "istanbul": "^0.2.7", 47 | "rewire": "^2.0.0", 48 | "grunt-cli": "^0.1.13", 49 | "grunt-contrib-jshint": "^0.10.0", 50 | "mocha-teamcity-reporter": "0.0.2", 51 | "jshint-teamcity": "^1.0.4", 52 | "asserts": "^4.0.0", 53 | "chai": "^1.9.1", 54 | "grunt-contrib-compress": "^0.8.0", 55 | "grunt-mocha-istanbul": "^1.4.0", 56 | "grunt-istanbul": "^0.2.5", 57 | "grunt-license-finder": "^0.1.3" 58 | }, 59 | "directories": { 60 | "doc": "doc", 61 | "test": "test" 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /send_udp.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | Copyright (c) 2014, Intel Corporation 4 | 5 | Redistribution and use in source and binary forms, with or without modification, 6 | are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, 9 | this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 15 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 16 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 17 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 18 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 19 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 20 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 21 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 22 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 23 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 24 | */ 25 | 26 | "use strict"; 27 | var endpoint = "127.0.0.1" 28 | var port = 41234 29 | 30 | // Check for valid parameters 31 | if (process.argv.length != 4) { 32 | console.log("Usage: " + process.argv[0] + " " + process.argv[1] + " component_name value"); 33 | process.exit(1); 34 | } 35 | 36 | // Format JSON message containing name/value pair 37 | var component = process.argv[2]; 38 | var value = process.argv[3]; 39 | var data = "{\"n\": \"" + component + "\", \"v\": \"" + value + "\"}"; 40 | 41 | //console.log(data); 42 | // Send UDP message to local agent 43 | var dgram = require('dgram'); 44 | var message = new Buffer(data); 45 | var client = dgram.createSocket("udp4"); 46 | client.send(message, 0, message.length, port, endpoint, function(err, bytes) { 47 | client.close(); 48 | process.exit(0); 49 | }); -------------------------------------------------------------------------------- /set-time.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | TM=$(curl -s http://www.timeapi.org/utc/now?format=%25Y-%25m-%25d%20%25H:%25M) 26 | echo $TM 27 | date --set="${TM}" -------------------------------------------------------------------------------- /sonar-project.properties: -------------------------------------------------------------------------------- 1 | ############################################################################ 2 | # INTEL CONFIDENTIAL # 3 | # Copyright (c), 2014 Intel Corporation. All Rights Reserved. # 4 | # # 5 | # The source code contained or described herein and all documents # 6 | # related to the source code ("Material") are owned by Intel Corporation # 7 | # or its suppliers or licensors. Title to the Material remains with # 8 | # Intel Corporation or its suppliers and licensors. The Material # 9 | # contains trade secrets and proprietary and confidential information of # 10 | # Intel or its suppliers and licensors. The Material is protected by # 11 | # worldwide copyright and trade secret laws and treaty provisions. No # 12 | # part of the Material may be used, copied, reproduced, modified, # 13 | # published, uploaded, posted, transmitted, distributed, or disclosed in # 14 | # any way without Intel's prior express written permission. # 15 | # # 16 | # No license under any patent, copyright, trade secret or other # 17 | # intellectual property right is granted to or conferred upon you by # 18 | # disclosure or delivery of the Materials, either expressly, by # 19 | # implication, inducement, estoppel or otherwise. Any license under such # 20 | # intellectual property rights must be express and approved by Intel in # 21 | # writing. # 22 | ############################################################################ 23 | 24 | # must be unique in a given SonarQube instance 25 | sonar.projectKey=dp1:iotkit-agent 26 | # this is the name displayed in the SonarQube UI 27 | sonar.projectName=iotkit-agent 28 | sonar.projectVersion=1.0 29 | 30 | # Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows. 31 | # Since SonarQube 4.2, this property is optional if sonar.modules is set. 32 | # If not set, SonarQube starts looking for source code from the directory containing 33 | # the sonar-project.properties file. 34 | sonar.sources=. 35 | sonar.language=js 36 | 37 | # Encoding of the source code. Default is default system encoding 38 | #sonar.sourceEncoding=UTF-8 39 | 40 | sonar.exclusions=lib/commander/** 41 | 42 | -------------------------------------------------------------------------------- /start-agent.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | 26 | echo "" 27 | echo "============================================" 28 | echo "IoT Kit Agent" 29 | echo "============================================" 30 | 31 | # reset logs directory 32 | if [ -f agent.log ] || [ -f forever.log ]; then 33 | rm *.log 34 | fi 35 | 36 | export BASE_DIR="${PWD}" 37 | FOREVER=${BASE_DIR}/node_modules/.bin/forever 38 | 39 | ${FOREVER} start -m 1 \ 40 | -a -l "${BASE_DIR}/forever.log" \ 41 | --sourceDir $BASE_DIR \ 42 | --minUptime 1s \ 43 | --spinSleepTime 3s iotkit-agent.js 44 | 45 | 46 | echo "" 47 | echo "Device Id:" 48 | ./iotkit-admin.js device-id 49 | echo "" 50 | echo "============================================" 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /stop-agent.sh: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2014, Intel Corporation 2 | # 3 | # Redistribution and use in source and binary forms, with or without modification, 4 | # are permitted provided that the following conditions are met: 5 | # 6 | # * Redistributions of source code must retain the above copyright notice, 7 | # this list of conditions and the following disclaimer. 8 | # * Redistributions in binary form must reproduce the above copyright notice, 9 | # this list of conditions and the following disclaimer in the documentation 10 | # and/or other materials provided with the distribution. 11 | # 12 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 13 | # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 14 | # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 15 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 16 | # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 17 | # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 18 | # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 19 | # ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 20 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 21 | # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 22 | 23 | #!/bin/bash 24 | 25 | export BASE_DIR="${PWD}" 26 | FOREVER=${BASE_DIR}/node_modules/forever/bin/forever 27 | 28 | ${FOREVER} stop iotkit-agent.js 29 | -------------------------------------------------------------------------------- /test/api_iot.devicesTests.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var assert = require('chai').assert, 26 | rewire = require('rewire'); 27 | 28 | var fileToTest = "../api/rest/iot.devices.js"; 29 | 30 | describe(fileToTest, function(){ 31 | var toTest = rewire(fileToTest); 32 | var logger = { 33 | info : function() {}, 34 | error : function() {}, 35 | debug : function() {} 36 | }; 37 | console.debug = function() { 38 | console.log(arguments); 39 | }; 40 | 41 | var Option = { 42 | DeviceActivateOption:{}, 43 | DeviceMetadataOption: {}, 44 | DeviceComponentOption: {} 45 | }; 46 | var httpClientMock = { 47 | httpRequest : {}, 48 | httpClient: {} 49 | }; 50 | var responseData = { 51 | statusCode : 200, 52 | data : "" 53 | }; 54 | 55 | it('Shall Register and Control the Response from device Registration >', function(done) { 56 | 57 | var optData = { 58 | method: 'PUT', 59 | host: "myhost", 60 | body: "mybody" 61 | }; 62 | 63 | var data = {deviceid : "did", 64 | body: { data: "message" } 65 | }; 66 | var reData = { 67 | x : 10, 68 | y : 220, 69 | ar : ["222", "223"] 70 | }; 71 | 72 | Option.DeviceActivateOption = function (device) { 73 | assert.deepEqual(device, data, "The Data is not oki"); 74 | return optData; 75 | }; 76 | httpClientMock.httpRequest = function (opt, cb) { 77 | assert.deepEqual(opt, optData, "the option object were missed"); 78 | cb(reData); 79 | } 80 | var callBack = function (response) { 81 | assert.isNotNull(response, "The Response were missing"); 82 | assert.deepEqual(response, reData, "The Data were missing"); 83 | done(); 84 | }; 85 | toTest.__set__("httpClient", httpClientMock); 86 | toTest.__set__("DeviceDef", Option); 87 | toTest.registerDevice(data, callBack); 88 | }); 89 | it('Shall Sent Update Data To Server >', function(done){ 90 | var optData = { 91 | method: 'PUT', 92 | host: "myhost", 93 | body: "mybody" 94 | }; 95 | 96 | var data = {deviceid : "did", 97 | body: { data: "message" } 98 | }; 99 | var reData = { 100 | x : 10, 101 | y : 220, 102 | ar : ["222", "223"] 103 | }; 104 | 105 | Option.DeviceMetadataOption = function (device) { 106 | assert.deepEqual(device, data, "The Data is not oki"); 107 | return optData; 108 | }; 109 | httpClientMock.httpRequest = function (opt, cb) { 110 | assert.deepEqual(opt, optData, "the option object were missed"); 111 | cb(reData); 112 | }; 113 | 114 | var callBack = function (response) { 115 | assert.isNotNull(response, "The Response were missing"); 116 | assert.deepEqual(response, reData, "The Data were missing"); 117 | done(); 118 | }; 119 | toTest.__set__("httpClient", httpClientMock); 120 | toTest.__set__("DeviceDef", Option); 121 | toTest.updateMetadataDevice(data, callBack); 122 | 123 | }); 124 | it('Shall Sent Component Registration To Server >', function(done){ 125 | var optData = { 126 | method: 'POST', 127 | host: "myhost", 128 | body: "mybody" 129 | }; 130 | 131 | var data = {deviceId : "did", 132 | body: { data: "message" } 133 | }; 134 | var reData = { 135 | x : 10, 136 | y : 220, 137 | ar : ["222", "223"] 138 | }; 139 | 140 | Option.DeviceComponentOption = function (device) { 141 | assert.deepEqual(device, data, "The Data is not the expected"); 142 | return optData; 143 | }; 144 | httpClientMock.httpRequest = function (opt, cb) { 145 | assert.deepEqual(opt, optData, "the option object were missed"); 146 | cb(null, reData); 147 | }; 148 | 149 | var callBack = function (error, response) { 150 | assert.isUndefined(error, "An expected Error is detected"); 151 | assert.isArray(response, "The Response were missing"); 152 | assert.deepEqual(response[0], reData, "The Data were missing"); 153 | done(); 154 | }; 155 | toTest.__set__("httpClient", httpClientMock); 156 | toTest.__set__("DeviceDef", Option); 157 | var dataClone = JSON.parse(JSON.stringify(data)); 158 | toTest.registerComponents(dataClone, callBack); 159 | 160 | }); 161 | it('Shall Return an Error in a fail Registration To Server >', function(done){ 162 | var optData = { 163 | method: 'POST', 164 | host: "myhost", 165 | body: "mybody" 166 | }; 167 | 168 | var data = {deviceId : "did", 169 | body: { data: "message" } 170 | }; 171 | var reData = { 172 | x : 10, 173 | y : 220, 174 | ar : ["222", "223"] 175 | }; 176 | 177 | Option.DeviceComponentOption = function (device) { 178 | assert.deepEqual(device, data, "The Data is not the expected"); 179 | return optData; 180 | }; 181 | httpClientMock.httpRequest = function (opt, cb) { 182 | assert.deepEqual(opt, optData, "the option object were missed"); 183 | var er = new Error("Invalid Component"); 184 | cb(er); 185 | }; 186 | 187 | var callBack = function (error, response) { 188 | assert.isObject(error, "An expected Error is detected"); 189 | assert.isArray(response, "The Response were missing"); 190 | done(); 191 | }; 192 | toTest.__set__("httpClient", httpClientMock); 193 | toTest.__set__("DeviceDef", Option); 194 | var dataClone = JSON.parse(JSON.stringify(data)); 195 | toTest.registerComponents(dataClone, callBack); 196 | 197 | }); 198 | }); 199 | -------------------------------------------------------------------------------- /test/lib_agentTests.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | 26 | process.env.NODE_ENV = 'test'; 27 | var assert = require('assert'), 28 | utils = require("../lib/utils").init(), 29 | logger = require("../lib/logger").init(utils), 30 | schemaValidation = require('../lib/schema-validator'), 31 | configurator = require('../admin/configurator');; 32 | 33 | describe('iotkit-agent', function() { 34 | it('should generate a valid device Id', function(done) { 35 | utils.getDeviceId(function(id){ 36 | assert(id, 'id is null'); 37 | this.deviceId = id; 38 | console.log(id); 39 | done(); 40 | }); 41 | }); 42 | 43 | }); 44 | 45 | describe('iotkit-agent', function() { 46 | it('should generate a valid gatewayId', function(done) { 47 | configurator.getGatewayId(function(id){ 48 | assert(id, 'id is null'); 49 | assert.notEqual(id, ''); 50 | this.gatewayId = id; 51 | done(); 52 | }); 53 | }); 54 | }); 55 | 56 | describe('iotkit-agent', function() { 57 | it('should set a correct gatewayId', function(done) { 58 | configurator.getGatewayId(function(id) { 59 | assert(id, 'id is null'); 60 | this.gatewayId = id; 61 | }); 62 | 63 | configurator.setGatewayId('test', function(id){ 64 | assert(id, 'id is null'); 65 | assert.equal(id, 'test'); 66 | //Revert changes made by previous setGateway 67 | configurator.setGatewayId(this.gatewayId, function(id){ 68 | assert.equal(id, this.gatewayId); 69 | }); 70 | done(); 71 | }); 72 | }); 73 | }); 74 | 75 | describe('iotkit-agent', function() { 76 | it('should format a valid error message from errors array', function(done) { 77 | var errors = [ 78 | { 79 | customMessage: 'n must be at least 4 characters long' 80 | }, 81 | { 82 | customMessage: 't is missing' 83 | } 84 | 85 | ]; 86 | schemaValidation.parseErrors(errors, function(msg){ 87 | assert(msg, 'msg is null'); 88 | assert.equal(msg, 'name must be at least 4 characters long, type is missing'); 89 | done(); 90 | }); 91 | }); 92 | it('should return empty error message from empty array', function(done) { 93 | var errors = []; 94 | schemaValidation.parseErrors(errors, function(msg){ 95 | //assert(msg, 'msg is null'); 96 | assert.equal(msg, ''); 97 | done(); 98 | }); 99 | }); 100 | }); 101 | 102 | 103 | -------------------------------------------------------------------------------- /test/lib_comp.registrationTests.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var assert = require('chai').assert, 26 | rewire = require('rewire'); 27 | var fileToTest = "../lib/comp.registration.js"; 28 | 29 | describe(fileToTest, function(){ 30 | var toTest = rewire(fileToTest); 31 | var logger = { 32 | info : function() {}, 33 | error : function() {}, 34 | debug : function() {} 35 | }; 36 | console.debug = function() { 37 | console.log(arguments); 38 | }; 39 | var connector = {}; 40 | var store = { 41 | 42 | }; 43 | it('Shall Return False if not a Registration Message >', function(done) { 44 | var wrongMessage = { 45 | x: "Sensor Name", 46 | t: "SensorType.v1" 47 | } 48 | store.exist = function (data) { 49 | assert.isFalse(true, "The message shall not be going through"); 50 | return true; 51 | }; 52 | var handler = toTest.init(connector, store, logger); 53 | handler.registration(wrongMessage, function(process){ 54 | assert.isFalse(process, "Message Shall be not processed invalid n key"); 55 | wrongMessage = { 56 | n: "Sensor Name", 57 | tw: "SensorType.v1" 58 | }; 59 | handler.registration(wrongMessage, function(process){ 60 | assert.isFalse(process, "Message Shall be not processed Msg - invalid t key"); 61 | wrongMessage = { 62 | n: 1, 63 | t: "SensorType.v1" 64 | }; 65 | handler.registration(wrongMessage, function(process){ 66 | assert.isFalse(process, "Message Shall be not processed Msg - invalid n Value"); 67 | wrongMessage = { 68 | n: "", 69 | t: "SensorType.v1" 70 | }; 71 | handler.registration(wrongMessage, function(process){ 72 | assert.isFalse(process, "Message Shall be not processed Msg - invalid n Value"); 73 | done(); 74 | }); 75 | }); 76 | }); 77 | }); 78 | }); 79 | it('Shall Return True if it a valid Registration Message if the Component already exist>', function(done) { 80 | var okMessage = { 81 | n: "Sensor Name", 82 | t: "SensorType.v1" 83 | }; 84 | var store = { 85 | exist: function (data) { 86 | assert.isObject(data, "Shall be and Registration Object Representation"); 87 | assert.property(data, "name", "The object is invalid"); 88 | assert.property(data, "type", "The object is invalid"); 89 | assert.equal(data.name, okMessage.n, "Invalid Conversion of Name Property "); 90 | assert.equal(data.type, okMessage.t, "Invalid Conversion of Type Property "); 91 | return true; 92 | } 93 | }; 94 | var handler = toTest.init(connector, store, logger); 95 | handler.registration(okMessage, function(process){ 96 | assert.isTrue(process, "Message Shall be processed Msg "); 97 | okMessage.n = "n123"; 98 | handler.registration(okMessage, function(process){ 99 | assert.isTrue(process, "Message Shall be processed Msg "); 100 | okMessage.t = "t123"; 101 | handler.registration(okMessage, function(process){ 102 | assert.isTrue(process, "Message Shall be processed Msg "); 103 | done(); 104 | }); 105 | 106 | }); 107 | 108 | }); 109 | 110 | }); 111 | it('Shall Add Sensor to Store if the component does not exist >', function(done) { 112 | var okMessage = { 113 | n: "Sensor Name", 114 | t: "SensorType.v1" 115 | }; 116 | var myCID = "my-token"; 117 | store = { 118 | exist: function (data) { 119 | assert.isObject(data, "Shall be and Registration Object Representation"); 120 | assert.property(data, "name", "The object is invalid"); 121 | assert.property(data, "type", "The object is invalid"); 122 | assert.equal(data.name, okMessage.n, "Invalid Conversion of Name Property "); 123 | assert.equal(data.type, okMessage.t, "Invalid Conversion of Type Property "); 124 | return null; 125 | }, 126 | add: function (data) { 127 | assert.isObject(data, "Shall be and Registration Object Representation"); 128 | assert.property(data, "name", "The object is missing Name"); 129 | assert.property(data, "type", "The object is missing Type"); 130 | assert.equal(data.name, okMessage.n, "Invalid Conversion of Name Property "); 131 | assert.equal(data.type, okMessage.t, "Invalid Conversion of Type Property "); 132 | data.cid = data.cid || myCID; 133 | return data; 134 | }, 135 | createId: function (data) { 136 | data.cid = myCID; 137 | return data; 138 | }, 139 | save: function (data) { 140 | assert.isUndefined(data, "Data shall no be passed"); 141 | return true; 142 | } 143 | }; 144 | connector.regComponent = function (sensor, callback) { 145 | assert.isObject(sensor, "The Sensor shall be register"); 146 | var x = [sensor]; 147 | x.status = 0; 148 | callback(x); 149 | }; 150 | 151 | var handler = toTest.init(connector, store, logger); 152 | handler.registration(okMessage, function(process){ 153 | assert.equal(process.status, 0, "Message Shall be processed Msg "); 154 | done(); 155 | }); 156 | 157 | }); 158 | }); 159 | -------------------------------------------------------------------------------- /test/lib_data.submissionTests.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var assert = require('chai').assert, 26 | rewire = require('rewire'); 27 | var fileToTest = "../lib/data.submission.js"; 28 | 29 | describe(fileToTest, function(){ 30 | var toTest = rewire(fileToTest); 31 | var logger = { 32 | info : function() {}, 33 | error : function() {}, 34 | debug : function() {} 35 | }; 36 | console.debug = function() { 37 | console.log(arguments); 38 | }; 39 | var connector = {}; 40 | var store = { 41 | 42 | }; 43 | it('Shall Return False if not a Registration Message >', function(done) { 44 | var wrongMessage = { 45 | x: "Sensor Name", 46 | v: "31" 47 | } 48 | store.exist = function (data) { 49 | assert.isFalse(true, "The message shall not be going through"); 50 | return true; 51 | }; 52 | var handler = toTest.init(connector, store, logger); 53 | var process = handler.submission(wrongMessage, function (process){ 54 | assert.isFalse(process, "Message Shall be not processed invalid n key") 55 | // assert.isFalse(process, "Message Shall be not processed invalid n key"); 56 | wrongMessage = { 57 | n: "Sensor Name", 58 | tw: "SensorType.v1" 59 | }; 60 | handler.submission(wrongMessage, function(process){ 61 | assert.isFalse(process, "Message Shall be not processed Msg - invalid t key"); 62 | wrongMessage = { 63 | n: 1, 64 | v: "SensorType.v1" 65 | }; 66 | handler.submission(wrongMessage, function(process){ 67 | wrongMessage = { 68 | n: "", 69 | v: "SensorType.v1" 70 | }; 71 | handler.submission(wrongMessage ,function(process) { 72 | assert.isFalse(process, "Message Shall be not processed Msg - invalid n Value"); 73 | done(); 74 | }); 75 | }); 76 | }); 77 | }); 78 | }); 79 | it('Shall Return True if it a valid Registration Message >', function(done) { 80 | var okMessage = { 81 | n: "Sensor Name", 82 | v: 1000, 83 | on: 1234567890 84 | }; 85 | var ci = { cid: "thisCID", 86 | n: okMessage.n, 87 | t: "thisT"}; 88 | var store = { 89 | byName: function (name) { 90 | assert.isString(name, "Shall be the name of the Component"); 91 | assert.equal(name, okMessage.n, "Invalid Conversion of Name Property "); 92 | return ci; 93 | } 94 | }; 95 | 96 | connector.dataSubmit = function (metric, callback) { 97 | assert.isObject(metric, " Shall be an object"); 98 | assert.property(metric, "on", "It is required the ON Message"); 99 | assert.equal(metric.on, okMessage.on, "The TimeStamp were not propagated"); 100 | assert.equal(metric.count, 1, " The count shall be 1"); 101 | // done(); 102 | callback(true); 103 | return; 104 | }; 105 | var handler = toTest.init(connector, store, logger); 106 | handler.submission(okMessage, function(status){ 107 | assert.isTrue(status, "Message Shall be processed Msg "); 108 | done(); 109 | }); 110 | 111 | }); 112 | it('Shall Return False if it a valid Registration Message but the Component not exist >', function(done) { 113 | var okMessage = { 114 | n: "Sensor Name", 115 | v: 1000, 116 | on: 1234567890 117 | }; 118 | var ci = { cid: "thisCID", 119 | n: okMessage.n, 120 | t: "thisT"}; 121 | var store = { 122 | byName: function (name) { 123 | assert.isString(name, "Shall be the name of the Component"); 124 | assert.equal(name, okMessage.n, "Invalid Conversion of Name Property "); 125 | return null; 126 | } 127 | }; 128 | 129 | connector.dataSubmit = function (metric, callback) { 130 | assert.isObject(metric, " Shall be an object"); 131 | assert.property(metric, "on", "It is required the ON Message"); 132 | assert.equal(metric.on, okMessage.on, "The TimeStamp were not propagated"); 133 | assert.equal(metric.count, 1, " The count shall be 1"); 134 | // done(); 135 | callback(); 136 | }; 137 | var handler = toTest.init(connector, store, logger); 138 | handler.submission(okMessage, function (process){ 139 | assert.isTrue(process, "Message Shall be processed Msg "); 140 | done(); 141 | }); 142 | }); 143 | 144 | }); 145 | -------------------------------------------------------------------------------- /test/lib_httpClientTests.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2014, Intel Corporation 3 | 4 | Redistribution and use in source and binary forms, with or without modification, 5 | are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above copyright notice, 10 | this list of conditions and the following disclaimer in the documentation 11 | and/or other materials provided with the distribution. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 14 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 15 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 16 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 17 | ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 18 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 19 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 20 | ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 21 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 22 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 23 | */ 24 | 25 | var assert = require('chai').assert, 26 | rewire = require('rewire'); 27 | 28 | var fileToTest = "../lib/httpClient.js"; 29 | 30 | describe(fileToTest, function(){ 31 | var toTest = rewire(fileToTest); 32 | 33 | var logger = { 34 | info : function(){}, 35 | error : function() {}, 36 | debug : function() {} 37 | }; 38 | 39 | console.debug = function() { 40 | console.log(arguments); 41 | }; 42 | var resp = { 43 | statusCode: 200, 44 | headers: {'content-type': "application/json"} 45 | }; 46 | it('Shall Connect to Specific Broker using HTTP >', function(done){ 47 | var body = { 48 | a:1, 49 | b:2, 50 | x:[] 51 | }; 52 | var myOption = { 53 | host: "myhosta", 54 | port: 911, 55 | path: "mypath", 56 | protocol: "http", 57 | method: "POSTEO", 58 | body: {x:2,c:34}, 59 | headers: {"content": "json"} 60 | }; 61 | var request = function (option, callback) { 62 | assert.isNotNull(option, "The option is missing"); 63 | assert.isFunction(callback, "The callback is not a function"); 64 | assert.deepEqual(option, myOption); 65 | callback(null, resp, JSON.stringify(body)); 66 | }; 67 | toTest.__set__("request", request); 68 | toTest.httpRequest(myOption, function(err, result){ 69 | assert.isObject(result, "The result data is not an object"); 70 | assert.isNull(err, "The error shall be null"); 71 | assert.deepEqual(result, body, "The result were missinge"); 72 | done(); 73 | 74 | }); 75 | }); 76 | it('Shall Connect to Specific Broker using HTTP with a 201 as Status code >', function(done){ 77 | var body = { 78 | a:1, 79 | b:3, 80 | x:[] 81 | }; 82 | var myOption = { 83 | host: "myhostaTestingDos", 84 | port: 9121, 85 | path: "mypath", 86 | protocol: "http", 87 | method: "POSTEO", 88 | body: {x:2,c:34}, 89 | headers: {"content": "json"} 90 | }; 91 | var request = function (option, callback) { 92 | assert.isNotNull(option, "The option is missing"); 93 | assert.isFunction(callback, "The callback is not a function"); 94 | assert.deepEqual(option, myOption); 95 | var resp = { 96 | statusCode: 201, 97 | headers: {'content-type': "application/json"} 98 | }; 99 | callback(null, resp, JSON.stringify(body)); 100 | }; 101 | toTest.__set__("request", request); 102 | toTest.httpRequest(myOption, function(err, result){ 103 | assert.isObject(result, "The result data is not an object"); 104 | assert.isNull(err, "the error shall be null"); 105 | assert.deepEqual(result, body, "The result were missinge"); 106 | done(); 107 | 108 | }); 109 | }); 110 | it('Shall Connect to Specific Broker using HTTP with a 204 as Status code >', function(done){ 111 | var body = { 112 | a:1, 113 | b:3, 114 | x:[] 115 | }; 116 | var myOption = { 117 | host: "myhostaTestingDos", 118 | port: 9121, 119 | path: "mypath", 120 | protocol: "http", 121 | method: "POSTEO", 122 | body: {x:2,c:34}, 123 | headers: {"content": "json"} 124 | }; 125 | var request = function (option, callback) { 126 | assert.isNotNull(option, "The option is missing"); 127 | assert.isFunction(callback, "The callback is not a function"); 128 | assert.deepEqual(option, myOption); 129 | var resp = { 130 | statusCode: 204, 131 | headers: {'content-type': "application/json"} 132 | }; 133 | callback(null, resp, null); 134 | }; 135 | toTest.__set__("request", request); 136 | toTest.httpRequest(myOption, function(err, result){ 137 | assert.isObject(result, "The result data is not an object"); 138 | assert.isNull(err, "The error shall be null"); 139 | assert.equal(result.status, "Done", "The result were missing"); 140 | done(); 141 | 142 | }); 143 | }); 144 | it('Shall Return Null when the Payload could not be decoded >', function(done) { 145 | var body = { 146 | a:1, 147 | b:2, 148 | x:[] 149 | }; 150 | var myOption = { 151 | host: "myhosta", 152 | port: 911, 153 | method: "POSTEO", 154 | body: {x:2,c:34}, 155 | headers: {"content": "json"} 156 | }; 157 | var request = function (option, callback) { 158 | assert.isNotNull(option, "The option is missing"); 159 | assert.isFunction(callback, "The callback is not a function"); 160 | assert.deepEqual(option, myOption); 161 | callback(null, resp, "@@@@"); 162 | }; 163 | toTest.__set__("request", request); 164 | toTest.httpRequest(myOption, function(result){ 165 | assert.isNull(result, "The result data shall be null"); 166 | done(); 167 | 168 | }); 169 | }); 170 | }); 171 | --------------------------------------------------------------------------------