Java 类org.eclipse.paho.client.mqttv3.MqttConnectOptions 实例源码

项目:jim    文件:MqttClientFactory.java   
/**
 * get MqttClient by clientKey
 * @param clientKey
 * @return
 * @throws MqttException
 */
public static MqttClient getMqttClient(String serverURI, String clientId,StringRedisTemplate redisTemplate) 
                throws MqttException{
     String clientKey=serverURI.concat(clientId);
     if(clientMap.get(clientKey)==null){
         lock.lock();
             if(clientMap.get(clientKey)==null){
                 MqttClientPersistence persistence = new MemoryPersistence();

                 MqttClient client = new MqttClient(serverURI, clientId, persistence);
                 MqttConnectOptions connOpts = new MqttConnectOptions();

                 MqttCallback callback = new IMMqttCallBack(client,redisTemplate);
                 client.setCallback(callback);

                 connOpts.setCleanSession(true);
                 client.connect(connOpts);
                 clientMap.put(clientKey, client);
             }
          lock.unlock();
     }
      return clientMap.get(clientKey);
}
项目:iotplatform    文件:MqttPlugin.java   
@Override
public void init(MqttPluginConfiguration configuration) {
  retryInterval = configuration.getRetryInterval();

  mqttClientOptions = new MqttConnectOptions();
  mqttClientOptions.setCleanSession(false);
  mqttClientOptions.setMaxInflight(configuration.getMaxInFlight());
  mqttClientOptions.setAutomaticReconnect(true);
  String clientId = configuration.getClientId();
  if (StringUtils.isEmpty(clientId)) {
    clientId = UUID.randomUUID().toString();
  }
  if (!StringUtils.isEmpty(configuration.getAccessToken())) {
    mqttClientOptions.setUserName(configuration.getAccessToken());
  }
  try {
    mqttClient = new MqttAsyncClient("tcp://" + configuration.getHost() + ":" + configuration.getPort(), clientId);
  } catch (Exception e) {
    log.error("Failed to create mqtt client", e);
    throw new RuntimeException(e);
  }
  // connect();
}
项目:export-distro    文件:IotCoreMQTTSender.java   
private void connectClient() throws Exception {
    try {
        String mqttServerAddress = String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        connectOptions.setUserName(username);
        password = createJwt(projectId, privateKeyFile, algorithm);
        connectOptions.setPassword(password.toCharArray());

        connectOptions.setCleanSession(true);
        connectOptions.setKeepAliveInterval(keepAlive);

        client = new MqttClient(mqttServerAddress, clientId, new MemoryPersistence());
        client.setCallback(this);

        logger.debug("Connecting to broker:  " + mqttServerAddress);
        client.connect(connectOptions);
        logger.debug("Connected");

    } catch (Exception e) {
        logger.error("Failed to connect to MQTT client ( " + mqttBridgeHostname + ":" + mqttBridgePort + "/" + clientId + ") for outbound messages");
        throw e;
    }
}
项目:EMQ-Android-Toolkit    文件:Connection.java   
public MqttConnectOptions getMqttConnectOptions() {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(isCleanSession());
    options.setConnectionTimeout(getTimeout());
    options.setKeepAliveInterval(getKeepAlive());

    if (!getUsername().isEmpty()) {
        options.setUserName(getUsername());
    }

    if (!getPassword().isEmpty()) {
        options.setPassword(getPassword().toCharArray());
    }

    if (!getLwtTopic().isEmpty() && !getLwtPayload().isEmpty()) {
        options.setWill(getLwtTopic(), getLwtPayload().getBytes(), getLwtQos(), isLwtRetained());
    }

    return options;
}
项目:SerialMqttBridge    文件:MqttHandler.java   
/*********************************************************************************************************************************************************************
 *
 */
