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

项目: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);
}
项目: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;
    }
}
项目: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());
}
项目:nCube-Thyme-Java    文件:MqttClientKetiSub.java   
public MqttClientKetiSub(String serverUrl) {

    this.mqttServerUrl = serverUrl;

    System.out.println("[KETI MQTT Client] Client Initialize");

    try {
        mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);

        while(!mqc.isConnected()){
            mqc.connect();
            System.out.println("[KETI MQTT Client] Connection try");
        }

        System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
项目:nCube-Thyme-Java    文件:MqttClientKetiSub.java   
public MqttClientKetiSub(String serverUrl, String aeId) {

    this.mqttServerUrl = serverUrl;
    this.aeId = aeId;
    this.mqttClientId = MqttClient.generateClientId()+"K";

    System.out.println("[KETI MQTT Client] Client Initialize");

    try {
        mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);

        while(!mqc.isConnected()){
            mqc.connect();
            System.out.println("[KETI MQTT Client] Connection try");
        }

        System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
项目:nCube-Thyme-Java    文件:MqttClientKetiPub.java   
public MqttClientKetiPub(String serverUrl) {

    this.mqttServerUrl = serverUrl;

    System.out.println("[KETI MQTT Client] Client Initialize");

    try {
        mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);

        while(!mqc.isConnected()){
            mqc.connect();
            System.out.println("[KETI MQTT Client] Connection try");
        }

        System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
项目:nCube-Thyme-Java    文件:MqttClientKetiPub.java   
public MqttClientKetiPub(String serverUrl, String aeId) {

    this.mqttServerUrl = serverUrl;
    this.aeId = aeId;
    this.mqttClientId = MqttClient.generateClientId()+"K";

    System.out.println("[KETI MQTT Client] Client Initialize");

    try {
        mqc = new MqttClient(mqttServerUrl, mqttClientId, persistence);

        while(!mqc.isConnected()){
            mqc.connect();
            System.out.println("[KETI MQTT Client] Connection try");
        }

        System.out.println("[KETI MQTT Client] Connected to Server - " + mqttServerUrl);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}
项目: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;
  }
}
项目:reactive-components    文件:MqttTest.java   
@Test
public void testMQtt() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);
    MqttClient client = new MqttClient("tcp://localhost:" + MQTT_PORT, MqttClient.generateClientId(), new MemoryPersistence());
    client.connect();
    MqttComponent mqtt = new MqttComponent();
    mqtt.client = client;
    Publisher<byte[]> fromTopic = mqtt.from("input", byte[].class);
    Subscriber<byte[]> toTopic = mqtt.to("output", byte[].class);
    Flux.from(fromTopic)
        .log()
        .subscribe(toTopic);

    client.subscribe("output", (topic, message) -> {
        result = new Integer(new String(message.getPayload()));
        latch.countDown();
    });
    client.publish("input", new MqttMessage(new Integer(2).toString().getBytes()));
    client.publish("input", new MqttMessage(new Integer(2).toString().getBytes()));
    latch.await(100, TimeUnit.SECONDS);
    Assert.assertEquals(2, result, 0.1);
    client.disconnect();
    client.close();
}
项目: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);
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void connectPublish(final String userKeyString, final String deviceKeyString, final String status) {

        try {
            final MqttClient client = connect();
            if (client == null || !client.isConnected()) {
                return;
            }
            MqttMessage message = new MqttMessage();
            message.setRetained(false);
            message.setPayload((userKeyString + "," + deviceKeyString + "," + status).getBytes());
            Utils.printLog(context,TAG, "UserKeyString,DeviceKeyString,status:" + userKeyString + "," + deviceKeyString + "," + status);
            message.setQos(0);
            client.publish(STATUS, message);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void subscribe() {
    if (!Utils.isInternetAvailable(context)) {
        return;
    }
    final String deviceKeyString = MobiComUserPreference.getInstance(context).getDeviceKeyString();
    final String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString();
    if (TextUtils.isEmpty(deviceKeyString) || TextUtils.isEmpty(userKeyString)) {
        return;
    }
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        connectPublish(userKeyString, deviceKeyString, "1");
        subscribeToConversation();
        if (client != null) {
            client.setCallback(ApplozicMqttService.this);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + userId, message);
        Utils.printLog(context,TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void unSubscribeToTypingTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        } else {
            MobiComUserPreference mobiComUserPreference = MobiComUserPreference.getInstance(context);
            currentId = mobiComUserPreference.getUserId();
        }

        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }

        client.unsubscribe("typing-" + getApplicationKey(context) + "-" + currentId);
        Utils.printLog(context,TAG, "UnSubscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + currentId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void subscribe() {
    if (!Utils.isInternetAvailable(context)) {
        return;
    }
    final String deviceKeyString = MobiComUserPreference.getInstance(context).getDeviceKeyString();
    final String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString();
    if (TextUtils.isEmpty(deviceKeyString) || TextUtils.isEmpty(userKeyString)) {
        return;
    }
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        connectPublish(userKeyString, deviceKeyString, "1");
        subscribeToConversation();
        if (client != null) {
            client.setCallback(ApplozicMqttService.this);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void publishTopic(final String applicationId, final String status, final String loggedInUserId, final String userId) {
    try {
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }
        MqttMessage message = new MqttMessage();
        message.setRetained(false);
        message.setPayload((applicationId + "," + loggedInUserId + "," + status).getBytes());
        message.setQos(0);
        client.publish("typing" + "-" + applicationId + "-" + userId, message);
        Utils.printLog(context, TAG, "Published " + new String(message.getPayload()) + " to topic: " + "typing" + "-" + applicationId + "-" + userId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void subscribeToTypingTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        } else {
            MobiComUserPreference mobiComUserPreference = MobiComUserPreference.getInstance(context);
            currentId = mobiComUserPreference.getUserId();
        }

        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }

        client.subscribe("typing-" + getApplicationKey(context) + "-" + currentId, 0);
        Utils.printLog(context, TAG, "Subscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + currentId);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Applozic-Android-Chat-Sample    文件:ApplozicMqttService.java   
public synchronized void unSubscribeToTypingTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        } else {
            MobiComUserPreference mobiComUserPreference = MobiComUserPreference.getInstance(context);
            currentId = mobiComUserPreference.getUserId();
        }

        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }

        client.unsubscribe("typing-" + getApplicationKey(context) + "-" + currentId);
        Utils.printLog(context, TAG, "UnSubscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + currentId);
    } catch (Exception e) {
        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());
}
项目:iot-device-bosch-indego-controller    文件:MqttIndegoAdapter.java   
/**
 * This marks the Indego device as offline.
 * 
 * @param mqttClient the connection to use
 * @throws MqttPersistenceException
 * @throws MqttException
 */
private void pushMqttStateOffline (MqttClient mqttClient) throws MqttPersistenceException, MqttException
{
    LOG.info("Pushing offline state to MQTT");

    publish(mqttClient, MQTT_TOPIC_ONLINE, false, true);
    publish(mqttClient, MQTT_TOPIC_STATE_CODE, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_STATE_MESSAGE, "", RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_ERROR_CODE, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_STATE_LEVEL, -2, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MOWED_PERCENTAGE, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MAP_SVG_CACHE_TS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MAP_UPDATE_AVAILABLE, false, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_MOWED_TS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_TOTAL_OPERATE_MINS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_TOTAL_CHARGE_MINS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_SESSION_OPERATE_MINS, 0, RETAINMENT);
    publish(mqttClient, MQTT_TOPIC_RUNTIME_SESSION_CHARGE_MINS, 0, RETAINMENT);
}
项目:vertx-mqtt    文件:MqttServerEndpointStatusTest.java   
@Test
public void disconnectedByClient(TestContext context) {

  Async async = context.async();

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    client.disconnect();

    // give more time to the MqttClient to update its connection state
    this.vertx.setTimer(1000, t1 -> {
      async.complete();
    });

    async.await();

    context.assertTrue(!client.isConnected() && !this.endpoint.isConnected());

  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
项目:enmasse    文件:SubscribeTest.java   
@Test
public void subscribe(TestContext context) {

    try {

        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), SUBSCRIBER_ID, persistence);
        client.connect();

        String[] topics = new String[]{ MQTT_TOPIC };
        int[] qos = new int[]{ 1 };
        // after calling subscribe, the qos is replaced with granted QoS that should be the same
        client.subscribe(topics, qos);

        context.assertTrue(qos[0] == 1);

    } catch (MqttException e) {

        context.assertTrue(false);
        e.printStackTrace();
    }

}
项目: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 connectionAlreadyAccepted(TestContext context) throws Exception {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED;

  MemoryPersistence persistence = new MemoryPersistence();
  MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
  client.connect();

  try {
    // try to accept a connection already accepted
    this.endpoint.accept(false);
    context.fail();
  } catch (IllegalStateException e) {
    // Ok
  }
}
项目: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);
  }
}
项目:vertx-mqtt    文件:MqttServerSubscribeTest.java   
private void subscribe(TestContext context, String topic, int expectedQos) {

    this.async = context.async();

    try {
      MemoryPersistence persistence = new MemoryPersistence();
      MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
      client.connect();

      String[] topics = new String[]{topic};
      int[] qos = new int[]{expectedQos};
      // after calling subscribe, the qos is replaced with granted QoS that should be the same
      client.subscribe(topics, qos);

      this.async.await();

      context.assertTrue(qos[0] == expectedQos);

    } catch (MqttException e) {

      context.assertTrue(!topic.equals(MQTT_TOPIC_FAILURE) ? false : true);
      e.printStackTrace();
    }
  }
