本文整理汇总了Java中org.eclipse.paho.client.mqttv3.MqttAsyncClient.setCallback方法的典型用法代码示例。如果您正苦于以下问题:Java MqttAsyncClient.setCallback方法的具体用法?Java MqttAsyncClient.setCallback怎么用?Java MqttAsyncClient.setCallback使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.eclipse.paho.client.mqttv3.MqttAsyncClient
的用法示例。
在下文中一共展示了MqttAsyncClient.setCallback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: connect
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
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);
}
}
示例2: connect
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
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");
}
示例3: MqttSession
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
/**
*
* @param deviceId ARTIK Cloud device ID
* @param deviceToken ARTIK Cloud device token
* @param msgCallback callback handling events such as receiving message from the topic subscribing to
* @param userCallback callback handling mqtt operations such as connect/disconnect/publish/subscribe et al.
* @throws ArtikCloudMqttException
*/
public MqttSession(String deviceId,
String deviceToken,
ArtikCloudMqttCallback callback
) throws ArtikCloudMqttException {
this.operationListener = new OperationListener(callback);
this.deviceId = deviceId;
this.deviceToken = deviceToken;
this.brokerUri = SCHEME + "://" + HOST + ":" + PORT;
this.publishMessageTopicPath = PUBLISH_TOPIC_MESSAGES_BASE + deviceId;
this.subscribeActionsTopicPath = SUBSCRIBE_TOPIC_ACTIONS_BASE + deviceId;
this.subscribeErrorTopicPath = SUBSCRIBE_TOPIC_ERRORS_BASE + deviceId;
try {
mqttClient = new MqttAsyncClient(brokerUri, deviceId, new MemoryPersistence());
msgListener = new MessageListener(callback);
mqttClient.setCallback(msgListener);
} catch (MqttException e) {
throw new ArtikCloudMqttException(e);
}
}
示例4: AwsIotMqttConnection
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
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);
}
}
示例5: startClient
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
public void startClient() throws MqttException {
MemoryPersistence persistence = new MemoryPersistence();
try {
conOpt = new MqttConnectOptions();
conOpt.setCleanSession(true);
// Construct the MqttClient instance
client = new MqttAsyncClient(this.brokerURL, clientId, persistence);
// Set this wrapper as the callback handler
client.setCallback(this);
} catch (MqttException e) {
log.info("Unable to set up client: " + e.toString());
}
}
示例6: init
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
@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);
}
示例7: init
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
@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);
}
示例8: connect
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
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);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
clientOptions.setSocketFactory(sslContext.getSocketFactory());
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 | NoSuchAlgorithmException | KeyManagementException e) {
log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
throw new RuntimeException("MQTT broker connection failed!", e);
}
}
示例9: doConnectBroker
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
private boolean doConnectBroker() {
try {
LOG.debug("{} > connect..", url);
final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
mqttConnectOptions.setUserName("admin");
mqttConnectOptions.setPassword("admin".toCharArray());
mqttConnectOptions.setCleanSession(true);
mqttConnectOptions.setWill(pubTopic2Mqtt, "Bye, bye Baby!".getBytes(), 0, false);
// client
final String tmpDir = System.getProperty("java.io.tmpdir");
final MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir);
LOG.info("creating MqttAsyncClient for {} and {}", url, clientId);
mqttAsyncClient = new MqttAsyncClient(url, clientId, dataStore);
// callback
mqttAsyncClient.setCallback(this);
// connect
mqttAsyncClient.connect(mqttConnectOptions).waitForCompletion();
// subscriptions
for (final String subTopic : subTopics) {
LOG.info("client {} subscribing to {}", clientId, subTopic);
mqttAsyncClient.subscribe(subTopic, 0);
}
LOG.info("{} > mqtt connection established for {}.", url, clientId);
return true;
} catch (final Throwable throwable) {
LOG.error("{} > connection failed. ({})", url, throwable.getMessage());
close();
return false;
}
}
示例10: PahoAsyncMqttClientService
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
/**
* Default constructor
*
* @param serverUri the Server URI to connect to
* @param clientId the Client ID to connect as
* @param connectionType the {@link MqttClientConnectType} this instance will be used as
* @param clientPersistence TODO: add description
* @throws IllegalArgumentException if the {@code serverUri} is blank or null, the
* {@code clientId} is blank or null, or if the {@code connectionType} value is null
* @throws MqttException if the underlying {@link MqttAsyncClient} instance cannot be created
*/
public PahoAsyncMqttClientService(final String serverUri, final String clientId,
final MqttClientConnectionType connectionType,
final MqttClientPersistence clientPersistence)
throws MqttException
{
super(connectionType);
Assert.hasText(serverUri, "'serverUri' must be set!");
Assert.hasText(clientId, "'clientId' must be set!");
this.clientPersistence = clientPersistence;
mqttClient = new MqttAsyncClient(serverUri, clientId, this.clientPersistence);
mqttClient.setCallback(this);
}
示例11: delayedSetupTest
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
public void delayedSetupTest(JavaSamplerContext context){
log.debug(myname + ">>>> in setupTest");
host = context.getParameter("HOST");
throttle = Integer.parseInt((context.getParameter("PUBLISHER_THROTTLE")));
acksTimeout = Integer.parseInt((context.getParameter("PUBLISHER_ACKS_TIMEOUT")));
//System.out.println("Publisher acks timeout: " + acksTimeout);
clientId = context.getParameter("CLIENT_ID");
if("TRUE".equalsIgnoreCase(context.getParameter("RANDOM_SUFFIX"))){
clientId= MqttPubSub.getClientId(clientId,Integer.parseInt(context.getParameter("SUFFIX_LENGTH")));
}
try {
log.debug("Host: " + host + "clientID: " + clientId);
client = new MqttAsyncClient(host, clientId, new MemoryPersistence());
} catch (MqttException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
//options.setCleanSession(false);
options.setCleanSession(Boolean.parseBoolean((context.getParameter("CLEAN_SESSION"))));
//System.out.println("Pubs cleansession ====> " + context.getParameter("CLEAN_SESSION"));
options.setKeepAliveInterval(0);
timeout = Integer.parseInt((context.getParameter("CONNECTION_TIMEOUT")));
myname = context.getParameter("SAMPLER_NAME");
String user = context.getParameter("USER");
String pwd = context.getParameter("PASSWORD");
if (user != null) {
options.setUserName(user);
if ( pwd!=null ) {
options.setPassword(pwd.toCharArray());
}
}
clientConnect(timeout);
client.setCallback(this);
}
示例12: SampleAsyncCallback
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
/**
* 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 quietMode
* whether debug should be printed to standard out
* @param userName
* the username to connect with
* @param password
* the password for the user
* @throws MqttException if an error happens
*/
public SampleAsyncCallback(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException {
this.brokerUrl = brokerUrl;
this.quietMode = quietMode;
this.clean = cleanSession;
this.password = password;
this.userName = userName;
try {
// Construct the object that contains connection parameters
// such as cleansession and LWAT
conOpt = new MqttConnectOptions();
conOpt.setCleanSession(clean);
if (password != null) {
conOpt.setPassword(this.password.toCharArray());
}
if (userName != null) {
conOpt.setUserName(this.userName);
}
// Construct the MqttClient instance
client = new MqttAsyncClient(this.brokerUrl, clientId);
// Set this wrapper as the callback handler
client.setCallback(this);
} catch (MqttException e) {
e.printStackTrace();
log("Unable to set up client: " + e.toString());
System.exit(1);
}
}
示例13: initialize
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
@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;
}
示例14: connect
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
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.setUserName("a-u88ncg-1qo8utyxwr");
// clientOptions.setPassword("KB?fB1sG-1GFb?wLvx".toCharArray());
clientOptions.setCleanSession(true);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
clientOptions.setSocketFactory(sslContext.getSocketFactory());
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);
// Properties props = new Properties();
// props.put("id", "appId001");
// props.put("Organization-ID", "u88ncg");
// props.put("Authentication-Method", "apikey");
// props.put("API-Key", "a-u88ncg-1qo8utyxwr");
// props.put("Authentication-Token", "KB?fB1sG-1GFb?wLvx");
// props.put("Device-Type", "DC_SensorType");
// props.put("Device-ID", "my-device-001");
// props.put("Shared-Subscription", "false");
// props.put("Clean-Session", "true");
//
// myClient = new ApplicationClient(props);
client.connect(clientOptions).waitForCompletion(1000 * 60);
if (client.isConnected()) {
System.out.println("Successfully connected " + "to the IBM Watson IoT Platform");
}
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 (Exception e) {
log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e);
throw new RuntimeException("MQTT broker connection failed!", e);
}
}
示例15: DC
import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //导入方法依赖的package包/类
public DC() throws MqttException, InterruptedException {
client = new MqttAsyncClient(CONNECTION, UID, new MemoryPersistence());
client.setCallback(new MQTTCallbackHandler());
}