Java MqttConnectOptions.setAutomaticReconnect方法代碼示例

Java MqttConnectOptions.setAutomaticReconnect方法代碼示例 - 純淨天空 (vimsky.com)

本文整理匯總了Java中org.eclipse.paho.client.mqttv3.MqttConnectOptions.setAutomaticReconnect方法的典型用法代碼示例。如果您正苦於以下問題:Java MqttConnectOptions.setAutomaticReconnect方法的具體用法?Java MqttConnectOptions.setAutomaticReconnect怎麽用?Java MqttConnectOptions.setAutomaticReconnect使用的例子?那麽恭喜您, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類org.eclipse.paho.client.mqttv3.MqttConnectOptions的用法示例。

在下文中一共展示了MqttConnectOptions.setAutomaticReconnect方法的21個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於我們的係統推薦出更棒的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: 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



示例3: ProtobufMqttProtocolHandler

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public ProtobufMqttProtocolHandler(NativeDeviceFactoryInterface deviceFactory) {
    super(deviceFactory);

    String mqtt_url = PropertyUtil.getProperty(MQTT_URL_PROP, null);
    if (mqtt_url == null) {
        throw new RuntimeIOException("Property '" + MQTT_URL_PROP + "' must be set");
    }

    try {
        mqttClient = new MqttClient(mqtt_url, MqttClient.generateClientId(), new MemoryPersistence());
        mqttClient.setCallback(this);
        MqttConnectOptions con_opts = new MqttConnectOptions();
        con_opts.setAutomaticReconnect(true);
        con_opts.setCleanSession(true);
        mqttClient.connect(con_opts);
        Logger.debug("Connected to {}", mqtt_url);

        // Subscribe
        Logger.debug("Subscribing to response and notification topics...");
        mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
        mqttClient.subscribe(MqttProviderConstants.GPIO_NOTIFICATION_TOPIC);
        Logger.debug("Subscribed");
    } catch (MqttException e) {
        throw new RuntimeIOException(e);
    }
}
 
開發者ID:mattjlewis,項目名稱:diozero,代碼行數:27,代碼來源:ProtobufMqttProtocolHandler.java



示例4: MqttTestClient

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public MqttTestClient(String mqttUrl) throws MqttException {
    mqttClient = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence());
    mqttClient.setCallback(this);
    MqttConnectOptions con_opts = new MqttConnectOptions();
    con_opts.setAutomaticReconnect(true);
    con_opts.setCleanSession(true);
    mqttClient.connect(con_opts);
    Logger.debug("Connected to {}", mqttUrl);

    lock = new ReentrantLock();
    conditions = new HashMap<>();
    responses = new HashMap<>();

    // Subscribe
    Logger.debug("Subscribing to {}...", MqttProviderConstants.RESPONSE_TOPIC);
    mqttClient.subscribe(MqttProviderConstants.RESPONSE_TOPIC);
    Logger.debug("Subscribed");
}
 
開發者ID:mattjlewis,項目名稱:diozero,代碼行數:19,代碼來源:MqttTestClient.java



示例5: MyMqttCloudClient

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public MyMqttCloudClient(String cloudBrokerAddress, String clientId) {
//		this._cloudTopic = cloudTopic;
        this._cloudBrokerAddress = cloudBrokerAddress;
        this._clientId = clientId;
        MemoryPersistence persistence = new MemoryPersistence();
        try {
            this._mqCloudClient = new MqttClient(this._cloudBrokerAddress,
                    this._clientId, persistence);
            this._mqCloudClient.setCallback(this);
            MqttConnectOptions connOpts = new MqttConnectOptions();
//			connOpts.setCleanSession(true);
            connOpts.setConnectionTimeout(0);
            connOpts.setKeepAliveInterval(30);
            connOpts.setAutomaticReconnect(true);
            System.out.println("Connecting to cloud broker: " + this._cloudBrokerAddress);
            this._mqCloudClient.connect(connOpts);
            System.out.println("Connected");			
        } 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();
        }
    }
 
開發者ID:HPCC-Cloud-Computing,項目名稱:IoT,代碼行數:27,代碼來源:MyMqttCloudClient.java



示例6: 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



示例7: 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



示例8: 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,項目名稱:iotgateway,代碼行數:29,代碼來源:MqttGatewayService.java



