當前位置: 首頁>>代碼示例>>Java>>正文


Java MqttAsyncClient類代碼示例

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


MqttAsyncClient類屬於org.eclipse.paho.client.mqttv3包,在下文中一共展示了MqttAsyncClient類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: init

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的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.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

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

示例4: connect

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的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

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

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

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

示例8: AllDataEvent

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
public AllDataEvent(AHandler deviceHandler, String eventTopic, MqttAsyncClient mqttClient) {
super(deviceHandler, eventTopic, "allData", mqttClient);
super.addDescription(IMUV2.VALUE, short[][].class, "JSON",
		     "[[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "],"
		     + "[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "],"
		     + "[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "],"
		     + "[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "],"
		     + "[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "],"
		     + "[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "],"
		     + "[" + Short.MIN_VALUE + "," + Short.MIN_VALUE + "," + Short.MIN_VALUE + "]]",
		     "...",
		     "[[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "],"
		     + "[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "],"
		     + "[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "],"
		     + "[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "],"
		     + "[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "],"
		     + "[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "],"
		     + "[" + Short.MAX_VALUE + "," + Short.MAX_VALUE + "," + Short.MAX_VALUE + "]]"
);
   }
 
開發者ID:knr1,項目名稱:ch.bfh.mobicomp,代碼行數:21,代碼來源:AllDataEvent.java

示例9: AHandler

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
public AHandler(URI mqttURI, String deviceNameRootTopic, String identityString) throws Throwable {
this.mqttURI = mqttURI;
this.identityString = identityString;
this.deviceNameTopic = deviceNameRootTopic + "/" + getApplicationName() + "/" + identityString;;
this.intentTopic = getDeviceBaseTopic() + "/intent";
this.eventTopic = getDeviceBaseTopic() + "/event";
this.statusTopic = getDeviceBaseTopic() + "/status";

this.mqttClient = new MqttAsyncClient(mqttURI.toString(), identityString, new MemoryPersistence());
this.intentSet = new HashSet<>();
this.intentsMap = new HashMap<>();
this.eventMap = new HashMap<>();
this.statusMap = new HashMap<>();
this.addStatusClass(HandlerReadyStatus.class);
connectToMQTT();
   }
 
開發者ID:knr1,項目名稱:ch.bfh.mobicomp,代碼行數:17,代碼來源:AHandler.java

示例10: addEventClass

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
public void addEventClass(Class... classes) {
for (Class eventClass : classes) {
    try {
	eventMap.put(eventClass, (AnEvent) eventClass.getConstructor(AHandler.class, String.class, MqttAsyncClient.class
	     ).newInstance(this, eventTopic, mqttClient));
    } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
	Logger.getLogger(AHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}
if (mqttClient != null && mqttClient.isConnected()) {
    for (AnEvent event : eventMap.values()) {
	event.publishDescriptions();
    }
}

   }
 
開發者ID:knr1,項目名稱:ch.bfh.mobicomp,代碼行數:17,代碼來源:AHandler.java

示例11: addStatusClass

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
public void addStatusClass(Class... classes) {
for (Class statusClass : classes) {
    try {
	statusMap.put(statusClass, (AStatus) statusClass.getConstructor(AHandler.class, String.class, MqttAsyncClient.class
	      ).newInstance(this, statusTopic, mqttClient));
    } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
	Logger.getLogger(AHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
}
if (mqttClient != null && mqttClient.isConnected()) {
    for (AStatus status : statusMap.values()) {
	status.publishDescriptions();
    }
    getStatus(HandlerReadyStatus.class).update(REACHABLE, true);
}
   }
 
開發者ID:knr1,項目名稱:ch.bfh.mobicomp,代碼行數:17,代碼來源:AHandler.java

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

示例13: MqttStressTestClient

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
public MqttStressTestClient(ResultAccumulator results, String brokerUri, String deviceToken) throws MqttException {
    this.results = results;
    this.clientId = MqttAsyncClient.generateClientId();
    this.deviceToken = deviceToken;
    this.persistence = new MemoryPersistence();
    this.client = new MqttAsyncClient(brokerUri, clientId, persistence);
}
 
開發者ID:thingsboard,項目名稱:performance-tests,代碼行數:8,代碼來源:MqttStressTestClient.java

示例14: makeClientId

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
private String makeClientId ( final String clientId )
{
    if ( clientId != null )
    {
        return clientId;
    }

    return MqttAsyncClient.generateClientId ();
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:10,代碼來源:MqttInput.java

示例15: SensorsManager

import org.eclipse.paho.client.mqttv3.MqttAsyncClient; //導入依賴的package包/類
public SensorsManager(final MqttAsyncClient asyncClient, 
		final String boardCommandsTopic, final String boardDataBaseTopic, final String encoding) {
	this.boardCommandsTopic = boardCommandsTopic;
	this.boardDataBaseTopic = boardDataBaseTopic;
	this.encoding = encoding;
	this.asyncClient = asyncClient;
	// Build and save the topic names that we will use to publish the data from the sensors
	this.earthHumidityTopic = this.boardDataBaseTopic.concat(SENSOR_EARTH_HUMIDITY);
	final String sunlightDataBaseTopic = boardDataBaseTopic.concat(SENSOR_SUNLIGHT);
	this.visibleLightTopic = String.join(TOPIC_SEPARATOR, sunlightDataBaseTopic, "visiblelight");
	this.infraredLightTopic = String.join(TOPIC_SEPARATOR, sunlightDataBaseTopic, "ir");
	this.ultraVioletIndexTopic = String.join(TOPIC_SEPARATOR, sunlightDataBaseTopic, "uv");
}
 
開發者ID:PacktPublishing,項目名稱:MQTT-Essentials-A-Lightweight-IoT-Protocol,代碼行數:14,代碼來源:SensorsManager.java


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