Java Code Examples for org.eclipse.paho.client.mqttv3.MqttClient#connect()

The following examples show how to use org.eclipse.paho.client.mqttv3.MqttClient#connect() . 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: 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 2
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 3
Source File: MQTTClient.java    From amazon-mq-workshop with Apache License 2.0 6 votes vote down vote up
private static void sendMessages(MqttClient client, MqttConnectOptions options, String destination, String name, int interval, WrapInt count) throws Exception {
    client.connect(options);
    System.out.println(String.format("Successfully connected to %s", client.getServerURI()));

    while (true) {
        count.v++;

        String message = String.format("[topic://%s] [%s] Message number %s", destination.replace('/', '.'), name, count.v);
        client.publish(destination, message.getBytes(StandardCharsets.UTF_8), 1, false);

        if (interval > 0) {
            System.out.println(String.format("%s - Sender: sent '%s'", df.format(new Date()), message));
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                System.out.println(String.format("Error: %s", e.getMessage()));
                System.exit(1);
            }
        }
    }
}
 
Example 4
Source File: MqttServerSubscribeTest.java    From vertx-mqtt with Apache License 2.0 6 votes vote down vote up
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();
    }
  }
 
Example 5
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 6
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 7
Source File: MQTTTestClient.java    From product-ei 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 8
Source File: SparkplugExample.java    From Sparkplug with Eclipse Public License 1.0 5 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(2000);	
		client.setCallback(this);
		client.connect(options);
		
		// Subscribe to control/command messages for both the edge of network node and the attached devices
		client.subscribe(NAMESPACE + "/" + groupId + "/+/" + edgeNode, 0);
		client.subscribe(NAMESPACE + "/" + groupId + "/+/" + edgeNode + "/*", 0);
		
		// Loop to receive input commands
		while (true) {
			System.out.print("\n> ");
			
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String line = br.readLine();

			handleCommand(line);
		}
	} catch(Exception e) {
		e.printStackTrace();
	}
}
 
Example 9
Source File: MqttListener.java    From diozero with MIT License 5 votes vote down vote up
public MqttListener() {
	try {
		mqttClient = new MqttClient(mqttServer, MqttClient.generateClientId(), new MemoryPersistence());
		mqttClient.setCallback(this);
		MqttConnectOptions con_opts = new MqttConnectOptions();
		con_opts.setCleanSession(true);
		mqttClient.connect(con_opts);
		System.out.println("Connected to '" + mqttServer + "'");
	} catch (MqttException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 10
Source File: MqttServerConnectionTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void refusedIdentifierRejected(TestContext context) {

  this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED;

  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.fail();
  } catch (MqttException e) {
    context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID);
  }
}
 
Example 11
Source File: MqttTestApp.java    From diozero with MIT License 5 votes vote down vote up
public MqttTestApp() throws UnknownHostException, MqttException {
	mqttClient = new MqttClient(mqttUrl, CLIENT_ID_PREFIX + InetAddress.getLocalHost().getHostName(),
			new MemoryPersistence());
	mqttClient.setCallback(this);
	MqttConnectOptions con_opts = new MqttConnectOptions();
	con_opts.setAutomaticReconnect(true);
	con_opts.setCleanSession(true);
	Logger.debug("Connecting to {}...", mqttUrl);
	mqttClient.connect(con_opts);
	Logger.debug("Connected to {}", mqttUrl);

	mqttClient.subscribe("outTopic");
	mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
}
 
Example 12
Source File: MQTTEventAdapter.java    From osgi.iot.contest.sdk with Apache License 2.0 5 votes vote down vote up
@Activate	
void activate(Config config, BundleContext context) throws Exception {
	id = context.getProperty(Constants.FRAMEWORK_UUID).toString();
	try {
		mqtt = new MqttClient(config.broker(), id);
		mqtt.connect();
		mqtt.setCallback(this);
		for(String topic : config.mqtt_topics()){
			mqtt.subscribe(topic.replaceAll("\\*", "#"));
		}
	} catch(Exception e){
		System.err.println("Error connecting to MQTT broker "+config.broker());
		throw e;
	}
}
 