示例9: initializeMqttClient

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
private void initializeMqttClient()
    throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {

    mqttClient = new MqttClient(mMqttOptions.getBrokerUrl(),
            mMqttOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(CloudIotCoreOptions.UNUSED_ACCOUNT_NAME);
    options.setAutomaticReconnect(true);

    // generate the jwt password
    options.setPassword(mqttAuth.createJwt(mMqttOptions.getProjectId()));

    mqttClient.setCallback(this);
    mqttClient.connect(options);

    if(mqttClient.isConnected()) {
        try{
            mSubTopic = "/devices/sense_hub_2.0_android_things/config";// + NetworkUtils.getMACAddress(mContext);
            Log.i(TAG, "initializeMqttClient subscribe topic=" + mSubTopic);
            mqttClient.subscribe(mSubTopic, 1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    mReady.set(true);
}
 
開發者ID:dmtan90,項目名稱:Sense-Hub-Android-Things,代碼行數:32,代碼來源:MqttIoTPublisher.java



示例10: initializeMqttClient

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
private void initializeMqttClient()
        throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Log.d(TAG, "initializeMqttClient broker=" + mMqttOptions.getBrokerUrl() +
            " clientID=" + mMqttOptions.getClientId() +
            " username=" + mMqttOptions.getUsername() +
            " password=" + mMqttOptions.getPassword());
    mqttClient = new MqttClient(mMqttOptions.getBrokerUrl(),
            mMqttOptions.getClientId(), new MemoryPersistence());

    MqttConnectOptions options = new MqttConnectOptions();
    // Note that the the Google Cloud IoT only supports MQTT 3.1.1, and Paho requires that we
    // explicitly set this. If you don't set MQTT version, the server will immediately close its
    // connection to your device.
    options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
    options.setUserName(mMqttOptions.getUsername());
    options.setPassword(mMqttOptions.getPassword().toCharArray());

    options.setAutomaticReconnect(true);

    mqttClient.setCallback(this);
    mqttClient.connect(options);

    if(mqttClient.isConnected()) {
        try{
            Log.i(TAG, "initializeMqttClient subscribe topic=" + mMqttOptions.getSubscribeTopicName());
            mqttClient.subscribe(mMqttOptions.getSubscribeTopicName(), 1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    else{
        Log.e(TAG, "Can't connect to " + mMqttOptions.getBrokerUrl());
    }
    mReady.set(true);
}
 
開發者ID:dmtan90,項目名稱:Sense-Hub-Android-Things,代碼行數:36,代碼來源:MqttPublisher.java



示例11: MqttTestApp

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
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);
}
 
開發者ID:mattjlewis,項目名稱:diozero,代碼行數:15,代碼來源:MqttTestApp.java



示例12: MqttJsonServer

 您还没有点赞,无法取消点赞!
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public MqttJsonServer(String mqttUrl) 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);
}
 
開發者ID:mattjlewis,項目名稱:diozero,代碼行數:12,代碼來源:MqttJsonServer.java



示例13: MqttProtobufServer

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public MqttProtobufServer(String mqttUrl) 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);
}
 
開發者ID:mattjlewis,項目名稱:diozero,代碼行數:12,代碼來源:MqttProtobufServer.java