private void connectAndSubscribe() throws Exception {

  ConfigHandler configHandler = serialMqttBridge.getConfigHandler();

  mqttClient = new MqttClient(configHandler.getMqttBrokerUrl(), configHandler.getMqttClientId(), null);
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  connOpts.setAutomaticReconnect(true);

  // Authentication
  if (configHandler.getMqttBrokerUsername() != null && configHandler.getMqttBrokerPassword() != null) {
    connOpts.setUserName(configHandler.getMqttBrokerUsername());
    connOpts.setPassword(configHandler.getMqttBrokerPassword().toCharArray());
  }

  // MqttCallback
  mqttCallback = new MqttSubscriptionCallback(this);
  mqttClient.setCallback(mqttCallback);

  mqttClient.connect(connOpts);

  // Subscribe to defined inbound topic
  mqttClient.subscribe(configHandler.getMqttTopicSubscribe(), configHandler.getMqttQosSubscribe());
}
项目:Taxi-Datalogger    文件:MQTTPublisher.java   
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(cloudIotOptions.getBrokerUrl(),
        cloudIotOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(CloudIotOptions.UNUSED_ACCOUNT_NAME);

    // generate the jwt password
    options.setPassword(mqttAuth.createJwt(cloudIotOptions.getProjectId()));

    mqttClient.connect(options);
    mReady.set(true);
}
项目:device-mqtt    文件:OutgoingSender.java   
private void connectClient() {
  try {
    client = new MqttClient(broker, clientId);
    client.setCallback(this);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(user);
    connOpts.setPassword(password.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(OUTGOING_MQTT_KEEP_ALIVE);
    logger.debug("Connecting to broker:  " + broker);
    client.connect(connOpts);
    logger.debug("Connected");
  } catch (MqttException e) {
    logger.error("Failed to connect to MQTT client ( " + broker + "/" + clientId
        + ") for outbound messages");
    logger.error(e.getLocalizedMessage());
    e.printStackTrace();
  }
}
项目:device-mqtt    文件:CommandResponseListener.java   
private void startListening() {
  logger.debug("Starting listening for response traffic");
  try {
    String url =
        cmdrespMqttBrokerProtocol + "://" + cmdrespMqttBroker + ":" + cmdrespMqttBrokerPort;
    client = new MqttClient(url, cmdrespMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(cmdrespMqttUser);
    connOpts.setPassword(cmdrespMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(cmdrespMqttKeepAlive);
    logger.debug("Connecting to response message broker:  " + cmdrespMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to response message broker");
    client.setCallback(this);
    client.subscribe(cmdrespMqttTopic, cmdrespMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to response message queue.  "
        + "Unable to respond to command requests.");
    e.printStackTrace();
    client = null;
  }
}
项目:device-mqtt    文件:IncomingListener.java   
private void startListening() {
  logger.debug("Starting listening for incoming traffic");
  try {
    String url =
        incomingMqttBrokerProtocol + "://" + incomingMqttBroker + ":" + incomingMqttBrokerPort;
    client = new MqttClient(url, incomingMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(incomingMqttUser);
    connOpts.setPassword(incomingMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(incomingMqttKeepAlive);
    logger.debug("Connecting to incoming message broker:  " + incomingMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to incoming message broker");
    client.setCallback(this);
    client.subscribe(incomingMqttTopic, incomingMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to incoming message queue.");
    e.printStackTrace();
    client = null;
  }
}
项目:sensorhub-cloud-iot    文件:MQTTPublisher.java   
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(cloudIotOptions.getBrokerUrl(),
        cloudIotOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(CloudIotOptions.UNUSED_ACCOUNT_NAME);

    // generate the jwt password
    options.setPassword(mqttAuth.createJwt(cloudIotOptions.getProjectId()));

    mqttClient.connect(options);
    mReady.set(true);
}
项目:tetrad    文件:TetradMQTT.java   
private void connect() {
    logger.debug(MessageFormat.format("Connecting to {0} as {1}", mqttConfig.getBroker(), mqttConfig.getClientid()));
    try {
        mqttSession = new MqttAsyncClient(mqttConfig.getBroker(),
                mqttConfig.getClientid(),
                new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);

        mqttSession.connect(connOpts, new TetradMQTTConnectionListener(this));
    } catch (MqttException e) {
        logger.error(MessageFormat.format("Error connecting to {0} as {1}. Message: {2}, ReasonCode: {3}",
                mqttConfig.getBroker(),
                mqttConfig.getClientid(),
                e.getMessage(),
                e.getReasonCode()
        ));
        e.printStackTrace();
    }

}
项目:SerialMqttBridge    文件:MqttHandler.java   
/*********************************************************************************************************************************************************************
 *
 */
private void connectAndSubscribe() throws Exception {

  ConfigHandler configHandler = serialMqttBridge.getConfigHandler();

  mqttClient = new MqttClient(configHandler.getMqttBrokerUrl(), configHandler.getMqttClientId(), null);
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  connOpts.setAutomaticReconnect(true);

  // Authentication
  if (configHandler.getMqttBrokerUsername() != null && configHandler.getMqttBrokerPassword() != null) {
    connOpts.setUserName(configHandler.getMqttBrokerUsername());
    connOpts.setPassword(configHandler.getMqttBrokerPassword().toCharArray());
  }

  // MqttCallback
  mqttCallback = new MqttSubscriptionCallback(this);
  mqttClient.setCallback(mqttCallback);

  mqttClient.connect(connOpts);

  // Subscribe to defined inbound topic
  mqttClient.subscribe(configHandler.getMqttTopicSubscribe(), configHandler.getMqttQosSubscribe());
}
项目:aws-iot-device-sdk-java    文件:AwsIotMqttConnection.java   
private MqttConnectOptions buildMqttConnectOptions(AbstractAwsIotClient client, SocketFactory socketFactory) {
    MqttConnectOptions options = new MqttConnectOptions();

    options.setSocketFactory(socketFactory);
    options.setCleanSession(true);
    options.setConnectionTimeout(client.getConnectionTimeout() / 1000);
    options.setKeepAliveInterval(client.getKeepAliveInterval() / 1000);

    Set<String> serverUris = getServerUris();
    if (serverUris != null && !serverUris.isEmpty()) {
        String[] uriArray = new String[serverUris.size()];
        serverUris.toArray(uriArray);
        options.setServerURIs(uriArray);
    }

    if (client.getWillMessage() != null) {
        AWSIotMessage message = client.getWillMessage();

        options.setWill(message.getTopic(), message.getPayload(), message.getQos().getValue(), false);
    }

    return options;
}
项目:vertx-mqtt    文件:MqttServerConnectionTest.java   
@Test
public void refusedBadUsernamePassword(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setUserName("wrong_username");
    options.setPassword("wrong_password".toCharArray());
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_FAILED_AUTHENTICATION);
  }
}
项目:vertx-mqtt    文件:MqttServerConnectionTest.java   
@Test
public void refusedUnacceptableProtocolVersion(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    // trying the old 3.1
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION);
  }
}
项目:vertx-mqtt    文件:MqttServerConnectionTest.java   
@Test
public void refusedClientIdZeroBytes(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(false);
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "", persistence);
    client.connect(options);
    context.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
    context.assertNotNull(rejection);
  }
}
项目:vertx-mqtt    文件:MqttServerClientIdentifierTest.java   
@Test
public void testInvalidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "invalid-id-with-24-chars", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(false);

  } catch (MqttException ignore) {
    context.assertTrue(true);
  }
}
项目:vertx-mqtt    文件:MqttServerClientIdentifierTest.java   
@Test
public void testValidClientIdentifier(TestContext context) throws Exception {

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "id-madeof-23-characters", persistence);
  MqttConnectOptions options = new MqttConnectOptions();
  options.setMqttVersion(MQTT_VERSION_3_1);

  try {

    client.connect(options);
    context.assertTrue(true);

  } catch (MqttException ignore) {
    context.assertTrue(false);
  }
}
项目:HelloMQTT    文件:MQService.java   
/**
 * 服务初始化回调函数
 */