Example 13
Source File: MqttServerUnsubscribeTest.java    From vertx-mqtt with Apache License 2.0 5 votes vote down vote up
@Test
public void unsubscribe(TestContext context) {

  this.subscribeAsync = context.async();
  this.unsubscribeAsync = 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[]{MQTT_TOPIC};
    int[] qos = new int[]{0};
    client.subscribe(topics, qos);

    this.subscribeAsync.await();

    client.unsubscribe(topics);

    this.unsubscribeAsync.await();

    context.assertTrue(true);

  } catch (MqttException e) {

    context.assertTrue(false);
    e.printStackTrace();
  }
}
 
Example 14
Source File: MqttUsage.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public MqttUsage(String host, int port, String user, String pwd) {
    try {
        client = new MqttClient("tcp://" + host + ":" + port, UUID.randomUUID().toString());
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(user);
        options.setPassword(pwd.toCharArray());
        client.connect(options);
        await().until(client::isConnected);
    } catch (MqttException e) {
        throw new RuntimeException(e);
    }
}
 
Example 15
Source File: PushSenderMqtt.java    From hmdm-server with Apache License 2.0 5 votes vote down vote up
@Override
public void init() {
    try {
        client = new MqttClient("tcp://" + serverUri, "HMDMServer", persistence);
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        client.connect(options);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 16
Source File: MqttConnector.java    From quarks with Apache License 2.0 5 votes vote down vote up
@Override
protected synchronized MqttClient doConnect(MqttClient client) throws MqttException {
    MqttConfig config = configFn.get();
    
    if (client == null)
        client = newClient(config);
    
    if (client.isConnected())
        return client;
    
    MqttConnectOptions options = (MqttConnectOptions) config.options();
    
    logger.info("{} cleanSession:{} userName:{} password:{} idleTimeout:{} idleReconnectTimeout:{} cnTimeout:{} keepalive:{} serverURIs:{} willDst:{} willMsg:{}",
            id(),
            options.isCleanSession(),
            options.getUserName(),
            options.getPassword() == null ? null : "*****",
            config.getIdleTimeout(),
            config.getSubscriberIdleReconnectInterval(),
            options.getConnectionTimeout(),
            options.getKeepAliveInterval(),
            options.getServerURIs(),
            options.getWillDestination(),
            options.getWillMessage()
            );
    
    client.connect(options);

    setIdleTimeout(config.getIdleTimeout(), TimeUnit.SECONDS);
    
    MqttSubscriber<?> sub = subscriber;
    if (sub != null) {
        setIdleReconnectInterval(config.getSubscriberIdleReconnectInterval());
        sub.connected(client);
    }

    return client;
}
 
Example 17
Source File: PahoMQTTQOS2SecurityTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 300000)
public void testSendAndReceiveMQTT() throws Exception {
   final CountDownLatch latch = new CountDownLatch(1);

   MqttClient consumer = createPahoClient("consumerId");
   MqttClient producer = createPahoClient("producerId");
   MqttConnectOptions conOpt = new MqttConnectOptions();
   conOpt.setCleanSession(true);
   conOpt.setUserName(user1);
   conOpt.setPassword(password1.toCharArray());
   consumer.connect(conOpt);
   consumer.subscribe(getQueueName(), 2);
   final boolean[] failed = new boolean[1];
   consumer.setCallback(new MqttCallback() {


      @Override
      public void connectionLost(Throwable cause) {
         cause.printStackTrace();
         failed[0] = true;
         latch.countDown();
      }

      @Override
      public void messageArrived(String topic, MqttMessage message) throws Exception {
         latch.countDown();
      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken token) {

      }
   });

   producer.connect(conOpt);
   producer.publish(getQueueName(), "hello".getBytes(), 2, false);

   waitForLatch(latch);
   producer.disconnect();
   producer.close();
   Assert.assertFalse(failed[0]);
}
 
Example 18
Source File: TopicPublisher.java    From solace-samples-mqtt with Apache License 2.0 4 votes vote down vote up
public void run(String... args) {
    System.out.println("TopicPublisher initializing...");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    try {
        // Create an Mqtt client
        MqttClient mqttClient = new MqttClient(host, "HelloWorldPub");
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        
        // Connect the client
        System.out.println("Connecting to Solace messaging at " + host);
        mqttClient.connect(connOpts);
        System.out.println("Connected");

        // Create a Mqtt message
        String content = "Hello world from MQTT!";
        MqttMessage message = new MqttMessage(content.getBytes());
        // Set the QoS on the Messages - 
        // Here we are using QoS of 0 (equivalent to Direct Messaging in Solace)
        message.setQos(0);
        
        System.out.println("Publishing message: " + content);
        
        // Publish the message
        mqttClient.publish("T/GettingStarted/pubsub", message);
        
        // Disconnect the client
        mqttClient.disconnect();
        
        System.out.println("Message published. Exiting");

        System.exit(0);
    } 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();
    }
}
 
