Connect to an MQTT broker.

@param broker
Uri of the broker to connect to
@param clientId
Client Id
@throws MqttException
if there is an issue connecting to the broker
346086
@RobotKeyword("Connect to MQTT Broker")
    @ArgumentNames({ "broker", "clientId" })
    public void connectToMQTTBroker(String broker, String clientId)
            throws MqttException {
        client = new MqttClient(broker, clientId);
        System.out.println("*INFO:" + System.currentTimeMillis()
                + "* connecting to broker");
        client.connect();
        System.out.println("*INFO:" + System.currentTimeMillis()
                + "* connected");
    }
982074
@Override
	public final void setClientID(String clientID) throws JMSException
    {
    	externalAccessLock.readLock().lock();
    	try
    	{
	        super.setClientID(clientID);
	        try
	        {
	        	ClientIDRegistry.getInstance().register(clientID);
	        }
	        catch (JMSException e)
	        {
	        	this.clientID = null; // Clear client ID
	        	throw e;
	        }
    	}
    	finally
    	{
    		externalAccessLock.readLock().unlock();
    	}
    }
149531
function(config) {
	  
     var client = mqtt.connect(config.server + ':' + config.port);
     client.subscribe(this.id);
     
	 client.on('message', function(topic, message) {
       /*
        * This is called when a result to a third party call request is delivered.  
        */
       l('DEBUG') && console.log('3PCC.mqttClient - Received Message on topic: '+topic);

	   //	First convert to a JS object;
       message = JSON.parse(message);
	   
		//	Next cancel the response timer.
		var respTimer = respTimerMap[message.transID];
		
		if (respTimer != null)
		{
		   clearInterval(respTimer);
		   delete respTimerMap[message.transID];
		}
		else
		{
			l('DEBUG') && console.log('3PCC.mqttClient - Received Message but could not find associated response timer');
		}
		
        try {
        	this.callback(message);
        } catch(e) {
          console.error('MqttClient Message callback chain failure:',e);
          console.log(e.stack);
        }
      }.bind(this));
	  
    client.on('connect', function(error) {
      //console.log('mqtt is CONNECTED');
      this.connected = true;
	  // Subscribe on unique ID to get the response back.
	  mqttClient.subscribe(this.id);
      this.emit('connected');
    }.bind(this));
    
	client.on('error', function(error) {
      console.log('DISCONNECTED - error: '+ error);
      this.connected = false;
      this.emit('disconnected', error);
    }.bind(this));
    
	client.on('close', function(error) {
      console.log('DISCONNECTED - close: '+error);
      this.connected = false;
      this.emit('disconnected',error);
    }.bind(this));
    return client;
  }
699401
function send(id) {
        if (msg.ack) { server._rememberAck(msg.ack, ws.broker_uuid); }

        var destWs = server.id2ws[id];
        if (destWs) {
            if (destWs.readyState === WebSocket.OPEN) {
                destWs.send(JSON.stringify({
                    action: 'message',
                    message: msg.message,
                    ack: msg.ack,
                    from: server.ws2id[ws.broker_uuid]
                }));
            } else {
                err = new Error('Unable to send message. Client "'+id+'" disconnected');
                server.emit('error', err);
            }
        } else {
            server.emit('warn', new Error('Unable to send message. Client "'+id+'" unknown'));
        }
    }
1333707
function connect() {
  console.log('Connecting client: ' + clientId + ' to url:"' + url + '"');
  client = mqtt.connect(url, { 'clientId': clientId });
}
376451
def connect(self):
        """"""
        if not self.connect_attempted:
            self.connect_attempted = True
            self.client.connect(self.host, port=self.port)
            self.client.loop_start()

            while not self.connected:
                log.info('waiting for MQTT connection...')
                time.sleep(1)
1025537
function MQTTMsgBusClientNode(config) {
        //console.log("MQTTMsgBusClientNode(): config = ", config)

        RED.nodes.createNode(this, config)

        this.domain     = "domain"
        this.platformId = "nodered"

        this.classType  = ClassType.ClassTypeControllerSvc
        this.nodename   = config.nodename
        this.broker     = config.broker
        this.brokerConn = RED.nodes.getNode(this.broker)

        var willMsg = statusMessage(this, MsgbusStatusDisconnected, 0)

        this.brokerConn.willTopic = willMsg.topic 
        this.brokerConn.options.will = {
            topic:   this.brokerConn.willTopic,
            payload: willMsg.msg,
            qos:     2,
            retain:  true
        }

        var birthMsg = statusMessage(this, MsgbusStatusOnline, 0)

        this.brokerConn.birthTopic = birthMsg.topic 
        this.brokerConn.birthMessage = {
            topic:   this.brokerConn.birthTopic,
            payload: birthMsg.msg,
            qos:     2,
            retain:  true
        }

        var node = this

        if (this.brokerConn) {
            //console.log("MQTTMsgBusClientNode(): node.brokerConn = ", node.brokerConn)
            node.brokerConn.register(node)
        } else {
            node.log(RED._("msgbus.errors.missing-config"))
        }

        this.on('close', function(done) {
            node.brokerConn.deregister(node, done)
        })
    }