@Override
public void onCreate() {
    super.onCreate();

    /**创建一个Handler*/
    mConnHandler = new Handler();
    try {
        /**新建一个本地临时存储数据的目录,该目录存储将要发送到服务器的数据,直到数据被发送到服务器*/
        mDataStore = new MqttDefaultFilePersistence(getCacheDir().getAbsolutePath());
    } catch(Exception e) {
        e.printStackTrace();
        /**新建一个内存临时存储数据的目录*/
        mDataStore = null;
        mMemStore = new MemoryPersistence();
    }
    /**连接的参数选项*/
    mOpts = new MqttConnectOptions();
    /**删除以前的Session*/
    mOpts.setCleanSession(MQTT_CLEAN_SESSION);
    // Do not set keep alive interval on mOpts we keep track of it with alarm's
    /**定时器用来实现心跳*/
    mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    /**管理网络连接*/
    mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
}
项目:diozero    文件:ProtobufMqttProtocolHandler.java   
public ProtobufMqttProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
    super(deviceFactory);

    String mqtt_url = PropertyUtil.getProperty(MQTT_URL_PROP, null);
    if (mqtt_url == null) {
        throw new RuntimeIOException("Property '" + MQTT_URL_PROP + "' must be set");
    }

    try {
        mqttClient = new MqttClient(mqtt_url, MqttClient.generateClientId(), new MemoryPersistence());
        mqttClient.setCallback(this);
        MqttConnectOptions con_opts = new MqttConnectOptions();
        con_opts.setAutomaticReconnect(true);
        con_opts.setCleanSession(true);
        mqttClient.connect(con_opts);
        Logger.debug("Connected to {}", mqtt_url);

        // Subscribe
        Logger.debug("Subscribing to response and notification topics...");
        mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
        mqttClient.subscribe(MqttProviderConstants.GPIO_NOTIFICATION_TOPIC);
        Logger.debug("Subscribed");
    } catch (MqttException e) {
        throw new RuntimeIOException(e);
    }
}
项目:diozero    文件:MqttTestClient.java   
public MqttTestClient(String mqttUrl) throws MqttException {
    mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence());
    mqttClient.setCallback(this);
    MqttConnectOptions con_opts = new MqttConnectOptions();
    con_opts.setAutomaticReconnect(true);
    con_opts.setCleanSession(true);
    mqttClient.connect(con_opts);
    Logger.debug("Connected to {}", mqttUrl);

    lock = new ReentrantLock();
    conditions = new HashMap<>();
    responses = new HashMap<>();

    // Subscribe
    Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC);
    mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
    Logger.debug("Subscribed");
}
项目:IoT    文件:MyMqttCloudClient.java   
public MyMqttCloudClient(String cloudBrokerAddress, String clientId) {
//      this._cloudTopic = cloudTopic;
        this._cloudBrokerAddress = cloudBrokerAddress;
        this._clientId = clientId;
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            this._mqCloudClient = new MqttClient(this._cloudBrokerAddress,
                    this._clientId, persistence);
            this._mqCloudClient.setCallback(this);
            MqttConnectOptions connOpts = new MqttConnectOptions();
//          connOpts.setCleanSession(true);
            connOpts.setConnectionTimeout(0);
            connOpts.setKeepAliveInterval(30);
            connOpts.setAutomaticReconnect(true);
            System.out.println("Connecting to cloud broker: " + this._cloudBrokerAddress);
            this._mqCloudClient.connect(connOpts);
            System.out.println("Connected");            
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
项目:IoT    文件:CopyOfMyMqttCloudClient.java   
public CopyOfMyMqttCloudClient(String cloudTopic, String cloudBrokerAddress, String clientId) {
        this._cloudTopic = cloudTopic;
        this._cloudBrokerAddress = cloudBrokerAddress;
        this._clientId = clientId;
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            this._mqCloudClient = new MqttClient(this._cloudBrokerAddress,
                    "sfdf", persistence);
            this._mqCloudClient.setCallback(this);
            MqttConnectOptions connOpts = new MqttConnectOptions();
//          connOpts.setCleanSession(true);
            connOpts.setKeepAliveInterval(30);
            System.out.println("Connecting to cloud broker: " + this._cloudBrokerAddress);
            this._mqCloudClient.connect(connOpts);
            System.out.println("Connected");            
        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }
项目:android-app    文件:MQTTClient.java   
/**
 *
 *
 */
private void connect() throws MqttException {
    connOpt = new MqttConnectOptions();

    connOpt.setCleanSession(true);
    connOpt.setKeepAliveInterval(3600);
    connOpt.setConnectionTimeout(3600);
    connOpt.setUserName(sharedPref.getString("pref_username", ""));
    connOpt.setPassword(sharedPref.getString("pref_password", "").toCharArray());

    String tmpDir = createTempDir().getPath(); //System.getProperty("java.io.tmpdir");
    Log.i(TAG, "Persistence will be done in " + tmpDir);

    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);

    // Connect to Broker
    mClient = new MqttClient(sharedPref.getString("pref_url", "") + ":" + sharedPref.getString("pref_port", "1883"), android_id + "_client", dataStore);
    mClient.setCallback(this);
    mClient.connect(connOpt);
    Log.i(TAG, "Connected to " + sharedPref.getString("pref_url", ""));

}
项目:Sparkplug    文件:MainActivity.java   
private MqttConnectOptions optionsFromModel(ConnectionModel model){

        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(model.isCleanSession());
        connOpts.setConnectionTimeout(model.getTimeout());
        connOpts.setKeepAliveInterval(model.getKeepAlive());
        if(!model.getUsername().equals(ActivityConstants.empty)){
            connOpts.setUserName(model.getUsername());
        }

        if(!model.getPassword().equals(ActivityConstants.empty)){
            connOpts.setPassword(model.getPassword().toCharArray());
        }
        /*
        if(!model.getLwtTopic().equals(ActivityConstants.empty) && !model.getLwtMessage().equals(ActivityConstants.empty)){
            connOpts.setWill(model.getLwtTopic(), model.getLwtMessage().getBytes(), model.getLwtQos(), model.isLwtRetain());
        }*/
        //   if(tlsConnection){
        //       // TODO Add Keys to conOpts here
        //       //connOpts.setSocketFactory();
        //   }
        return connOpts;
    }