项目: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;
    }
}
项目: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();
        }
    }
项目:enmasse    文件:DisconnectionTest.java   
private void mqttReceiver(TestContext context, String topic, int qos) {

        try {

            MemoryPersistence persistence = new MemoryPersistence();
            MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), CLIENT_ID, persistence);
            client.connect();

            client.subscribe(topic, qos, (t, m) -> {

                LOG.info("topic: {}, message: {}", t, m);
                this.async.complete();
            });

        } catch (MqttException e) {

            context.assertTrue(false);
            e.printStackTrace();
        }
    }
项目:enmasse    文件:SslTest.java   
private void mqttReceiver(TestContext context, String topic, int qos) {

        try {

            MemoryPersistence persistence = new MemoryPersistence();
            MqttClient client = new MqttClient(String.format("ssl://%s:%d", MQTT_BIND_ADDRESS, MQTT_TLS_LISTEN_PORT), SUBSCRIBER_ID, persistence);
            client.connect();

            client.subscribe(topic, qos, (t, m) -> {

                LOG.info("topic: {}, message: {}", t, m);
                this.async.complete();
            });

        } catch (MqttException e) {

            context.assertTrue(false);
            e.printStackTrace();
        }
    }
项目:jim    文件:MqttPerformanceClient.java   
/**
 * init Mqtt Client
 * @param mqtt_connect_count is connect size
 */
private void initMqttClient(String preClientID,long offset,long mqtt_connect_count,String topics[]) {
    logger.info("MqttPerformanceClient.performanceTestRun() starting");
    long end = offset+mqtt_connect_count;
    for (long i = offset; i < end; i++) {
        try {
            MqttClient client = getMqttClient(preClientID + i);
            client.subscribe(topics);
            clientMap.put(preClientID + i, client);
            logger.info("connected by ID :"+preClientID + i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    logger.info("MqttPerformanceClient.performanceTestRun() end");
}
项目: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", ""));

}
项目:mqtt-liferay-plugins    文件:MqttLocalServiceImpl.java   
private void _notifyEvent(MqttClient client, String event, Throwable e) {

        Message mb = new Message();

        mb.put("event", event);

        if (client != null) {
            mb.put("brokerUrl", client.getServerURI());
        }

        if (e != null) {
            mb.put("error", e.getMessage());
        }

        MessageBusUtil.sendMessage(
            PortletPropsValues.MQTT_EVENTS_DESTINATION, mb);
    }