示例14: 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(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("
> ");
            
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String line = br.readLine();

            handleCommand(line);
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:33,代碼來源:SparkplugExample.java



示例15: createConnectOptions

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
protected MqttConnectOptions createConnectOptions() {
    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName(accessKey);
    connOpts.setPassword(sign.toCharArray());
    connOpts.setCleanSession(cleanSession);
    connOpts.setKeepAliveInterval(90);
    connOpts.setAutomaticReconnect(true);
    return connOpts;
}
 
開發者ID:nince-wyj,項目名稱:jahhan,代碼行數:10,代碼來源:LmqClient.java



示例16: keepAliveTimeout

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
@Test
public void keepAliveTimeout(TestContext context) {

  Async async = context.async();
  int keepAliveInterval = 5;
  // MQTT spec : server will wait half more then the keepAliveInterval
  int timeout = keepAliveInterval + keepAliveInterval / 2;

  try {
    MemoryPersistence persistence = new MemoryPersistence();
    MqttClient client = new MqttClient(String.format("tcp://%s:%d", Proxy.SERVER_HOST, Proxy.SERVER_PORT), "12345", persistence);

    MqttConnectOptions options = new MqttConnectOptions();
    options.setAutomaticReconnect(false);
    options.setKeepAliveInterval(keepAliveInterval);

    this.started = System.currentTimeMillis();

    client.setCallback(new MqttCallback() {

      @Override
      public void connectionLost(Throwable throwable) {

        ended = System.currentTimeMillis();
        log.info("Elapsed : " + (ended - started));
        async.complete();
      }

      @Override
      public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {

      }

      @Override
      public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

      }
    });

    client.connect(options);

    vertx.setTimer(1000, t -> {
      proxy.pause();
    });

    async.await();

    long elapsed = ended - started;
    // consider a range of 500 ms
    context.assertTrue(elapsed > (timeout * 1000 - 500) && elapsed < (timeout * 1000 + 500));

  } catch (MqttException e) {
    context.fail(e);
  }

}
 
開發者ID:vert-x3,項目名稱:vertx-mqtt,代碼行數:57,代碼來源:MqttServerNetworkIssueTest.java



示例17: MyMqttFogClient

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public MyMqttFogClient(ArrayList<Item> items, String fogBrokerAddress, String cloudBrokerAddress, String fogClientId, String cloudClientId) {
        this._fogBrokerAddress = fogBrokerAddress;
        this._cloudBrokerAddress = cloudBrokerAddress;
        this._fogClientId = fogClientId;
        this._cloudClientId = cloudClientId;
        this._items = items;		
        MemoryPersistence persistence = new MemoryPersistence();
//		try {
//			this._mqCloudClient = new MqttClient(this._cloudBrokerAddress,
//					_cloudClientId, persistence);
//			this._mqCloudClient.setCallback(this);
//			MqttConnectOptions connOpts = new MqttConnectOptions();
//			connOpts.setCleanSession(true);
//			connOpts.setKeepAliveInterval(30);
//			System.out.println("Connecting to cloud broker: " + this._cloudBrokerAddress);
//			this._mqCloudClient.connect(connOpts);
//			System.out.println("Connected");			
//		} 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();
//		}		
        try {
            this._mqFogClient = new MqttClient(this._fogBrokerAddress, this._fogClientId,
                    persistence);
            MqttConnectOptions connOpts = new MqttConnectOptions();
            connOpts.setCleanSession(true);
            connOpts.setKeepAliveInterval(60);
            connOpts.setAutomaticReconnect(true);
            connOpts.setConnectionTimeout(0);
            System.out.println("Connecting to fog broker: " + this._fogBrokerAddress);
            this._mqFogClient.connect(connOpts);
            System.out.println("Connected");
            this._mqCloudClient = new MyMqttCloudClient(this._cloudBrokerAddress, this._cloudClientId);
            this._mqFogClient.setCallback(this);
        } catch (MqttException e) {
            e.printStackTrace();
        }
//		this._mqCloudClient = new MyMqttCloudClient(this._cloudTopic, this._cloudBrokerAddress, "oneM2M publisher");
    }
 
開發者ID:HPCC-Cloud-Computing,項目名稱:IoT,代碼行數:44,代碼來源:MyMqttFogClient.java



示例18: establishMqttSession

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
/**
 * Establish an MQTT Session with Sparkplug defined Death Certificate. It may not be
 * Immediately intuitive that the Death Certificate is created prior to publishing the
 * Birth Certificate, but the Death Certificate is actually part of the MQTT Session 
 * establishment. For complete details of the actual MQTT wire protocol refer to the 
 * latest OASyS MQTT V3.1.1 standards at:
 * http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/mqtt-v3.1.1.html
 * 
 * @return true = MQTT Session Established
 */
public boolean establishMqttSession() {
    try {

        //
        // Setup the MQTT connection parameters using the Paho MQTT Client.
        //
        MqttConnectOptions options = new MqttConnectOptions();
        
        if (USING_REAL_TLS) {
            SocketFactory sf = SSLSocketFactory.getDefault();
            options.setSocketFactory(sf);
        }
        
        // Autoreconnect enable
        options.setAutomaticReconnect(true);
        // MQTT session parameters Clean Start = true
        options.setCleanSession(true);
        // Session connection attempt timeout period in seconds
        options.setConnectionTimeout(10);
        // MQTT session parameter Keep Alive Period in Seconds
        options.setKeepAliveInterval(30);
        // MQTT Client Username
        options.setUserName(username);
        // MQTT Client Password
        options.setPassword(password.toCharArray());
        //
        // Build up the Death Certificate MQTT Payload. Note that the Death
        // Certificate payload sequence number
        // is not tied to the normal message sequence numbers.
        //
        SparkplugBPayload payload = new SparkplugBPayloadBuilder(getNextSeqNum())
                .setTimestamp(new Date())
                .addMetric(new MetricBuilder("bdSeq",
                        MetricDataType.Int64,
                        bdSeq)
                        .createMetric())
                .createPayload();
        byte[] bytes = new SparkplugBPayloadEncoder().getBytes(payload);
        //
        // Setup the Death Certificate Topic/Payload into the MQTT session
        // parameters
        //
        options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, bytes, 0, false);

        //
        // Create a new Paho MQTT Client
        //
        client = new MqttClient(serverUrl, clientId);
        //
        // Using the parameters set above, try to connect to the define MQTT
        // server now.
        //
        System.out.println("Trying to establish an MQTT Session to the MQTT Server @ :" + serverUrl);
        client.connect(options);
        System.out.println("MQTT Session Established");
        client.setCallback(this);
        //
        // With a successful MQTT Session in place, now issue subscriptions
        // for the EoN Node and Device "Command" Topics of 'NCMD' and 'DCMD'
        // defined in Sparkplug
        //
        client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
        client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);
    } catch (Exception e) {
        System.out.println("Error Establishing an MQTT Session:");
        e.printStackTrace();
        return false;
    }
    return true;
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:81,代碼來源:SparkplugRaspberryPiExample.java



