当前位置: 首页>>代码示例>>Java>>正文


Java MqttAsyncClient.setCallback方法代码示例

本文整理汇总了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);
    }
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:33,代码来源:MqttBrokerMonitor.java

示例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");
}
 
开发者ID:DhruvKalaria,项目名称:MQTTKafkaBridge,代码行数:19,代码来源:Bridge.java

示例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);
    }
}
 
开发者ID:artikcloud,项目名称:artikcloud-java,代码行数:30,代码来源:MqttSession.java

示例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);
    }
}
 
开发者ID:aws,项目名称:aws-iot-device-sdk-java,代码行数:17,代码来源:AwsIotMqttConnection.java

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

}
 
开发者ID:glaudiston,项目名称:project-bianca,代码行数:17,代码来源:MQTT.java

示例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);
}
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:28,代码来源:MqttGatewayService.java

示例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);
}
 
开发者ID:osswangxining,项目名称:iotgateway,代码行数:29,代码来源:MqttGatewayService.java

示例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);
  }
}
 
开发者ID:osswangxining,项目名称:iotgateway,代码行数:36,代码来源:MqttBrokerMonitor.java

示例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;
	}
}
 
开发者ID:dcsolutions,项目名称:kalinka,代码行数:37,代码来源:MqttClient.java

示例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);
}
 
开发者ID:christophersmith,项目名称:summer-mqtt,代码行数:24,代码来源:PahoAsyncMqttClientService.java

示例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);
}
 
开发者ID:zerogvt,项目名称:mqttws-jmeter,代码行数:39,代码来源:MqttPubSub.java

示例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);
  }
}
 
开发者ID:MyRobotLab,项目名称:myrobotlab,代码行数:50,代码来源:SampleAsyncCallback.java

示例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;
}
 
开发者ID:LSIR,项目名称:gsn,代码行数:34,代码来源:MQTTWrapper.java

示例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);
        }
    }
 
开发者ID:osswangxining,项目名称:iot-edge-greengrass,代码行数:58,代码来源:WiotpMqttBrokerMonitor.java

示例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());
   }
 
开发者ID:knr1,项目名称:ch.bfh.mobicomp,代码行数:5,代码来源:DC.java


注:本文中的org.eclipse.paho.client.mqttv3.MqttAsyncClient.setCallback方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。