org.eclipse.paho.client.mqttv3.MqttClient Java Examples

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 7 votes vote down vote up
@Before
public void before() throws Exception {
    log.info("=============================={}.{}==============================",
            this.getClass().getSimpleName(),
            this.testName.getMethodName());

    String clientId = UUID.randomUUID().toString();

    this.cleanupOptions = new MqttConnectOptions();
    this.cleanupOptions.setConnectionTimeout(this.actionTimeout);
    this.cleanupOptions.setKeepAliveInterval(this.actionTimeout);
    this.cleanupOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    this.cleanupOptions.setCleanSession(true);

    this.persistOptions = new MqttConnectOptions();
    this.persistOptions.setConnectionTimeout(this.actionTimeout);
    this.persistOptions.setKeepAliveInterval(this.actionTimeout);
    this.persistOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    this.persistOptions.setCleanSession(false);

    this.mqttClient = new MqttClient(this.url, clientId, null);
    this.mqttClient.connect(this.cleanupOptions);
}
 
Example #2
Source File: MqttTopicConnector.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
/**
 * Create MQTT client object with required configuration.
 */
@Override
public void create() {

    try {
        String mqttUrl = System.getProperty("mqtturl");
        if (StringUtils.isBlank(mqttUrl)) {
            mqttUrl = MessagingConstants.MQTT_PROPERTIES.getProperty("mqtturl", MessagingConstants.MQTT_URL_DEFAULT);
        }
        MemoryPersistence memoryPersistence = new MemoryPersistence();
        String clientId = MessagingUtil.getRandomString(23);
        mqttClient = new MqttClient(mqttUrl, clientId, memoryPersistence);
        if (log.isDebugEnabled()) {
            log.debug("MQTT client created: [client-id] " + clientId);
        }
    } catch (Exception e) {
        String message = "Could not create MQTT client";
        log.error(message, e);
        throw new MessagingException(message, e);
    }
}
 
Example #3
Source File: MqttTestClient.java    From diozero with MIT License 6 votes vote down vote up
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");
}
 
Example #4
Source File: ProtobufMqttProtocolHandler.java    From diozero with MIT License 6 votes vote down vote up
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);
	}
}
 
Example #5
Source File: MqttService.java    From PresencePublisher with MIT License 6 votes vote down vote up
public void sendMessages(List<Message> messages) throws MqttException {
    HyperLog.i(TAG, "Sending " + messages.size() + " messages to server");
    boolean tls = sharedPreferences.getBoolean(USE_TLS, false);
    String clientCertAlias = sharedPreferences.getString(CLIENT_CERTIFICATE, null);
    String login = sharedPreferences.getString(USERNAME, "");
    String password = securePreferences.getString(PASSWORD, "");

    MqttClient mqttClient = new MqttClient(getMqttUrl(tls), Settings.Secure.ANDROID_ID, new MemoryPersistence());
    MqttConnectOptions options = new MqttConnectOptions();
    options.setConnectionTimeout(5);
    if (!login.isEmpty() && !password.isEmpty()) {
        options.setUserName(login);
        options.setPassword(password.toCharArray());
    }
    if (tls) {
        options.setSocketFactory(factory.getSslSocketFactory(clientCertAlias));
    }
    mqttClient.connect(options);
    for (Message message : messages) {
        mqttClient.publish(message.getTopic(), message.getContent().getBytes(Charset.forName("UTF-8")), 1, false);
    }
    mqttClient.disconnect(5);
    mqttClient.close(true);
    HyperLog.i(TAG, "Sending messages was successful");
}
 
