beforeEach(function(done) {
        logger.setLevel('FATAL');

        iotAgentLib.activate(iotAgentConfig, function() {
            iotAgentLib.clearAll(done);
        });
    });
    beforeEach(function(done) {
        nock.cleanAll();
        logger.setLevel('FATAL');
        iotamMock = nock('http://localhost:8082')
            .post('/protocols')
            .reply(200, {});

        iotAgentLib.activate(iotAgentConfig, done);
    });
Exemplo n.º 3
0
function setConfig(newConfig) {
    config = newConfig;

    if (config.logLevel) {
        logger.setLevel(config.logLevel);
    }

    processEnvironmentVariables();
}
Exemplo n.º 4
0
/**
 * Register the client in the Lightweight M2M Server in the seleted host and port, with the given endpoint name. If the
 * registration is successful, a deviceInformation object is returned with the host and port of the connected server
 * and the device location in that server (usually with the form '/rd/<deviceId>').
 *
 * @param {String} host                  Host of the LWTM2M Server
 * @param {String} port                  Port of the LWTM2M Server
 * @param {String} url                   URL of the LWTM2M Server (optional)
 * @param {String} endpointName          Name the client will be registered under
 */
function register(host, port, url, endpointName, callback) {
    var rs = new Readable(),
        creationRequest =  {
            host: host,
            port: port,
            method: 'POST',
            pathname: ((url)? url : '') + '/rd',
            query: 'ep=' +  endpointName + '&lt=' + config.client.lifetime + '&lwm2m=' + config.client.version + '&b=U'
        },
        agent = new coap.Agent({type: config.client.ipProtocol}),
        req = agent.request(creationRequest),
        deviceInformation = {
            currentHost: host,
            currentPort: port,
            location: ''
        };

    if (config.logLevel) {
        logger.setLevel(config.client.logLevel);
    }

    function sendRequest(payload, innerCallback) {
        logger.debug(context, 'Sending registration request');

        rs.push(payload);
        rs.push(null);

        rs.on('error', function(error) {
            logger.error(context, 'Error found trying to send registration request: %s', payload);
            innerCallback(new errors.RegistrationError(error));
        });

        req.on('response', createRegisterResponseHandler(deviceInformation, innerCallback));

        req.on('error', function(error) {
            req.removeAllListeners();

            if (error.code === 'ENOTFOUND') {
                logger.error(context, 'Server not found [%s]', req.url.host);
                innerCallback(new errors.ServerNotFound(req.url.host));
            } else {
                logger.error(context, 'An error was found while trying to register a response listener');
                innerCallback(new errors.RegistrationError(error));
            }
        });

        rs.pipe(req);
    }

    async.waterfall([
        objRegistry.list,
        generatePayload,
        sendRequest,
        async.apply(startListener, deviceInformation)
    ], callback);
}
    beforeEach(function(done) {
        logger.setLevel('FATAL');

        iotAgentLib.activate(iotAgentConfig, function() {
            iotAgentLib.clearAll(function() {
                iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.timestampProcess.update);
                done();
            });
        });
    });
    beforeEach(function(done) {
        logger.setLevel('FATAL');

        iotAgentLib.activate(iotAgentConfig, function() {
            iotAgentLib.clearAll(function() {
                iotAgentLib.addUpdateMiddleware(iotAgentLib.dataPlugins.attributeAlias.update);
                iotAgentLib.addQueryMiddleware(iotAgentLib.dataPlugins.attributeAlias.query);
                done();
            });
        });
    });
/**
 * Start the IoT Agent using the selected config.
 *
 * @param {Object} localConfig          Configuration object to use in the IoT Agent.
 */
function start(localConfig, callback) {
    config = localConfig;
    logger.setLevel(config.lwm2m.logLevel);

    ngsiHandlers.init(config);
    commons.init(config);

    async.series([
        apply(lwm2mLib.start, localConfig.lwm2m),
        apply(iotAgentLib.activate, localConfig.ngsi)
    ], function(error, results) {
        if (error) {
            callback(error);
        } else {
            serverInfo = results[0];
            initialize(callback);
        }
    });
}
Exemplo n.º 8
0
  /**
   * Sets the log level to the value passed in the request
   * @param request The received request
   * @param reply hapi's server reply() function
   */
  function setLogLevelHandler(request, reply) {
    request.sth = request.sth || {};
    request.sth.context = getContext(request);

    sthLogger.debug(
      request.sth.context,
      request.method.toUpperCase() + ' ' + request.url.path +
      ' with headers: ' + JSON.stringify(request.headers)
    );

    var level = (request.query.level.toUpperCase() === 'WARNING') ?
      'WARN' : request.query.level.toUpperCase();
    sthLogger.setLevel(level);

    sthLogger.info(
      request.sth.context,
      'Log level set to: ' + level
    );

    reply();
  }
