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


Java MqttConnectOptions.setCleanSession方法代码示例

本文整理汇总了Java中org.eclipse.paho.client.mqttv3.MqttConnectOptions.setCleanSession方法的典型用法代码示例。如果您正苦于以下问题:Java MqttConnectOptions.setCleanSession方法的具体用法?Java MqttConnectOptions.setCleanSession怎么用?Java MqttConnectOptions.setCleanSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.eclipse.paho.client.mqttv3.MqttConnectOptions的用法示例。


在下文中一共展示了MqttConnectOptions.setCleanSession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: init

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
@Override
public void init(MqttPluginConfiguration configuration) {
  retryInterval = configuration.getRetryInterval();

  mqttClientOptions = new MqttConnectOptions();
  mqttClientOptions.setCleanSession(false);
  mqttClientOptions.setMaxInflight(configuration.getMaxInFlight());
  mqttClientOptions.setAutomaticReconnect(true);
  String clientId = configuration.getClientId();
  if (StringUtils.isEmpty(clientId)) {
    clientId = UUID.randomUUID().toString();
  }
  if (!StringUtils.isEmpty(configuration.getAccessToken())) {
    mqttClientOptions.setUserName(configuration.getAccessToken());
  }
  try {
    mqttClient = new MqttAsyncClient("tcp://" + configuration.getHost() + ":" + configuration.getPort(), clientId);
  } catch (Exception e) {
    log.error("Failed to create mqtt client", e);
    throw new RuntimeException(e);
  }
  // connect();
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:24,代码来源:MqttPlugin.java

示例2: connect

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的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

示例3: getMqttConnectOptions

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public MqttConnectOptions getMqttConnectOptions() {
    MqttConnectOptions options = new MqttConnectOptions();
    options.setCleanSession(isCleanSession());
    options.setConnectionTimeout(getTimeout());
    options.setKeepAliveInterval(getKeepAlive());

    if (!getUsername().isEmpty()) {
        options.setUserName(getUsername());
    }

    if (!getPassword().isEmpty()) {
        options.setPassword(getPassword().toCharArray());
    }

    if (!getLwtTopic().isEmpty() && !getLwtPayload().isEmpty()) {
        options.setWill(getLwtTopic(), getLwtPayload().getBytes(), getLwtQos(), isLwtRetained());
    }

    return options;
}
 
开发者ID:emqtt,项目名称:EMQ-Android-Toolkit,代码行数:21,代码来源:Connection.java

示例4: connectAndSubscribe

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
/*********************************************************************************************************************************************************************
 *
 */
private void connectAndSubscribe() throws Exception {

  ConfigHandler configHandler = serialMqttBridge.getConfigHandler();

  mqttClient = new MqttClient(configHandler.getMqttBrokerUrl(), configHandler.getMqttClientId(), null);
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  connOpts.setAutomaticReconnect(true);

  // Authentication
  if (configHandler.getMqttBrokerUsername() != null && configHandler.getMqttBrokerPassword() != null) {
    connOpts.setUserName(configHandler.getMqttBrokerUsername());
    connOpts.setPassword(configHandler.getMqttBrokerPassword().toCharArray());
  }

  // MqttCallback
  mqttCallback = new MqttSubscriptionCallback(this);
  mqttClient.setCallback(mqttCallback);

  mqttClient.connect(connOpts);

  // Subscribe to defined inbound topic
  mqttClient.subscribe(configHandler.getMqttTopicSubscribe(), configHandler.getMqttQosSubscribe());
}
 
开发者ID:DerTomm,项目名称:SerialMqttBridge,代码行数:28,代码来源:MqttHandler.java

示例5: connectClient

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void connectClient() {
  try {
    client = new MqttClient(broker, clientId);
    client.setCallback(this);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(user);
    connOpts.setPassword(password.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(OUTGOING_MQTT_KEEP_ALIVE);
    logger.debug("Connecting to broker:  " + broker);
    client.connect(connOpts);
    logger.debug("Connected");
  } catch (MqttException e) {
    logger.error("Failed to connect to MQTT client ( " + broker + "/" + clientId
        + ") for outbound messages");
    logger.error(e.getLocalizedMessage());
    e.printStackTrace();
  }
}
 
开发者ID:edgexfoundry,项目名称:device-mqtt,代码行数:20,代码来源:OutgoingSender.java

示例6: startListening

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void startListening() {
  logger.debug("Starting listening for response traffic");
  try {
    String url =
        cmdrespMqttBrokerProtocol + "://" + cmdrespMqttBroker + ":" + cmdrespMqttBrokerPort;
    client = new MqttClient(url, cmdrespMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(cmdrespMqttUser);
    connOpts.setPassword(cmdrespMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(cmdrespMqttKeepAlive);
    logger.debug("Connecting to response message broker:  " + cmdrespMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to response message broker");
    client.setCallback(this);
    client.subscribe(cmdrespMqttTopic, cmdrespMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to response message queue.  "
        + "Unable to respond to command requests.");
    e.printStackTrace();
    client = null;
  }
}
 
开发者ID:edgexfoundry,项目名称:device-mqtt,代码行数:24,代码来源:CommandResponseListener.java

示例7: startListening

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void startListening() {
  logger.debug("Starting listening for incoming traffic");
  try {
    String url =
        incomingMqttBrokerProtocol + "://" + incomingMqttBroker + ":" + incomingMqttBrokerPort;
    client = new MqttClient(url, incomingMqttClientId);
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(incomingMqttUser);
    connOpts.setPassword(incomingMqttPassword.toCharArray());
    connOpts.setCleanSession(true);
    connOpts.setKeepAliveInterval(incomingMqttKeepAlive);
    logger.debug("Connecting to incoming message broker:  " + incomingMqttBroker);
    client.connect(connOpts);
    logger.debug("Connected to incoming message broker");
    client.setCallback(this);
    client.subscribe(incomingMqttTopic, incomingMqttQos);
  } catch (MqttException e) {
    logger.error("Unable to connect to incoming message queue.");
    e.printStackTrace();
    client = null;
  }
}
 
开发者ID:edgexfoundry,项目名称:device-mqtt,代码行数:23,代码来源:IncomingListener.java

示例8: connect

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void connect() {
    logger.debug(MessageFormat.format("Connecting to {0} as {1}", mqttConfig.getBroker(), mqttConfig.getClientid()));
    try {
        mqttSession = new MqttAsyncClient(mqttConfig.getBroker(),
                mqttConfig.getClientid(),
                new MemoryPersistence());
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);

        mqttSession.connect(connOpts, new TetradMQTTConnectionListener(this));
    } catch (MqttException e) {
        logger.error(MessageFormat.format("Error connecting to {0} as {1}. Message: {2}, ReasonCode: {3}",
                mqttConfig.getBroker(),
                mqttConfig.getClientid(),
                e.getMessage(),
                e.getReasonCode()
        ));
        e.printStackTrace();
    }

}
 
开发者ID:dmitriid,项目名称:tetrad,代码行数:22,代码来源:TetradMQTT.java

示例9: optionsFromModel

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private MqttConnectOptions optionsFromModel(ConnectionModel model){

        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(model.isCleanSession());
        connOpts.setConnectionTimeout(model.getTimeout());
        connOpts.setKeepAliveInterval(model.getKeepAlive());
        if(!model.getUsername().equals(ActivityConstants.empty)){
            connOpts.setUserName(model.getUsername());
        }

        if(!model.getPassword().equals(ActivityConstants.empty)){
            connOpts.setPassword(model.getPassword().toCharArray());
        }
        /*
        if(!model.getLwtTopic().equals(ActivityConstants.empty) && !model.getLwtMessage().equals(ActivityConstants.empty)){
            connOpts.setWill(model.getLwtTopic(), model.getLwtMessage().getBytes(), model.getLwtQos(), model.isLwtRetain());
        }*/
        //   if(tlsConnection){
        //       // TODO Add Keys to conOpts here
        //       //connOpts.setSocketFactory();
        //   }
        return connOpts;
    }
 
开发者ID:Cirrus-Link,项目名称:Sparkplug,代码行数:24,代码来源:MainActivity.java

示例10: run

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
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();
	}
}
 
开发者ID:Cirrus-Link,项目名称:Sparkplug,代码行数:22,代码来源:SparkplugListener.java

示例11: InputPinHandler

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public InputPinHandler() {
  MqttConnectOptions connOpts = new MqttConnectOptions();
  connOpts.setCleanSession(true);
  try {
    mClient = new MqttClient(PropertyUtil.getMqttAddress(), MqttClient.generateClientId(), new MemoryPersistence());
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connecting to broker " + PropertyUtil.getMqttAddress() + "...");
    }
    mClient.connect(connOpts);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Connected to broker " + PropertyUtil.getMqttAddress() + ".");
    }
  } catch (MqttException e) {
    LOGGER.error(e.getMessage(), e);
  }
}
 
