Java Code Examples for org.eclipse.paho.client.mqttv3.MqttAsyncClient#setCallback()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttAsyncClient#setCallback() .
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: AbstractMqttClient.java From xian with Apache License 2.0 | 6 votes |
/** * 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null */ public MqttAsyncClient connectBroker() { LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName)); try { sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence); connOpts = new MqttConnectOptions(); connOpts.setAutomaticReconnect(true); connOpts.setServerURIs(serverURIs); connOpts.setUserName(userName); connOpts.setPassword(getPwd()); connOpts.setCleanSession(cleanSession); connOpts.setMaxInflight(1000 /**默认的值是10,对于我们来说这个值太小!*/); connOpts.setKeepAliveInterval(keepAliveInterval); sampleClient.setCallback(getCallback(this)); sampleClient.connect(connOpts).waitForCompletion(60 * 1000); LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName)); return sampleClient; } catch (MqttException me) { throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me); } }
Example 2
Source File: Bridge.java From MQTTKafkaBridge with Apache License 2.0 | 6 votes |
private void connect(String serverURI, String clientId, String zkConnect) throws MqttException { mqtt = new MqttAsyncClient(serverURI, clientId); mqtt.setCallback(this); IMqttToken token = mqtt.connect(); Properties props = new Properties(); //Updated based on Kafka v0.8.1.1 props.put("metadata.broker.list", "localhost:9092"); props.put("serializer.class", "kafka.serializer.StringEncoder"); props.put("partitioner.class", "example.producer.SimplePartitioner"); props.put("request.required.acks", "1"); ProducerConfig config = new ProducerConfig(props); kafkaProducer = new Producer<String, String>(config); token.waitForCompletion(); logger.info("Connected to MQTT and Kafka"); }
Example 3
Source File: AwsIotMqttConnection.java From aws-iot-device-sdk-java with Apache License 2.0 | 6 votes |
public AwsIotMqttConnection(AbstractAwsIotClient client, SocketFactory socketFactory, String serverUri) throws AWSIotException { super(client); this.socketFactory = socketFactory; messageListener = new AwsIotMqttMessageListener(client); clientListener = new AwsIotMqttClientListener(client); try { mqttClient = new MqttAsyncClient(serverUri, client.getClientId(), new MemoryPersistence()); mqttClient.setCallback(clientListener); } catch (MqttException e) { throw new AWSIotException(e); } }
Example 4
Source File: PushListActivity.java From pushfish-android with BSD 2-Clause "Simplified" License | 5 votes |
private void configureMqttClient() { try { mqttClient = new MqttAsyncClient("tcp://test-io.Pushfish.api.push.fish:1883", "android", new MemoryPersistence()); mqttClient.setCallback(new MqttCallbackExtended() { @Override public void connectComplete(boolean reconnect, String serverURI) { Log.i(PushListActivity.class.getName(), "MQTT Connection successful!"); } @Override public void connectionLost(Throwable cause) { Log.w(PushListActivity.class.getName(), "MQTT Connection was lost!"); } @Override public void messageArrived(String topic, MqttMessage message) { handleMessage(topic, message); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); } catch (MqttException e) { e.printStackTrace(); } }
Example 5
Source File: MQTTWrapper.java From gsn with GNU General Public License v3.0 | 5 votes |
@Override public boolean initialize() { try { addressBean = getActiveAddressBean( ); serverURI = addressBean.getPredicateValue("uri"); if ( serverURI == null || serverURI.trim().length() == 0 ) { logger.error( "The uri parameter is missing from the MQTT wrapper, initialization failed." ); return false; } clientID = addressBean.getPredicateValue("client_id"); if ( clientID == null || clientID.trim().length() == 0 ) { logger.error( "The client_id parameter is missing from the MQTT wrapper, initialization failed." ); return false; } topic = addressBean.getPredicateValue("topic"); if ( topic == null || topic.trim().length() == 0 ) { logger.error( "The topic parameter is missing from the MQTT wrapper, initialization failed." ); return false; } qos = addressBean.getPredicateValueAsInt("qos", 0); if (qos < 0 || qos > 2) { logger.error( "The qos parameter from MQTT wrapper can be 0, 1 or 2 (found "+qos+"), initialization failed." ); return false; } client = new MqttAsyncClient(serverURI, clientID); client.setCallback(this); client.connect(); }catch (Exception e){ logger.error("Error in instanciating MQTT broker with "+topic+" @ "+serverURI,e); return false; } return true; }
Example 6
Source File: QoS1Consumer.java From solace-samples-mqtt with Apache License 2.0 | 4 votes |
public void run(String... args) { System.out.println("QoS1Consumer initializing..."); String host = args[0]; String username = args[1]; String password = args[2]; try { // Create an Mqtt client MqttAsyncClient mqttClient = new MqttAsyncClient(host, "HelloWorldQoS1Consumer"); 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); IMqttToken conToken = mqttClient.connect(connOpts); conToken.waitForCompletion(10000); if (!conToken.isComplete() || conToken.getException() != null) { System.out.println("Error connecting: " + conToken.getException()); System.exit(-1); } System.out.println("Connected"); // Latch used for synchronizing b/w threads final CountDownLatch latch = new CountDownLatch(1); // Callback - Anonymous inner-class for receiving messages mqttClient.setCallback(new MqttCallback() { public void messageArrived(String topic, MqttMessage message) throws Exception { // Called when a message arrives from the server that // matches any subscription made by the client String time = new Timestamp(System.currentTimeMillis()).toString(); System.out.println("\nReceived a Message!" + "\n\tTime: " + time + "\n\tTopic: " + topic + "\n\tMessage: " + new String(message.getPayload()) + "\n\tQoS: " + message.getQos() + "\n"); latch.countDown(); // unblock main thread } public void connectionLost(Throwable cause) { System.out.println("Connection to Solace messaging lost!" + cause.getMessage()); latch.countDown(); } public void deliveryComplete(IMqttDeliveryToken token) { } }); // Topic filter the client will subscribe to final String subTopic = "Q/tutorial"; // Subscribe client to the topic filter with QoS level of 1 System.out.println("Subscribing client to topic: " + subTopic); IMqttToken subToken = mqttClient.subscribe(subTopic, 1); subToken.waitForCompletion(10000); if (!subToken.isComplete() || subToken.getException() != null) { System.out.println("Error subscribing: " + subToken.getException()); System.exit(-1); } if (subToken.getGrantedQos()[0] != 1) { System.out.println("Expected OoS level 1 but got OoS level: " + subToken.getGrantedQos()[0]); System.exit(-1); } System.out.println("Subscribed with OoS level 1 and waiting to receive msgs"); // Wait for the message to be received try { latch.await(); // block here until message received, and latch will flip } catch (InterruptedException e) { System.out.println("I was awoken while waiting"); } // Disconnect the client mqttClient.disconnect(); System.out.println("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 7
Source File: AsyncClient.java From mqtt-jmeter with Apache License 2.0 | 4 votes |
/** * Constructs an instance of the sample client wrapper * * @param brokerUrl the url to connect to * @param clientId the client id to connect with * @param cleanSession clear state at end of connection or not (durable or non-durable subscriptions) * @param userName the username to connect with * @param password the password for the user * @throws MqttException */ public AsyncClient(String brokerUrl, String clientId, boolean cleanSession, String userName, String password, int keepAlive) throws MqttException { this.brokerUrl = brokerUrl; String testPlanFileDir = System.getProperty("java.io.tmpdir") + File.separator + "mqtt" + File.separator + clientId + File.separator + Thread.currentThread().getId(); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(testPlanFileDir); try { // Construct the connection options object that contains connection parameters // such as cleanSession and LWT MqttConnectOptions conOpt = new MqttConnectOptions(); conOpt.setCleanSession(cleanSession); if (password != null && !password.isEmpty()) { conOpt.setPassword(password.toCharArray()); } if (userName != null && !userName.isEmpty()) { conOpt.setUserName(userName); } // Setting keep alive time conOpt.setKeepAliveInterval(keepAlive); // Construct a non-blocking MQTT client instance client = new MqttAsyncClient(this.brokerUrl, clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); // Connect to the MQTT server // issue a non-blocking connect and then use the token to wait until the // connect completes. An exception is thrown if connect fails. log.info("Connecting to " + brokerUrl + " with client ID '" + client.getClientId() + "' and cleanSession " + " is " + String.valueOf(cleanSession) + " as an async clientt"); IMqttToken conToken = client.connect(conOpt, null, null); conToken.waitForCompletion(); log.info("Connected"); } catch (MqttException e) { log.info("Unable to set up client: " + e.toString()); } }