Example #6
Source File: MQTTTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testWill() {
    try {
        String clientId = UUID.randomUUID().toString();
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);

        MqttConnectOptions connectOptions = new MqttConnectOptions();
        connectOptions.setConnectionTimeout(this.actionTimeout);
        connectOptions.setKeepAliveInterval(this.actionTimeout);
        connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        connectOptions.setWill(this.topicName, this.content.getBytes(), 1, false);
        connectOptions.setCleanSession(true);
        mqttClient.connect(this.cleanupOptions);
        mqttClient.disconnect();

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #7
Source File: MqttBrokerConnection.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Create a new MQTT client connection to a server with the given protocol, host and port.
 *
 * @param protocol The transport protocol
 * @param host A host name or address
 * @param port A port or null to select the default port for a secure or insecure connection
 * @param secure A secure connection
 * @param clientId Client id. Each client on a MQTT server has a unique client id. Sometimes client ids are
 *            used for access restriction implementations.
 *            If none is specified, a default is generated. The client id cannot be longer than 65535
 *            characters.
 * @throws IllegalArgumentException If the client id or port is not valid.
 */
public MqttBrokerConnection(Protocol protocol, String host, @Nullable Integer port, boolean secure,
        @Nullable String clientId) {
    this.protocol = protocol;
    this.host = host;
    this.secure = secure;
    String newClientID = clientId;
    if (newClientID == null) {
        newClientID = MqttClient.generateClientId();
    } else if (newClientID.length() > 65535) {
        throw new IllegalArgumentException("Client ID cannot be longer than 65535 characters");
    }
    if (port != null && (port <= 0 || port > 65535)) {
        throw new IllegalArgumentException("Port is not within a valid range");
    }
    this.port = port != null ? port : (secure ? 8883 : 1883);
    this.clientId = newClientID;
    setReconnectStrategy(new PeriodicReconnectStrategy());
    connectionCallback = new ConnectionCallback(this);
}
 
Example #8
Source File: MqttPahoClient.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void shutdown() {
    if (shutdown.get()) {
        return;
    }
    shutdown.set(true);
    logger.info("{}: Attempting to shutdown connection.", clientInformation);
    long stamp = mqttClientLock.writeLock();
    try {
        if (mqttClient != null) {
            final boolean forcibly = false;
            MqttClient clientToDisconnect = mqttClient;
            mqttClient = null;
            disconnect(clientToDisconnect, forcibly);
        }
    } finally {
        mqttClientLock.unlockWrite(stamp);
    }
}
 
Example #9
Source File: SparkplugListener.java    From Sparkplug with Eclipse Public License 1.0 6 votes vote down vote up
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();
	}
}
 
Example #10
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnect31() {
    try {
        // client id must less then 23 bytes in 3.1
        String clientId = UUID.randomUUID().toString().split("-")[0];
        MqttClient mqttClient = new MqttClient(this.url, clientId, null);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setConnectionTimeout(this.actionTimeout);
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1);
        mqttClient.connect(connOpts);

        Assert.assertTrue(true);
    } catch (MqttException e) {
        log.error("exception", e);
        Assert.fail();
    }
}
 
Example #11
Source File: MQTTOverWebSocketTest.java    From WeEvent with Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws Exception {
    log.info("=============================={}.{}==============================",
            this.getClass().getSimpleName(),
            this.testName.getMethodName());

    this.url = "ws://localhost:" + this.listenPort + "/weevent-broker/mqtt";

    String clientId = UUID.randomUUID().toString();

    this.cleanupOptions = new MqttConnectOptions();
    this.cleanupOptions.setConnectionTimeout(this.actionTimeout);
    this.cleanupOptions.setKeepAliveInterval(this.actionTimeout);
    this.cleanupOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    this.cleanupOptions.setCleanSession(true);

    this.mqttClient = new MqttClient(this.url, clientId, null);
    this.mqttClient.connect(this.cleanupOptions);
}
 
Example #12
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void subscribeToSupportGroup(boolean useEncrypted) {
    try {
        String userKeyString = MobiComUserPreference.getInstance(context).getSuUserKeyString();
        if (TextUtils.isEmpty(userKeyString)) {
            return;
        }
        final MqttClient client = connect();
        if (client != null && client.isConnected()) {
            String topic = (useEncrypted ? MQTT_ENCRYPTION_TOPIC : "") + SUPPORT_GROUP_TOPIC + getApplicationKey(context);
            Utils.printLog(context, TAG, "Subscribing to support group topic : " + topic);
            client.subscribe(topic, 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #13
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #14
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void subscribeToOpenGroupTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        }
        final MqttClient client = connect();
        if (client == null || !client.isConnected()) {
            return;
        }

        client.subscribe(OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId), 0);
        Utils.printLog(context, TAG, "Subscribed to Open group: " + OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@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
  }
}
 
Example #16
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #17
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #18
Source File: ManualReceive.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
private void receive() throws Exception {
    MqttClient client = new MqttClient(SERVER, "test");
    MqttCallback callback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            System.out.println(message);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
        }

        @Override
        public void connectionLost(Throwable cause) {
            cause.printStackTrace();
        }
    };
    client.connect();
    client.subscribe(TOPIC_FILTER);
    client.setCallback(callback);
    System.in.read();
    client.disconnect();
    client.close();
}
 
