Device represents your physical device.
@param {Object} Connection The constructor function of the connection.
7475
function Device(Connection) {
  var self = this;

  // call super class
  EventEmitter2.call(this, {
    wildcard: true,
    delimiter: ':',
    maxListeners: 1000 // default would be 10!
  });

  if (this.log) {
    this.log = _.wrap(this.log, function(func, msg) {
      func(self.constructor.name + ': ' + msg);
    });
  } else if (Device.prototype.log) {
    Device.prototype.log = _.wrap(Device.prototype.log, function(func, msg) {
      func(self.constructor.name + ': ' + msg);
    });
    this.log = Device.prototype.log;
  } else {
    var debug = require('debug')(this.constructor.name);
    this.log = function(msg) {
      debug(msg);
    };
  }

  this.id = uuid();
  this.Connection = Connection;

  this.attributes = { id: this.id };

  this.on('disconnect', function() {
    self.connection = null;
  });
}
702803
function (connection, attempt) {
  var clonedAttempt = EJSON.clone(attempt);
  clonedAttempt.connection = connection;
  return clonedAttempt;
}
17836
function Device(key, name, children) {
    /**
     * @property key
     * @type {String}
     */
    this.key = key;
    /**
     * @property name
     * @type {String}
     */
    this.name = name;
    /**
     * @propety children
     * @type {Array}
     */
    this.children = children;
    /**
     * @property processChannels
     * @type {Array}
     */
    this.processChannels = [];
}
353280
public void addConnection (Connection connection) {
		if (connection == null) throw new IllegalArgumentException("connection cannot be null.");

		synchronized (connectionsLock) {
			Connection[] newConnections = new Connection[connections.length + 1];
			newConnections[0] = connection;
			System.arraycopy(connections, 0, newConnections, 1, connections.length);
			connections = newConnections;
		}

		connection.addListener(invokeListener);

		if (TRACE) trace("kryonet", "Added connection to ObjectSpace: " + connection);
	}
16902
void setParentConnection(final JmsJcaConnectionImpl connection) {

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, "setParentConnection", connection);
        }

        _connection = connection;

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "setParentConnection");
        }

    }
630661
function Message(connection) {
  // Inherit from event emitter
  var that = this;
  EventEmitter.call(this);

  // Save the connection
  this.connection = connection;

  // If there is a body already, don't buffer
  if (connection.body) {
    that.body = connection.body;
    async.setImmediate(function () {
      that.emit('loaded');
    });
    return;
  }

  // Buffer the content of the connecftion
  connection.pipe(concat(function handleBuffer (buff) {
    // Save the body and emit a `loaded` event
    // DEV: The delay is so `async.waterfall` still operates when we enter it
    that.body = buff.length ? buff : '';
    async.setImmediate(function () {
      that.emit('loaded');
    });
  }));
}
326840
public void dev_import(final Connection connection) throws DevFailed {
		Database db;
		if (connection.url.host == null) {
	    	db = ApiUtil.get_db_obj();
		} else {
	    	db = ApiUtil.get_db_obj(connection.url.host, connection.url.strPort);
		}
		// Check if device must be imported directly from IOR
        String  local_ior = null;
        boolean ior_read  = false;
		if (connection.ior == null) {
	    	final DbDevImportInfo info = db.import_device(connection.devname);
	    	if (info.exported) {
                 local_ior = info.ior;
                 ior_read = true;
	    	} else {
                Except.throw_connection_failed("TangoApi_DEVICE_NOT_EXPORTED",
                        connection.devname + " Not Exported !",
                        "Connection(" + connection.devname + ")");
             }
		} else {
	    	local_ior = connection.ior;
		}
		try {
	    	// Import the TANGO device
            try {
    	    	createDevice(connection, local_ior);
            }
            catch(final Exception e0) {
                if (ior_read || connection.isAlready_connected())
                    throw e0;   //  Has already been connected
				if (e0.toString().startsWith("org.omg.CORBA.TRANSIENT")) {
    				throw e0;   //  Connection failed (Hard killed)
				}
                // Else it is the first time, retry (ior could have changed)
                connection.ior = null;
                dev_import(connection);
            }

	    	connection.setAlready_connected(true);
	    	connection.ior = local_ior;

		} catch (final DevFailed e) {
	    	connection.device = null;
	    	connection.device_2 = null;
	    	connection.device_3 = null;
	    	connection.device_4 = null;
	    	connection.device_5 = null;
	    	connection.ior = null;
	    	throw e;
		} catch (final Exception e) {
	    	connection.device = null;
	    	connection.device_2 = null;
	    	connection.device_3 = null;
	    	connection.device_4 = null;
	    	connection.device_5 = null;
	    	connection.ior = null;
	    	final String reason = "TangoApi_CANNOT_IMPORT_DEVICE";
	    	final String s = connection.isAlready_connected() ? "Re-" : "";
	    	final String desc = "Cannot " + s + "import " + connection.devname + " :\n\t"
		    	+ e.toString();
	    	final String origin = "Connection.dev_import(" + connection.devname + ")";
	    	// e.printStackTrace();
	    	Except.throw_connection_failed(reason, desc, origin);
		}
    }