Exemplo n.º 9
0
function start(config, startCallback) {
    function loadDefaults(serverInfo, callback) {
        loadRoutes(serverInfo);
        loadDefaultHandlers(serverInfo, config);
        callback(null, serverInfo);
    }

    if (config.logLevel) {
        logger.setLevel(config.logLevel);
    }

    logger.info(context, 'Starting Lightweight M2M Server');

    if (config.deviceRegistry && config.deviceRegistry.type === 'mongodb') {
        logger.info(context, 'Mongo DB Device registry selected for Lightweight M2M Library');
        registry = require('./services/server/mongodbDeviceRegistry');
    } else {
        logger.info(context, 'Memory Device registry selected for Lightweight M2M Library');
        registry = require('./services/server/inMemoryDeviceRegistry');
    }

    deviceManagement.init(registry);
    informationReporting.init(registry);
    coapUtils.init(config);

    exports.listDevices = registry.list;
    exports.getDevice = registry.getByName;

    async.waterfall([
        apply(validateTypes, config),
        apply(registry.init, config),
        registry.clean,
        apply(coapRouter.start, config),
        loadDefaults
    ], startCallback);
}
Exemplo n.º 10
0
/**
 * Activates the IoT Agent to start listening for NGSI Calls (to act as a Context Provider). It also creates the
 * device registry for the IoT Agent (based on the deviceRegistry.type configuration option).
 *
 * @param {Object} newConfig            Configuration of the Context Server
 */
function doActivate(newConfig, callback) {
    var registry,
        groupRegistry;

    config.setConfig(newConfig);

    logger.format = logger.formatters.pipe;

    logger.getContext = function domainContext() {
        var domainObj = require('domain').active || {};

        return {
            corr: domainObj.corr,
            trans: domainObj.trans,
            op: domainObj.op,
            srv: domainObj.service,
            subsrv: domainObj.subservice,
            msg: domainObj.msg
        };
    };

    if (config.getConfig().logLevel) {
        logger.setLevel(config.getConfig().logLevel);
    }

    logger.info(context, 'Activating IOT Agent NGSI Library.');

    if (newConfig.deviceRegistry &&
        newConfig.deviceRegistry.type &&
        newConfig.deviceRegistry.type === 'mongodb') {
        logger.info(context, 'MongoDB Device registry selected for NGSI Library');

        registry = require('./services/devices/deviceRegistryMongoDB');
        groupRegistry = require('./services/groups/groupRegistryMongoDB');
    } else {
        logger.info(context, 'Falling back to Transient Memory registry for NGSI Library');

        registry = require('./services/devices/deviceRegistryMemory');
        groupRegistry = require('./services/groups/groupRegistryMemory');
    }

    exports.clearAll = function(callback) {
        async.series([
            registry.clear,
            groupRegistry.clear,
            ngsi.resetMiddlewares
        ], callback);
    };

    if (!config.getConfig().dieOnUnexpectedError) {
        process.on('uncaughtException', globalErrorHandler);
    }

    config.setRegistry(registry);
    config.setGroupRegistry(groupRegistry);

    async.series([
        db.configureDb,
        apply(contextServer.start, newConfig),
        apply(activateStatLogs, newConfig)
    ], callback);
}
Exemplo n.º 11
0
/**
 * Looks for environment variables that could override configuration values.
 */