Example #19
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void subscribe(boolean useEncrypted) {
    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(useEncrypted);
        if (client != null) {
            client.setCallback(ApplozicMqttService.this);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #20
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) + "-" + User.getEncodedUserId(currentId), 0);
        Utils.printLog(context, TAG, "Subscribed to topic: " + "typing-" + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #21
Source File: MQTT_PVConn.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
private boolean connect()
{
    if (! connected.compareAndSet(false, true))
        return true; // Already connected

    generateClientID();
    setOptions();

    // Connect to Broker
    try
    {
        myClient = new MqttClient(brokerURL, clientID);
        myClient.setCallback(this);
        myClient.connect(connOpt);
    }
    catch (MqttException ex)
    {
        PV.logger.log(Level.SEVERE, "Could not connect to MQTT broker " + brokerURL, ex);
        connected.set(false);
    }

    return connected.get();
}
 
Example #22
Source File: WildcardSubscriber.java    From paho-wildcard-subscriber with Apache License 2.0 6 votes vote down vote up
public void start() {
    log.info("Starting Wilcard subscriber");
    try {
        final String clientId = MqttClient.generateClientId();
        final MqttClient mqttClient = new MqttClient(BROKER_URL, clientId, new MemoryPersistence());

        mqttClient.setCallback(new SubscribeCallback(mqttClient));

        log.info("Connecting to {} with clientID {}", BROKER_URL, clientId);
        mqttClient.connect();

        //We subscribe to wildcard
        log.info("Subscribing to {}", TOPIC_SUBSCRIPTION);
        mqttClient.subscribe(TOPIC_SUBSCRIPTION, QUALITY_OF_SERVICE_LEVEL);

    } catch (MqttException e) {
        log.error("An unexpected error occured. Exiting", e);
        System.exit(1);
    }
}
 
Example #23
Source File: ApplozicMqttService.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public synchronized void unSubscribeToOpenGroupTopic(Channel channel) {
    try {
        String currentId = null;
        if (channel != null) {
            currentId = String.valueOf(channel.getKey());
        }

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

        client.unsubscribe(OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId));
        Utils.printLog(context, TAG, "UnSubscribed to topic: " + OPEN_GROUP + getApplicationKey(context) + "-" + User.getEncodedUserId(currentId));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #24
Source File: MQTTStreamSourceTest.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
@Test
public void testMQTTOpenException() throws Exception {
  PowerMockito.mockStatic( MQTTClientBuilder.class );
  MQTTClientBuilder.ClientFactory clientFactory = mock( MQTTClientBuilder.ClientFactory.class );
  MqttClient mqttClient = mock( MqttClient.class );
  MQTTClientBuilder builder = spy( MQTTClientBuilder.class );
  MqttException mqttException = mock( MqttException.class );

  when( clientFactory.getClient( any(), any(), any() ) ).thenReturn( mqttClient );
  when( mqttException.toString() ).thenReturn( "There is an error connecting" );
  doThrow( mqttException ).when( builder ).buildAndConnect();
  PowerMockito.when( MQTTClientBuilder.builder() ).thenReturn( builder );

  MQTTStreamSource source = new MQTTStreamSource( consumerMeta, mqttConsumer );
  source.open();

  verify( mqttConsumer ).stopAll();
  verify( mqttConsumer ).logError( "There is an error connecting" );
}
 
Example #25
Source File: MqttServerEndpointStatusTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
@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();
  }
}
 
Example #26
Source File: MQTTTestClient.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #27
Source File: MqttServerEndpointStatusTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void connected(TestContext context) {

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence);
    client.connect();
    context.assertTrue(client.isConnected() && this.endpoint.isConnected());
  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example #28
Source File: MqttConnector.java    From quarks with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new connector.
 * 
 * @param config connector configuration.
 */
public MqttConnector(Supplier<MqttConfig> config) {
    this.configFn = config;
    
    String cid = configFn.get().getClientId();
    if (cid == null)
        cid = MqttClient.generateClientId();
    clientId = cid;
}
 
Example #29
Source File: MqttServerDisconnectTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void disconnect(TestContext context) {

  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();
    context.assertTrue(true);
  } catch (MqttException e) {
    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example #30
Source File: MqttServerEndpointStatusTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void disconnectedByServer(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();

    // the local endpoint closes connection after a few seconds
    this.vertx.setTimer(1000, t -> {

      this.endpoint.close();

      // 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();
  }
}