示例19: run

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public void run() {
    try {
        // Random generator and thread pool for outgoing published messages
        executor = Executors.newFixedThreadPool(1);
        
        // Build up DEATH payload - note DEATH payloads don't have a regular sequence number
        SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
        deathPayload = addBdSeqNum(deathPayload);
        byte [] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());
        
        MqttConnectOptions options = new MqttConnectOptions();
        
        if (USING_REAL_TLS) {
            SocketFactory sf = SSLSocketFactory.getDefault();
            options.setSocketFactory(sf);
        }
        
        // Connect to the MQTT Server
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(30);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
        client = new MqttClient(serverUrl, clientId);
        client.setTimeToWait(2000);	
        client.setCallback(this);					// short timeout on failure to connect
        client.connect(options);
        
        // Subscribe to control/command messages for both the edge of network node and the attached devices
        client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
        client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);	
        client.subscribe(NAMESPACE + "/#", 0);	
        
        // Loop forever publishing data every PUBLISH_PERIOD
        while (true) {
            Thread.sleep(PUBLISH_PERIOD);

            if (client.isConnected()) {
                synchronized(seqLock) {
                    System.out.println("Connected - publishing new data");
                    // Create the payload and add some metrics
                    SparkplugBPayload payload = new SparkplugBPayload(
                            new Date(), 
                            newMetrics(false), 
                            getSeqNum(),
                            newUUID(), 
                            null);
                    
                    client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId, 
                            new SparkplugBPayloadEncoder().getBytes(payload), 0, false);
                }
            } else {
                System.out.println("Not connected - not publishing data");
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:62,代碼來源:SparkplugExample.java



示例20: run

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
public void run() {
    try {
        // Random generator and thread pool for outgoing published messages
        executor = Executors.newFixedThreadPool(1);

        // Build up DEATH payload - note DEATH payloads don't have a regular sequence number
        SparkplugBPayloadBuilder deathPayload = new SparkplugBPayloadBuilder().setTimestamp(new Date());
        deathPayload = addBdSeqNum(deathPayload);
        byte[] deathBytes = new SparkplugBPayloadEncoder().getBytes(deathPayload.createPayload());

        MqttConnectOptions options = new MqttConnectOptions();

        if (USING_REAL_TLS) {
            SocketFactory sf = SSLSocketFactory.getDefault();
            options.setSocketFactory(sf);
        }

        // Connect to the MQTT Server
        options.setAutomaticReconnect(true);
        options.setCleanSession(true);
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(30);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setWill(NAMESPACE + "/" + groupId + "/NDEATH/" + edgeNode, deathBytes, 0, false);
        client = new MqttClient(serverUrl, clientId);
        client.setTimeToWait(2000);
        client.setCallback(this); // short timeout on failure to connect
        client.connect(options);

        // Subscribe to control/command messages for both the edge of network node and the attached devices
        client.subscribe(NAMESPACE + "/" + groupId + "/NCMD/" + edgeNode + "/#", 0);
        client.subscribe(NAMESPACE + "/" + groupId + "/DCMD/" + edgeNode + "/#", 0);

        // Loop forever publishing data every PUBLISH_PERIOD
        while (true) {
            Thread.sleep(PUBLISH_PERIOD);

            if (client.isConnected()) {
                synchronized (seqLock) {
                    System.out.println("Connected - publishing new data");
                    // Create the payload and add some metrics
                    SparkplugBPayload payload = new SparkplugBPayload(new Date(), newComplexTemplateInstance(),
                            getSeqNum(), newUUID(), null);

                    client.publish(NAMESPACE + "/" + groupId + "/DDATA/" + edgeNode + "/" + deviceId,
                            new SparkplugBPayloadEncoder().getBytes(payload), 0, false);
                }
            } else {
                System.out.println("Not connected - not publishing data");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
開發者ID:Cirrus-Link,項目名稱:Sparkplug,代碼行數:57,代碼來源:SparkplugExample.java



示例21: reconnectOptions

 
import org.eclipse.paho.client.mqttv3.MqttConnectOptions; //導入方法依賴的package包/類
@NonNull
public static MqttConnectOptions reconnectOptions(@NonNull final MqttConnectOptions options) {
    options.setAutomaticReconnect(true);
    options.setCleanSession(false);
    return options;
}
 
開發者ID:yongjhih,項目名稱:rx-mqtt,代碼行數:7,代碼來源:RxMqtt.java




注:本文中的org.eclipse.paho.client.mqttv3.MqttConnectOptions.setAutomaticReconnect方法示例整理自Github/MSDocs等源碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。

原文地址:https://www.cnblogs.com/zkwarrior/p/14783837.html