Example 19
Source File: MqttClientHandler.java    From SI with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private void connect(String brokerURL, String userName, String password, 
			boolean ssl, boolean cleanSession) throws Exception {
		MqttConnectOptions connOpt = new MqttConnectOptions();

		connOpt.setCleanSession(cleanSession);
		connOpt.setKeepAliveInterval(keepAliveInterval);

		if (userName != null) {
			connOpt.setUserName(userName);
		}
		if  (password != null) {
			connOpt.setPassword(password.toCharArray());
		}

		if(ssl) {
//			SSLContext sslContext = SSLContext.getInstance("TLS");
//			TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//			KeyStore keyStore = KeyStore.getInstance("JKS");
//			InputStream in = new FileInputStream(KEY_STORE_LOCATION);
//			keyStore.load(in, KEY_STORE_PASSWORD.toCharArray());
//			
//			trustManagerFactory.init(keyStore);
//			sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
//			 
//			connOpt.setSocketFactory(sslContext.getSocketFactory());
			
			
//			connOpt.setSocketFactory(SSLSocketFactory.getDefault());
		}
		
		
//		mqttClient = new MqttAsyncClient(brokerURL, clientID);
		mqttClient = new MqttClient(brokerURL, clientID);
		mqttClient.setCallback(this);
		mqttClient.connect(connOpt);
//		mqttClient.connect(connOpt, new IMqttActionListener() {
//
//			@Override
//			public void onSuccess(IMqttToken asyncActionToken) {
//				// TODO Auto-generated method stub
//				try {
//					setSubscribe();
//				} catch (Exception e) {
//					log.error("Subscription exception: ", e);
//				}
//			}
//
//			@Override
//			public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//				// TODO Auto-generated method stub
//				
//			}
//			
//		});
		log.debug("MQTT] connected to mqtt borker.");
	
//		pingSender = new TimerPingSender();
//		pingSender.schedule((keepAliveInterval-5)*1000);
//		pingSender.start();
		
//		MqttDeliveryToken token = new MqttDeliveryToken(getClientId());
//		MqttPingReq pingMsg = new MqttPingReq();
//		mqttClient. sendNoWait(pingMsg, token);
		
	}
 
Example 20
Source File: PahoIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testMQTTProducer() throws Exception {

    String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").
            transform(body().prepend("Hello ")).
            to("paho:" + BrokerSetup.TEST_TOPIC + "?brokerUrl=" + conUrl);
        }
    });

    camelctx.start();
    try {
        MqttClient client = new MqttClient(conUrl, "MqttClient", new MemoryPersistence());
        MqttConnectOptions opts = new MqttConnectOptions();
        opts.setCleanSession(true);
        client.connect(opts);
        client.subscribe(BrokerSetup.TEST_TOPIC, 2);

        final List<String> result = new ArrayList<>();
        final CountDownLatch latch = new CountDownLatch(1);

        client.setCallback(new MqttCallback() {

            @Override
            public void connectionLost(Throwable cause) {
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                result.add(new String (message.getPayload()));
                latch.countDown();
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
            }});

        ProducerTemplate producer = camelctx.createProducerTemplate();
        producer.asyncSendBody("direct:start", "Kermit");

        Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
        Assert.assertEquals("One message", 1, result.size());
        Assert.assertEquals("Hello Kermit", result.get(0));
    } finally {
        camelctx.close();
    }
}