function processEnvironmentVariables() {
    var environmentVariables = [
            'IOTA_SERVER_PORT',
            'IOTA_SERVER_HOST',
            'IOTA_LOG_LEVEL'
        ],
        serverVariables = [
            'IOTA_SERVER_PORT',
            'IOTA_SERVER_HOST'
        ],
        mongoVariables = [
            'IOTA_MONGO_HOST',
            'IOTA_MONGO_PORT',
            'IOTA_MONGO_DB',
            'IOTA_MONGO_REPLICASET',
            'IOTA_MONGO_RETRIES',
            'IOTA_MONGO_RETRY_TIME'
        ];

    for (var i = 0; i < environmentVariables.length; i++) {
        if (process.env[environmentVariables[i]]) {
            logger.info('Setting %s to environment value: %s',
                environmentVariables[i], process.env[environmentVariables[i]]);
        }
    }

    if (anyIsSet(serverVariables)) {
        config.server = {};
    }

    if (process.env.IOTA_SERVER_HOST) {
        config.server.host = process.env.IOTA_SERVER_HOST;
    }

    if (process.env.IOTA_SERVER_PORT) {
        config.server.port = process.env.IOTA_SERVER_PORT;
    }

    if (process.env.IOTA_LOG_LEVEL) {
        config.logLevel = process.env.IOTA_LOG_LEVEL;
        logger.setLevel(process.env.IOTA_LOG_LEVEL);
    }

    if (anyIsSet(mongoVariables)) {
        config.mongodb = {};
    }

    if (process.env.IOTA_MONGO_HOST) {
        config.mongodb.host = process.env.IOTA_MONGO_HOST;
    }

    if (process.env.IOTA_MONGO_PORT) {
        config.mongodb.port = process.env.IOTA_MONGO_PORT;
    }

    if (process.env.IOTA_MONGO_DB) {
        config.mongodb.db = process.env.IOTA_MONGO_DB;
    }

    if (process.env.IOTA_MONGO_REPLICASET) {
        config.mongodb.replicaSet = process.env.IOTA_MONGO_REPLICASET;
    }

    if (process.env.IOTA_MONGO_RETRIES) {
        config.mongodb.retries = process.env.IOTA_MONGO_RETRIES;
    }

    if (process.env.IOTA_MONGO_RETRY_TIME) {
        config.mongodb.retryTime = process.env.IOTA_MONGO_RETRY_TIME;
    }

}
Exemplo n.º 12
0
/**
 * Looks for environment variables that could override configuration values.
 */