59659
function connectNode (subscriptions, host, clientId) {
    // Create client
    var url = "tcp://" + host + ":1883";
    var client = mqtt_lib.connect(url, {clientId : clientId});
    // Register incoming message callback
    client.on('message', function(channel, message) {
        // Execute all the appropriate callbacks:
        // the ones specific to this channel with a single parameter (message)
        // the ones associated to a wildcard channel, with two parameters (message and channel)
        var cbs = findCallbacks(subscriptions, channel);
        if (cbs!==undefined) {
            cbs.forEach(function(cb) {
                if (Object.keys(subscriptions).indexOf(channel)!==-1) {
                    cb(message.toString());
                } else {
                    cb(message.toString(), channel);
                }
            });
        }
    });
    return client;
}
635411
public Client getClient() {
		if(transportClient != null)
			return ((TransportClientUtil)transportClient.getEventClientUtil(indexNameBuilder)).getClient();
		else
			return null;
	}
789243
@Override
	public void started(ServiceBroker broker) throws Exception {
		super.started(broker);

		// Local nodeID
		this.nodeID = broker.getNodeID();

		// Set components
		ServiceBrokerConfig cfg = broker.getConfig();
		this.executor = cfg.getExecutor();
		this.scheduler = cfg.getScheduler();
		this.strategyFactory = cfg.getStrategyFactory();
		this.contextFactory = cfg.getContextFactory();
		this.transporter = cfg.getTransporter();
		this.eventbus = cfg.getEventbus();
		this.uid = cfg.getUidGenerator();
	}
785904
public synchronized void register( String clientID ) throws InvalidClientIDException
    {
        if (!clientIDs.add(clientID))
        {
            log.error("Client ID already exists : "+clientID);
            throw new InvalidClientIDException("Client ID already exists : "+clientID);
        }
        log.debug("Registered clientID : "+clientID);
    }
1280799
function connectBrowser (subscriptions, backlog, host, done_cb, secure) {

    // Associate the right port
    var websocket_uri;
    if(secure == true) {
        websocket_uri ='wss://' + host + ':1885/mqtt';
    }
    else {
        websocket_uri ='ws://' + host + ':1884/mqtt';
    }

    // Create client
    var client = new mqtt_lib.Client(websocket_uri, generateRandomClientId());
    // Register callback for connection lost
    client.onConnectionLost = function() {
        // TODO try to reconnect
    };
    // Register callback for received message
    client.onMessageArrived = function (message) {
        // Execute all the appropriate callbacks:
        // the ones specific to this channel with a single parameter (message)
        // the ones associated to a wildcard channel, with two parameters (message and channel)
        var cbs = findCallbacks(subscriptions, message.destinationName);
        if (cbs!==undefined) {
            cbs.forEach(function(cb) {
                if (Object.keys(subscriptions).indexOf(message.destinationName)!==-1)
                    cb(message.payloadString);
                else
                    cb(message.payloadString, message.destinationName);
            });
        }
    };
    // Connect
    client.connect({onSuccess: function() {
        // Execute optional done callback passing true
        if (done_cb!==undefined)
            done_cb(true);
        // Execute the backlog of operations performed while the client wasn't connected
        backlog.forEach(function(e) {
            e.op.apply(this, e.params);
        });
    },
        onFailure: function() {
            // Execute optional done callback passing false
            if (done_cb!==undefined)
                done_cb(false);
            else
                console.error('There was a problem initializing nutella.');
        }});
    return client;
}
427589
def __on_connect(self, client, userdata, flags, result_code):
        # pylint: disable=W0613
        
        if result_code:
            # result_code != 0: something wrong happened
            _logger.error(
                "Error connecting the MQTT server: %s (%d)",
                paho.connack_string(result_code),
                result_code,
            )
        else:
            # Connection is OK: stop the reconnection timer
            self.__stop_timer()

        # Notify the caller, if any
        if self.on_connect is not None:
            try:
                self.on_connect(self, result_code)
            except Exception as ex:
                _logger.exception("Error notifying MQTT listener: %s", ex)
612581
public void setClientID(String clientID) {
        if (clientID == null || clientID.isEmpty()) {
            this.clientID = DEFAULT_CLIENT_ID;
            return;
        }
        this.clientID = clientID;
    }
186947
@Override
  public void channelInactive(ChannelHandlerContext ctx) {
    Status status = Status.UNAVAILABLE.withDescription(
        "Connection closed while performing protocol negotiation for " + ctx.pipeline().names());
    failWrites(status.asRuntimeException());
  }
693675
void initializeClientUnprotected(String host, int port, String sessionId)
    throws IOException {
    if (client != null) {
      return;
    }
    LOG.info("Creating JT client to " + host + ":" + port);
    long connectTimeout = RemoteJTProxy.getRemotJTTimeout(conf);
    int rpcTimeout = RemoteJTProxy.getRemoteJTRPCTimeout(conf);
    remoteJTAddr = new InetSocketAddress(host, port);
    client = RPC.waitForProtocolProxy(
      JobSubmissionProtocol.class,
      JobSubmissionProtocol.versionID,
      remoteJTAddr,
      conf,
      connectTimeout,
      rpcTimeout
      ).getProxy();
    remoteJTStatus = RemoteJTStatus.SUCCESS;
    remoteJTHost = host;
    remoteJTPort = port;
    remoteSessionId = sessionId;
    
    if (remoteJTState != null) {
      remoteJTState.setSessionId(sessionId);
    }
  }
411411
@Override
	public void started(ServiceBroker broker) throws Exception {
		super.started(broker);

		// Set components
		ServiceBrokerConfig cfg = broker.getConfig();
		this.transporter = cfg.getTransporter();
		this.monitor = cfg.getMonitor();
		
		// Set local nodeID
		this.localNodeID = broker.getNodeID();
	}