项目:Sparkplug    文件:MainActivity.java   
public void connect(Connection connection) {
    String[] actionArgs = new String[1];
    actionArgs[0] = connection.getId();
    final ActionListener callback = new ActionListener(this,
            ActionListener.Action.CONNECT, connection, actionArgs);
    connection.getClient().setCallback(new MqttCallbackHandler(this, connection.handle()));
    try {
        MqttConnectOptions mqttConnectOptions = connection.getConnectionOptions();
        SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
        deathPayload = connection.addBdSeqNum(deathPayload);
        byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());
        String lwtTopic = "spBv1.0/" + connection.getGroupId() + "/NDEATH/" + connection.getEdgeNodeId();
        Log.d(TAG, "1. Setting up LWT: " + lwtTopic);
        mqttConnectOptions.setWill(lwtTopic, deathBytes, 0, false);

        connection.getClient().connect(mqttConnectOptions, null, callback);
    }
    catch (Exception e) {
        Log.e(this.getClass().getCanonicalName(),
                "Exception occurred", e);
    }
}
项目:Sparkplug    文件:SparkplugListener.java   
public void run() {
    try {
        // Connect to the MQTT Server
        MqttConnectOptions options = new MqttConnectOptions();
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(30);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        client = new MqttClient(serverUrl, clientId);
        client.setTimeToWait(5000);                     // short timeout on failure to connect
        client.connect(options);
        client.setCallback(this);

        // Just listen to all DDATA messages on spAv1.0 topics and wait for inbound messages
        client.subscribe("spBv1.0/#", 0);
    } catch(Exception e) {
        e.printStackTrace();
    }
}
项目:product-ei    文件:MQTTTestClient.java   
/**
 * Generate a MQTT client with given parameters
 *
 * @param brokerURL url of MQTT provider
 * @param userName username to connect to MQTT provider
 * @param password password to connect to MQTT provider
 * @param clientId unique id for the publisher/subscriber client
 * @throws MqttException in case of issue of connect/publish/consume
 */