function processEnvironmentVariables() {
    var environmentVariables = [
             'IOTA_CB_URL',
             'IOTA_CB_HOST',
             'IOTA_CB_PORT',
             'IOTA_CB_NGSI_VERSION',
             'IOTA_NORTH_HOST',
             'IOTA_NORTH_PORT',
             'IOTA_PROVIDER_URL',
             'IOTA_AUTH_ENABLED',
             'IOTA_AUTH_TYPE',
             'IOTA_AUTH_HEADER',
             'IOTA_AUTH_URL',
             'IOTA_AUTH_HOST',
             'IOTA_AUTH_PORT',
             'IOTA_AUTH_USER',
             'IOTA_AUTH_PASSWORD',
             'IOTA_AUTH_CLIENT_ID',
             'IOTA_AUTH_CLIENT_SECRET',
             'IOTA_AUTH_TOKEN_PATH',
             'IOTA_AUTH_PERMANENT_TOKEN',
             'IOTA_REGISTRY_TYPE',
             'IOTA_LOG_LEVEL',
             'IOTA_TIMESTAMP',
             'IOTA_IOTAM_HOST',
             'IOTA_IOTAM_PORT',
             'IOTA_IOTAM_PATH',
             'IOTA_IOTAM_PROTOCOL',
             'IOTA_IOTAM_DESCRIPTION',
             'IOTA_DEFAULT_RESOURCE',
             'IOTA_MONGO_HOST',
             'IOTA_MONGO_PORT',
             'IOTA_MONGO_DB',
             'IOTA_MONGO_REPLICASET',
             'IOTA_AUTOCAST',
             'IOTA_MONGO_RETRIES',
             'IOTA_MONGO_RETRY_TIME',
             'IOTA_SINGLE_MODE',
             'IOTA_APPEND_MODE',
             'IOTA_POLLING_EXPIRATION',
             'IOTA_POLLING_DAEMON_FREQ'
        ],
        iotamVariables = [
            'IOTA_IOTAM_URL',
            'IOTA_IOTAM_HOST',
            'IOTA_IOTAM_PORT',
            'IOTA_IOTAM_PATH',
            'IOTA_IOTAM_PROTOCOL',
            'IOTA_IOTAM_DESCRIPTION',
            'IOTA_IOTAM_AGENTPATH'
        ],
        mongoVariables = [
            'IOTA_MONGO_HOST',
            'IOTA_MONGO_PORT',
            'IOTA_MONGO_DB',
            'IOTA_MONGO_REPLICASET',
            'IOTA_MONGO_RETRIES',
            'IOTA_MONGO_RETRY_TIME'
        ];

    for (var i = 0; i < environmentVariables.length; i++) {
        if (process.env[environmentVariables[i]]) {
            logger.info(context, 'Setting %s to environment value: %s',
                environmentVariables[i], process.env[environmentVariables[i]]);
        }
    }

    // Context Broker Configuration
    if (process.env.IOTA_CB_URL) {
        config.contextBroker.url = process.env.IOTA_CB_URL;
    } else if (process.env.IOTA_CB_HOST) {
        config.contextBroker.host = process.env.IOTA_CB_HOST;
        config.contextBroker.url = 'http://' + process.env.IOTA_CB_HOST;
        if (process.env.IOTA_CB_PORT) {
            config.contextBroker.url += ':' + process.env.IOTA_CB_PORT;
        } else {
            config.contextBroker.url += ':' + config.contextBroker.port;
        }
    }

    if (process.env.IOTA_CB_HOST) {
        config.contextBroker.host = process.env.IOTA_CB_HOST;
    }
    if (process.env.IOTA_CB_PORT) {
        config.contextBroker.port = process.env.IOTA_CB_PORT;
    }
    if (process.env.IOTA_CB_NGSI_VERSION) {
        config.contextBroker.ngsiVersion = process.env.IOTA_CB_NGSI_VERSION;
    }

    // North Port Configuration
    if (process.env.IOTA_NORTH_HOST) {
        config.server.host = process.env.IOTA_NORTH_HOST;
    }
    if (process.env.IOTA_NORTH_PORT) {
        config.server.port = process.env.IOTA_NORTH_PORT;
    }

    if (process.env.IOTA_PROVIDER_URL) {
        config.providerUrl = process.env.IOTA_PROVIDER_URL;
    }

    // Authentication Parameters - General
    if (process.env.IOTA_AUTH_ENABLED) {
        config.authentication = {};
        config.authentication.enabled = process.env.IOTA_AUTH_ENABLED === 'true';
    }
    if (process.env.IOTA_AUTH_TYPE) {
        config.authentication.type = process.env.IOTA_AUTH_TYPE;
    }
    if (process.env.IOTA_AUTH_HEADER) {
        config.authentication.header = process.env.IOTA_AUTH_HEADER;
    }
    if (process.env.IOTA_AUTH_URL) {
        config.authentication.url = process.env.IOTA_AUTH_URL;
    } else if (process.env.IOTA_AUTH_HOST) {
        config.authentication.host = process.env.IOTA_AUTH_HOST;
        config.authentication.url = 'http://' + process.env.IOTA_AUTH_HOST;
        if (process.env.IOTA_AUTH_PORT) {
            config.authentication.url += ':' + process.env.IOTA_AUTH_PORT;
        } else {
            config.authentication.url += ':' + config.authentication.port;
        }
    }
    if (process.env.IOTA_AUTH_HOST) {
        config.authentication.host = process.env.IOTA_AUTH_HOST;
    }
    if (process.env.IOTA_AUTH_PORT) {
        config.authentication.port = process.env.IOTA_AUTH_PORT;
    }
    // Authentication Parameters - Oauth + Keyrock
    if (process.env.IOTA_AUTH_CLIENT_ID) {
        config.authentication.clientId = process.env.IOTA_AUTH_CLIENT_ID;
    }
    if (process.env.IOTA_AUTH_CLIENT_SECRET) {
        config.authentication.clientSecret = process.env.IOTA_AUTH_CLIENT_SECRET;
    }
    if (process.env.IOTA_AUTH_TOKEN_PATH) {
        config.authentication.tokenPath = process.env.IOTA_AUTH_TOKEN_PATH;
    }
    // Authentication Parameters - Keyrock only
    if (process.env.IOTA_AUTH_PERMANENT_TOKEN) {
        config.authentication.permanentToken = process.env.IOTA_AUTH_PERMANENT_TOKEN;
    }
    // Authentication Parameters - Keystone only
    if (process.env.IOTA_AUTH_USER) {
        config.authentication.user = process.env.IOTA_AUTH_USER;
    }
    if (process.env.IOTA_AUTH_PASSWORD) {
        config.authentication.password = process.env.IOTA_AUTH_PASSWORD;
    }

    // Registry configuration (memory or database)
    if (process.env.IOTA_REGISTRY_TYPE) {
        config.deviceRegistry = {};
        config.deviceRegistry.type = process.env.IOTA_REGISTRY_TYPE;
    }

    // Log Level configuration
    if (process.env.IOTA_LOG_LEVEL) {
        config.logLevel = process.env.IOTA_LOG_LEVEL;
        logger.setLevel(process.env.IOTA_LOG_LEVEL);
    }

    // Whether to include timestamps
    if (process.env.IOTA_TIMESTAMP) {
        config.timestamp = process.env.IOTA_TIMESTAMP === 'true';
    }

    // Default resource
    if (process.env.IOTA_DEFAULT_RESOURCE) {
        config.defaultResource = process.env.IOTA_DEFAULT_RESOURCE;
    }

    // IoT Manager Configuration
    if (anyIsSet(iotamVariables)) {
        config.iotManager = {};
    }

    if (process.env.IOTA_IOTAM_URL) {
        config.iotManager.url = process.env.IOTA_IOTAM_URL;
    } else if (process.env.IOTA_IOTAM_HOST) {
        config.iotManager.url = 'http://' + process.env.IOTA_IOTAM_HOST;
        if (process.env.IOTA_IOTAM_PORT) {
            config.iotManager.url += ':' + process.env.IOTA_IOTAM_PORT;
        } else {
            config.iotManager.url += ':' + config.iotManager.port;
        }
    }

    if (process.env.IOTA_IOTAM_PATH) {
        config.iotManager.path = process.env.IOTA_IOTAM_PATH;
    }

    if (process.env.IOTA_IOTAM_PROTOCOL) {
        config.iotManager.protocol = process.env.IOTA_IOTAM_PROTOCOL;
    }

    if (process.env.IOTA_IOTAM_DESCRIPTION) {
        config.iotManager.description = process.env.IOTA_IOTAM_DESCRIPTION;
    }

    if (process.env.IOTA_IOTAM_AGENTPATH) {
        config.iotManager.agentPath = process.env.IOTA_IOTAM_AGENTPATH;
    }

    // Mongo DB configuration
    if (anyIsSet(mongoVariables)) {
        config.mongodb = {};
    }

    if (process.env.IOTA_MONGO_HOST) {
        config.mongodb.host = process.env.IOTA_MONGO_HOST;
    }

    if (process.env.IOTA_MONGO_PORT) {
        config.mongodb.port = process.env.IOTA_MONGO_PORT;
    }

    if (process.env.IOTA_MONGO_DB) {
        config.mongodb.db = process.env.IOTA_MONGO_DB;
    }

    if (process.env.IOTA_MONGO_REPLICASET) {
        config.mongodb.replicaSet = process.env.IOTA_MONGO_REPLICASET;
    }

    if (process.env.IOTA_MONGO_RETRIES) {
        config.mongodb.retries = process.env.IOTA_MONGO_RETRIES;
    }

    if (process.env.IOTA_MONGO_RETRY_TIME) {
        config.mongodb.retryTime = process.env.IOTA_MONGO_RETRY_TIME;
    }

    // Other configuration properties
    if (process.env.IOTA_SINGLE_MODE) {
        config.singleConfigurationMode = process.env.IOTA_SINGLE_MODE === 'true';
    }

    if (process.env.IOTA_APPEND_MODE) {
        config.appendMode = process.env.IOTA_APPEND_MODE === 'true';
    }

    if (process.env.IOTA_POLLING_EXPIRATION) {
        config.pollingExpiration = process.env.IOTA_POLLING_EXPIRATION;
    }

    if (process.env.IOTA_POLLING_DAEMON_FREQ) {
        config.pollingDaemonFrequency = process.env.IOTA_POLLING_DAEMON_FREQ;
    }

    if (process.env.IOTA_AUTOCAST) {
        config.autocast = process.env.IOTA_AUTOCAST === 'true';
    }

}
 beforeEach(function() {
     logger.setLevel('FATAL');
 });
/**
 * Initializes the device registry based on the parameter found in the configuration. For this in memory registry this
 * function doesn't do anything.
 *
 * @param {Object} config           Configuration object.
 */
function init(config, callback) {
    if (config.logLevel) {
        logger.setLevel(config.logLevel);
    }
    callback(null);
}
 beforeEach(function() {
     logger.setLevel('FATAL');
     iotAgentConfig.authentication.permanentToken = true;
 });