382174
function Device (client, opts) {
  var self = this
  if (!(self instanceof Device)) return new Device(client, opts)
  if (!opts) opts = {}

  self.client = client
}
739569
function(conn)
    {
    this._connection = conn;
        this._identities = [];
        this._features   = [];
        this._items      = [];
        // disco info
        conn.addHandler(this._onDiscoInfo.bind(this), Strophe.NS.DISCO_INFO, 'iq', 'get', null, null);
        // disco items
        conn.addHandler(this._onDiscoItems.bind(this), Strophe.NS.DISCO_ITEMS, 'iq', 'get', null, null);
    }
881666
function setup(connection) {

                var request = undefined;
                var reply_to = undefined;
                var response = undefined;

                node.connection = connection;

                // node connected
                node.status({ fill: 'green', shape: 'dot', text: 'connected' });

                node.sender = node.connection.open_sender({ target: {} });

                // build receiver options
                var receiver_options = {
                    source: {
                        address: node.address
                    }
                };
                node.receiver = node.connection.open_receiver(receiver_options);

                node.receiver.on('message', function(context) {

                    // save request and reply_to address on AMQP message received
                    request = context.message;
                    reply_to = request.reply_to;

                    // provides the request and delivery as node output
                    var msg = {
                        payload: context.message,
                        delivery: context.delivery
                    };
                    node.send(msg);
                });

                node.connection.on('disconnected', function(context) {
                    // node disconnected
                    node.status({fill: 'red', shape: 'dot', text: 'disconnected' });
                });

                node.on('input', function(msg) {
                    // enough credits to send
                    if (node.sender.sendable()) {

                        if (reply_to) {

                            // fill the response with the provided one as input
                            response = msg.payload;
                            response.to = reply_to;

                            node.sender.send(response);
                        }
                    }
                });

                node.on('close', function() {
                    if (node.sender != null)
                        node.sender.detach();
                    if (node.receiver != null)
                        node.receiver.detach();
                    node.connection.close();
                })

            }