开发者ID:thilankam,项目名称:AppInventorRaspberryPiCompanion,代码行数:17,代码来源:InputPinHandler.java

示例12: connect

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的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

示例13: init

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的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

示例14: connectClient

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
private void connectClient() throws Exception {
	try {
	    String mqttServerAddress = String.format("ssl://%s:%s", mqttBridgeHostname, mqttBridgePort);

		MqttConnectOptions connectOptions = new MqttConnectOptions();
	    connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
	    connectOptions.setUserName(username);
	    password = createJwt(projectId, privateKeyFile, algorithm);
	    connectOptions.setPassword(password.toCharArray());

		connectOptions.setCleanSession(true);
		connectOptions.setKeepAliveInterval(keepAlive);

	    client = new MqttClient(mqttServerAddress, clientId, new MemoryPersistence());
		client.setCallback(this);

		logger.debug("Connecting to broker:  " + mqttServerAddress);
		client.connect(connectOptions);
		logger.debug("Connected");
		
	} catch (Exception e) {
		logger.error("Failed to connect to MQTT client ( " + mqttBridgeHostname + ":" + mqttBridgePort + "/" + clientId + ") for outbound messages");
		throw e;
	}
}
 
开发者ID:edgexfoundry,项目名称:export-distro,代码行数:26,代码来源:IotCoreMQTTSender.java

示例15: main

import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //导入方法依赖的package包/类
public static void main(String args[]) {
    String topic = "iot/iot";
    String content = "Hello ith";
    int qos = 2;
    String broker = "tcp://127.0.0.1:1883";
    String clientId = "sample";
    MemoryPersistence persistence = new MemoryPersistence();

    try {
        MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        System.out.println("Connecting to broker");
        sampleClient.connect(connOpts);
        System.out.println("connected");
        System.out.println("Publishing meessage: " + content);
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        sampleClient.publish(topic, message);
        System.out.println("Message published");
        sampleClient.disconnect();
        System.out.println("Disconnected");
        System.exit(0);
    } catch (MqttException e){
        System.out.println("reason " + e.getReasonCode());
        System.out.println("msg " + e.getMessage());
        System.out.println("loc " + e.getLocalizedMessage());
        System.out.println("cause " + e.getCause());
        System.out.println("exxcep " + e);
    }

}
 
开发者ID:dream-lab,项目名称:echo,代码行数:33,代码来源:MQTTPublisher.java


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