public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException {
    this.brokerURL = brokerURL;
    //Store messages until server fetches them
    MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId);
    mqttClient = new MqttClient(brokerURL, clientId, dataStore);
    SimpleMQTTCallback callback = new SimpleMQTTCallback();
    mqttClient.setCallback(callback);
    MqttConnectOptions connectOptions = new MqttConnectOptions();
    connectOptions.setUserName(userName);
    connectOptions.setPassword(password);
    connectOptions.setCleanSession(true);
    mqttClient.connect(connectOptions);

    log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL);
}
项目:ActiveMQ-MQTT-Android    文件:MainActivity.java   
private void startConnect(String clientID, String serverIP, String port) {
    //服务器地址
    String  uri ="tcp://";
    uri=uri+serverIP+":"+port;
    Log.d("MainActivity",uri+"  "+clientID);
    /**
     * 连接的选项
     */
    MqttConnectOptions conOpt = new MqttConnectOptions();
    /**设计连接超时时间*/
    conOpt.setConnectionTimeout(3000);
    /**设计心跳间隔时间300秒*/
    conOpt.setKeepAliveInterval(300);
    /**
     * 创建连接对象
     */
     client = new MqttAndroidClient(this,uri, clientID);
    /**
     * 连接后设计一个回调
     */
    client.setCallback(new MqttCallbackHandler(this, clientID));
    /**
     * 开始连接服务器,参数:ConnectionOptions,  IMqttActionListener
     */
    try {
        client.connect(conOpt, null, new ConnectCallBackHandler(this));
    } catch (MqttException e) {
        e.printStackTrace();
    }

}
项目:AppInventorRaspberryPiCompanion    文件:InputPinHandler.java   
public InputPinHandler() {
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  try {
    mClient = new MqttClient(PropertyUtil.getMqttAddress(), MqttClient.generateClientId(), new MemoryPersistence());
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connecting to broker " + PropertyUtil.getMqttAddress() + "...");
    }
    mClient.connect(connOpts);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connected to broker " + PropertyUtil.getMqttAddress() + ".");
    }
  } catch (MqttException e) {
    LOGGER.error(e.getMessage(), e);
  }
}
项目:mqtt-listener-example    文件:Ingestion.java   
public void init() throws MqttException {
    try {
        String url = mqttProperties.getHostname() + ":" + mqttProperties.getPort();
        LOGGER.info("Opening MQTT connection: '{}'", url);
        LOGGER.info("properties: {}", mqttProperties);
        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setUserName(mqttProperties.getUsername());
        connectOptions.setPassword(mqttProperties.getPassword().toCharArray());
        connectOptions.setCleanSession(false);
        client = new MqttClient(url, mqttProperties.getClientName(), new MemoryPersistence());
        client.setCallback(onMessageArrived);
        client.connect(connectOptions);
        client.subscribe(mqttProperties.getTopic());
    } catch (MqttException e) {
        LOGGER.error(e.getMessage(), e);
        throw e;
    }
}
项目:iot-edge-greengrass    文件:MqttGatewayService.java   
@PostConstruct
public void init() throws Exception {
    scheduler = Executors.newSingleThreadScheduledExecutor();

    tbClientOptions = new MqttConnectOptions();
    tbClientOptions.setCleanSession(false);
    tbClientOptions.setMaxInflight(connection.getMaxInFlight());
    tbClientOptions.setAutomaticReconnect(true);

    MqttGatewaySecurityConfiguration security = connection.getSecurity();
    security.setupSecurityOptions(tbClientOptions);

    tbClient = new MqttAsyncClient((security.isSsl() ? "ssl" : "tcp") + "://" + connection.getHost() + ":" + connection.getPort(),
            security.getClientId(), persistence.getPersistence());
    tbClient.setCallback(this);

    if (persistence.getBufferSize() > 0) {
        DisconnectedBufferOptions options = new DisconnectedBufferOptions();
        options.setBufferSize(persistence.getBufferSize());
        options.setBufferEnabled(true);
        options.setPersistBuffer(true);
        tbClient.setBufferOpts(options);
    }
    connect();

    scheduler.scheduleAtFixedRate(this::reportStats, 0, reporting.getInterval(), TimeUnit.MILLISECONDS);
}
项目:iot-edge-greengrass    文件:MqttBrokerMonitor.java   
public void connect() {
    try {
        client = new MqttAsyncClient((configuration.isSsl() ? "ssl" : "tcp") + "://" + configuration.getHost() + ":" + configuration.getPort(),
                getClientId(), new MemoryPersistence());
        client.setCallback(this);
        clientOptions = new MqttConnectOptions();
        clientOptions.setCleanSession(true);
        if (configuration.isSsl() && !StringUtils.isEmpty(configuration.getTruststore())) {
            Properties sslProperties = new Properties();
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, configuration.getTruststore());
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, configuration.getTruststorePassword());
            sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS");
            sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, false);
            clientOptions.setSSLProperties(sslProperties);
        }
        configuration.getCredentials().configure(clientOptions);
        checkConnection();
        if (configuration.getAttributeUpdates() != null) {
            configuration.getAttributeUpdates().forEach(mapping ->
                    gateway.subscribe(new AttributesUpdateSubscription(mapping.getDeviceNameFilter(), this))
            );
        }
        if (configuration.getServerSideRpc() != null) {
            configuration.getServerSideRpc().forEach(mapping ->
                    gateway.subscribe(new RpcCommandSubscription(mapping.getDeviceNameFilter(), this))
            );
        }
    } catch (MqttException e) {
        log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
        throw new RuntimeException("MQTT broker connection failed!", e);
    }
}
项目:iot-edge-greengrass    文件:BasicCredentials.java   
@Override
public void configure(MqttConnectOptions clientOptions) {
  clientOptions.setUserName(username);
  if (!StringUtils.isEmpty(password)) {
    clientOptions.setPassword(password.toCharArray());
  }
}
项目:echo    文件:MQTTPublisher.java   
public static void main(String args[]) {
    String topic = "iot/iot";
    String content = "Hello ith";
    int qos = 2;
    String broker = "tcp://127.0.0.1:1883";
    String clientId = "sample";
    MemoryPersistence persistence = new MemoryPersistence();

    try {
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        System.out.println("Connecting to broker");
        sampleClient.connect(connOpts);
        System.out.println("connected");
        System.out.println("Publishing meessage: " + content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        System.out.println("Message published");
        sampleClient.disconnect();
        System.out.println("Disconnected");
        System.exit(0);
    } catch (MqttException e){
        System.out.println("reason " + e.getReasonCode());
        System.out.println("msg " + e.getMessage());
        System.out.println("loc " + e.getLocalizedMessage());
        System.out.println("cause " + e.getCause());
        System.out.println("exxcep " + e);
    }

}
项目:echo    文件:NifiDeployer.java   
public DataflowInput deployDag(Map<Processor, Device> placementMap,
                               DataflowInput input) {

    this.processorMapping = placementMap;
    for (Map.Entry<Processor, Device> entry : this.processorMapping.entrySet()) {
        System.out.println(entry.getValue().getDeviceIP());
    }

    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setCleanSession(true);
    try {
        mqttClient.connect();

        populateMaps(input.getWiring(), placementMap);

        createProcessorsPortsAndRPGs();
        createConnections();
        startAllPorts();
        createRemoteConnections();
        startAllProcessors();

        mqttClient.disconnect();
    } catch (MqttException e) {
        e.printStackTrace();
    }
    return input;
}
项目:thingsboard-gateway    文件:BasicCredentials.java   
@Override
public void configure(MqttConnectOptions clientOptions) {
    clientOptions.setUserName(username);
    if (!StringUtils.isEmpty(password)) {
        clientOptions.setPassword(password.toCharArray());
    }
}
项目:mqttserver    文件:PubWebMessage.java   
public static void pubMsg(String tcpUrl, String clientId, String topicName,
            String message) throws MqttException, UnsupportedEncodingException {
        MqttClient client = new MqttClient(tcpUrl, clientId);
        MqttConnectOptions mqcConf = new MqttConnectOptions();
        mqcConf.setConnectionTimeout(300);
        mqcConf.setKeepAliveInterval(1200);
        client.connect(mqcConf);

        MqttTopic topic = client.getTopic(topicName);
        topic.publish(message.getBytes("utf8"), 1, false);

//      client.close();
    }
项目:mqttserver    文件:SubscribeMessage.java   
public void doDemo(String tcpUrl, String clientId, String topicName) {
    try {
      MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
      mqttConnectOptions.setMqttVersion(4);
        client = new MqttClient(tcpUrl, clientId);
        client.connect(mqttConnectOptions);
        client.setCallback(this);
        client.subscribe(topicName);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
项目:mqttserver    文件:PubMessage.java   
public static void pubMsg(String tcpUrl, String clientId, String topicName)
    throws MqttException, UnsupportedEncodingException {
  MqttClient client = new MqttClient(tcpUrl, clientId);
  MqttConnectOptions mqcConf = new MqttConnectOptions();
  mqcConf.setConnectionTimeout(300);
  mqcConf.setKeepAliveInterval(1200);
  client.connect(mqcConf);

  MqttTopic topic = client.getTopic(topicName);
  for (int i = 0; i < 10; i++) {
    String message = "{\"id\":" + (i+1) + ",\"temp\":12}";
    topic.publish(message.getBytes("utf8"), 1, false);
  }
  client.disconnect();
}