1357590
function SipConnection(connection, connectCallback) {
    function isData(session) {
        return !session.audio && !session.video && !session.screen && session.data;
    }

    connection.socket = {
        send: function(data) {
            var remoteSipURI = data.remoteUserId + '@yourServer.com';
            sip.publish(remoteSipURI, data); // maybe JSON.stringify(data)
        }
    };

    // connect/subscribe to SIP here

    // ref: http://sipjs.com/demo-phone/
    // and: http://sipjs.com/demo-phone/js/ua.js
    var config = {
        userAgentString: 'SIP.js/0.7.0 BB',
        traceSip: true,
        register: false,
        displayName: '',
        uri: '', // connection.userid + '@yourServer.com'
        authorizationUser: '',
        password: '',
        wsServers: 'wss://edge.sip.onsip.com'
    };

    var sip = new SIP.UA(config);

    sip.on('invite', function(session) {
        // do the stuff!
    });

    sip.on('message', function(data) {
        data = JSON.parse(data);

        if (data.eventName === connection.socketMessageEvent) {
            onMessagesCallback(data.data);
        }

        if (data.eventName === 'presence') {
            data = data.data;
            if (data.userid === connection.userid) return;
            connection.onUserStatusChanged({
                userid: data.userid,
                status: data.isOnline === true ? 'online' : 'offline',
                extra: connection.peers[data.userid] ? connection.peers[data.userid].extra : {}
            });
        }
    });

    // connected or registered
    sip.on('connected', function() {
        if (connection.enableLogs) {
            console.info('SIP connection is opened.');
        }

        connection.socket.emit('presence', {
            userid: connection.userid,
            isOnline: true
        });

        if (connectCallback) connectCallback(connection.socket);
    });

    sip.on('unregistered', function() {
        if (!connection.enableLogs) return;
        console.warn('Socket connection is closed.');
    });

    connection.socket.emit = function(eventName, data, callback) {
        if (eventName === 'changed-uuid') return;
        if (data.message && data.message.shiftedModerationControl) return;

        connection.socket.send({
            eventName: eventName,
            data: data
        });

        if (callback) {
            callback(true);
        }
    };

    var mPeer = connection.multiPeersHandler;

    function onMessagesCallback(message) {
        if (message.remoteUserId != connection.userid) return;

        if (connection.peers[message.sender] && connection.peers[message.sender].extra != message.message.extra) {
            connection.peers[message.sender].extra = message.message.extra;
            connection.onExtraDataUpdated({
                userid: message.sender,
                extra: message.message.extra
            });
        }

        if (message.message.streamSyncNeeded && connection.peers[message.sender]) {
            var stream = connection.streamEvents[message.message.streamid];
            if (!stream || !stream.stream) {
                return;
            }

            var action = message.message.action;

            if (action === 'ended' || action === 'stream-removed') {
                connection.onstreamended(stream);
                return;
            }

            var type = message.message.type != 'both' ? message.message.type : null;
            stream.stream[action](type);
            return;
        }

        if (message.message === 'connectWithAllParticipants') {
            if (connection.broadcasters.indexOf(message.sender) === -1) {
                connection.broadcasters.push(message.sender);
            }

            mPeer.onNegotiationNeeded({
                allParticipants: connection.getAllParticipants(message.sender)
            }, message.sender);
            return;
        }

        if (message.message === 'removeFromBroadcastersList') {
            if (connection.broadcasters.indexOf(message.sender) !== -1) {
                delete connection.broadcasters[connection.broadcasters.indexOf(message.sender)];
                connection.broadcasters = removeNullEntries(connection.broadcasters);
            }
            return;
        }

        if (message.message === 'dropPeerConnection') {
            connection.deletePeer(message.sender);
            return;
        }

        if (message.message.allParticipants) {
            if (message.message.allParticipants.indexOf(message.sender) === -1) {
                message.message.allParticipants.push(message.sender);
            }

            message.message.allParticipants.forEach(function(participant) {
                mPeer[!connection.peers[participant] ? 'createNewPeer' : 'renegotiatePeer'](participant, {
                    localPeerSdpConstraints: {
                        OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                        OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                    },
                    remotePeerSdpConstraints: {
                        OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                        OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                    },
                    isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
                    isDataOnly: isData(connection.session)
                });
            });
            return;
        }

        if (message.message.newParticipant) {
            if (message.message.newParticipant == connection.userid) return;
            if (!!connection.peers[message.message.newParticipant]) return;

            mPeer.createNewPeer(message.message.newParticipant, message.message.userPreferences || {
                localPeerSdpConstraints: {
                    OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                remotePeerSdpConstraints: {
                    OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                isOneWay: !!connection.session.oneway || connection.direction === 'one-way',
                isDataOnly: isData(connection.session)
            });
            return;
        }

        if (message.message.readyForOffer || message.message.addMeAsBroadcaster) {
            connection.addNewBroadcaster(message.sender);
        }

        if (message.message.newParticipationRequest && message.sender !== connection.userid) {
            if (connection.peers[message.sender]) {
                connection.deletePeer(message.sender);
            }

            var userPreferences = {
                extra: message.message.extra || {},
                localPeerSdpConstraints: message.message.remotePeerSdpConstraints || {
                    OfferToReceiveAudio: connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                remotePeerSdpConstraints: message.message.localPeerSdpConstraints || {
                    OfferToReceiveAudio: connection.session.oneway ? !!connection.session.audio : connection.sdpConstraints.mandatory.OfferToReceiveAudio,
                    OfferToReceiveVideo: connection.session.oneway ? !!connection.session.video || !!connection.session.screen : connection.sdpConstraints.mandatory.OfferToReceiveVideo
                },
                isOneWay: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
                isDataOnly: typeof message.message.isDataOnly !== 'undefined' ? message.message.isDataOnly : isData(connection.session),
                dontGetRemoteStream: typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way',
                dontAttachLocalStream: !!message.message.dontGetRemoteStream,
                connectionDescription: message,
                successCallback: function() {
                    // if its oneway----- todo: THIS SEEMS NOT IMPORTANT.
                    if (typeof message.message.isOneWay !== 'undefined' ? message.message.isOneWay : !!connection.session.oneway || connection.direction === 'one-way') {
                        connection.addNewBroadcaster(message.sender, userPreferences);
                    }

                    if (!!connection.session.oneway || connection.direction === 'one-way' || isData(connection.session)) {
                        connection.addNewBroadcaster(message.sender, userPreferences);
                    }
                }
            };

            connection.onNewParticipant(message.sender, userPreferences);
            return;
        }

        if (message.message.shiftedModerationControl) {
            connection.onShiftedModerationControl(message.sender, message.message.broadcasters);
            return;
        }

        if (message.message.changedUUID) {
            if (connection.peers[message.message.oldUUID]) {
                connection.peers[message.message.newUUID] = connection.peers[message.message.oldUUID];
                delete connection.peers[message.message.oldUUID];
            }
        }

        if (message.message.userLeft) {
            mPeer.onUserLeft(message.sender);

            if (!!message.message.autoCloseEntireSession) {
                connection.leave();
            }

            return;
        }

        mPeer.addNegotiatedMessage(message.message, message.sender);
    }

    window.addEventListener('beforeunload', function() {
        connection.socket.emit('presence', {
            userid: connection.userid,
            isOnline: false
        });
    }, false);
}
274278
protected void removeConnection(ConnectionImpl connection) {
        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.entry(tc, "removeConnection", connection);

        synchronized (_connections) {
            _connections.remove(connection);
        }

        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.exit(tc, "removeConnection");
    }
589084
function handleConnection(self, options) {
	if (TRACE)	console.log('Connected to ' + options.host + ':' + options.port)
    	//self.socket = socket;
	self.emit("connect");
}
232195
CompletableFuture<Void> connect(LocalConnection connection) {
    LocalConnection localConnection = new LocalConnection(listener.context, connections);
    connections.add(localConnection);
    connection.connect(localConnection);
    localConnection.connect(connection);
    return CompletableFuture.runAsync(() -> listener.listener.accept(localConnection), listener.context.executor());
  }
928535
private void createDevice(final Connection connection, final String corba_str) throws DevFailed {
		try {
	    	// Build corba object
	    	final ORB orb = ApiUtil.get_orb();
	    	connection.setObj(orb.string_to_object(corba_str));
		}
        catch (final RuntimeException e) {
	    	Except.throw_connection_failed("TangoApi_TANGO_HOST_NOT_VALID", e.toString().substring(
		    	e.toString().indexOf(":") + 2), "Connection.createDevice()");
		}
		// Get default timeout from env or fix it if not set
		String strTimeout;
		if ((strTimeout = ApiUtil.getStrDefaultTimeout()) == null) {
	    	strTimeout = "3000";
		}
		try {
	    	connection.setDev_timeout(Integer.parseInt(strTimeout));
		}
        catch (final Exception e) {
	    	ApiUtilDAODefaultImpl.removePendingRepliesOfDevice(connection);
	    	e.printStackTrace();
		}
		set_obj_timeout(connection, connection.getDev_timeout());

		// Construct the Object
		if (connection.getObj()._is_a("IDL:Tango/Device_5:1.0")) {
	    	//System.out.println(connection.devname + " Device is a Tango/Device_5:1.0 !!!!!!!!!");
	    	connection.device_5 = Device_5Helper.narrow(connection.getObj());
	    	connection.device_4 = connection.device_5;
	    	connection.device_3 = connection.device_5;
	    	connection.device_2 = connection.device_5;
	    	connection.device = connection.device_5;
	    	connection.idl_version = 5;
        }
        else if (connection.getObj()._is_a("IDL:Tango/Device_4:1.0")) {
	    	// System.out.println("Device is a Tango/Device_4:1.0 !!!!!!!!!");
            connection.device_5 = null;
	    	connection.device_4 = Device_4Helper.narrow(connection.getObj());
	    	connection.device_3 = connection.device_4;
	    	connection.device_2 = connection.device_4;
	    	connection.device = connection.device_4;
	    	connection.idl_version = 4;
		}
        else if (connection.getObj()._is_a("IDL:Tango/Device_3:1.0")) {
	    	// System.out.println("Device is a Tango/Device_3:1.0 !!!!!!!!!");
            connection.device_5 = null;
	    	connection.device_4 = null;
	    	connection.device_3 = Device_3Helper.narrow(connection.getObj());
	    	connection.device_2 = connection.device_3;
	    	connection.device = connection.device_3;
	    	connection.idl_version = 3;
		}
        else if (connection.getObj()._is_a("IDL:Tango/Device_2:1.0")) {
	    	System.err.println("Device " + connection.get_name() + " is a Tango/Device_2:1.0 !!!!!!!!!");
            connection.device_5 = null;
	    	connection.device_4 = null;
	    	connection.device_3 = null;
	    	connection.device_2 = Device_2Helper.narrow(connection.getObj());
	    	connection.device = connection.device_2;
	    	connection.idl_version = 2;
		}
        else if (connection.getObj()._is_a("IDL:Tango/Device:1.0")) {
	    	System.err.println("Device " + connection.get_name() + " is a Tango/Device:1.0 !!!!!!!!!");
            connection.device_5 = null;
	    	connection.device_4 = null;
	    	connection.device_3 = null;
	    	connection.device_2 = null;
	    	connection.device = DeviceHelper.narrow(connection.getObj());
	    	connection.idl_version = 1;
		}
        else {
	    	System.err.println("TangoApi_DEVICE_IDL_UNKNOWN!");
	    	Except.throw_non_supported_exception("TangoApi_DEVICE_IDL_UNKNOWN", connection.devname
		    	+ " has an IDL revision not supported !", "Connection.createDevice("
		    	+ connection.devname + ")");
		}

		// Force a network is_a() here for error
		// management of build_connection()
		// We do not use ping() as it can be serialized
		// at the server level

		connection.getObj()._is_a("Dummy");
    }
219951
function(isGateway) {

        // Remove the host/app/instance params if connecting directly.
        if (!isGateway) {
          delete monitorJSON.hostName;
          delete monitorJSON.appName;
          delete monitorJSON.appInstance;
        }

        // Define the connect/error listeners
        var onConnect = function() {
          removeListeners();
          callback(null, connection);
        };
        var onError = function(err) {
          removeListeners();
          log.error('connect.error', err);
          callback({msg: 'connection error', err:err});
        };
        var removeListeners = function() {
          connection.off('connect', onConnect);
          connection.off('error', onError);
        };

        // Wait if the connection is still awaiting connect
        if (connection && connection.connecting) {
          connection.on('connect', onConnect);
          connection.on('error', onError);
          return;
        }

        // Re-try if disconnected
        if (connection && !connection.connected) {
          connection.on('connect', onConnect);
          connection.on('error', onError);
          return connection.connect(callback);
        }

        // Verified connection
        return callback(null, connection);
      }
214863
function Device (sock1,sock2) {
    var that = this;
    this.sock1= sock1;
    this.sock2 = sock2;
    this.s1 = -1;
    this.s2 = -1;

    if(sock1 instanceof Socket) {
        this.s1 = sock1.binding;

        if(sock2 instanceof Socket) {
            this.s2 = sock2.binding;
        }

        this._timer = setImmediate(function () {
            nn.DeviceWorker(that.s1, that.s2, function (err) {
                that.emit('error', new Error('lib err: '+ err +'\n'+ nn.Err()));
            });
        });

    } else {
        throw new Error('expected at least one Socket argument');
    }

    EventEmitter.call(this);
}