Java Code Examples for org.eclipse.paho.client.mqttv3.MqttConnectOptions#setPassword()
The following examples show how to use
org.eclipse.paho.client.mqttv3.MqttConnectOptions#setPassword() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MqttService.java From PresencePublisher with MIT License | 6 votes |
public void sendMessages(List<Message> messages) throws MqttException { HyperLog.i(TAG, "Sending " + messages.size() + " messages to server"); boolean tls = sharedPreferences.getBoolean(USE_TLS, false); String clientCertAlias = sharedPreferences.getString(CLIENT_CERTIFICATE, null); String login = sharedPreferences.getString(USERNAME, ""); String password = securePreferences.getString(PASSWORD, ""); MqttClient mqttClient = new MqttClient(getMqttUrl(tls), Settings.Secure.ANDROID_ID, new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); options.setConnectionTimeout(5); if (!login.isEmpty() && !password.isEmpty()) { options.setUserName(login); options.setPassword(password.toCharArray()); } if (tls) { options.setSocketFactory(factory.getSslSocketFactory(clientCertAlias)); } mqttClient.connect(options); for (Message message : messages) { mqttClient.publish(message.getTopic(), message.getContent().getBytes(Charset.forName("UTF-8")), 1, false); } mqttClient.disconnect(5); mqttClient.close(true); HyperLog.i(TAG, "Sending messages was successful"); }
Example 2
Source File: MQTTTestClient.java From product-ei with Apache License 2.0 | 6 votes |
/** * Generate a MQTT client with given parameters * * @param brokerURL url of MQTT provider * @param userName username to connect to MQTT provider * @param password password to connect to MQTT provider * @param clientId unique id for the publisher/subscriber client * @throws MqttException in case of issue of connect/publish/consume */ public MQTTTestClient(String brokerURL, String userName, char[] password, String clientId) throws MqttException { this.brokerURL = brokerURL; //Store messages until server fetches them MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(JAVA_TMP_DIR + "/" + clientId); mqttClient = new MqttClient(brokerURL, clientId, dataStore); SimpleMQTTCallback callback = new SimpleMQTTCallback(); mqttClient.setCallback(callback); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(userName); connectOptions.setPassword(password); connectOptions.setCleanSession(true); mqttClient.connect(connectOptions); log.info("MQTTTestClient successfully connected to broker at " + this.brokerURL); }
Example 3
Source File: IotCoreClient.java From cloud-iot-core-androidthings with Apache License 2.0 | 6 votes |
private MqttConnectOptions configureConnectionOptions() throws JoseException { MqttConnectOptions options = new MqttConnectOptions(); // Note that the 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); // Cloud IoT Core ignores the user name field, but Paho requires a user name in order // to send the password field. We set the user name because we need the password to send a // JWT to authorize the device. options.setUserName("unused"); // generate the jwt password options.setPassword(mJwtGenerator.createJwt().toCharArray()); return options; }
Example 4
Source File: MqttAutoConfiguration.java From mqtt-spring-boot with MIT License | 6 votes |
@Bean public DefaultMqttPahoClientFactory clientFactory() { MqttConnectOptions connectOptions = new MqttConnectOptions(); String username = mqttProperties.getUsername(); String password = mqttProperties.getPassword(); if(username != null) { connectOptions.setUserName(username); } if (password != null) { connectOptions.setPassword(password.toCharArray()); } String[] serverURIs = mqttProperties.getServerURIs(); if (serverURIs == null || serverURIs.length == 0) { throw new NullPointerException("serverURIs can not be null"); } connectOptions.setCleanSession(mqttProperties.getCleanSession()); connectOptions.setKeepAliveInterval(mqttProperties.getKeepAliveInterval()); connectOptions.setServerURIs(serverURIs); DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setConnectionOptions(connectOptions); return factory; }
Example 5
Source File: MainActivity.java From Sparkplug with Eclipse Public License 1.0 | 6 votes |
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; }
Example 6
Source File: SparkplugListener.java From Sparkplug with Eclipse Public License 1.0 | 6 votes |
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(); } }
Example 7
Source File: AbstractMqttClient.java From xian with Apache License 2.0 | 6 votes |
/** * 连接mqtt server,并返回一个客户端对象,如果连接失败,那么返回null */ public MqttAsyncClient connectBroker() { LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 准备建立连接,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName)); try { sampleClient = new MqttAsyncClient("tcp://overriddenByMqttConnectOptions.setServerURIs:1883", getMqttClientId(), persistence); connOpts = new MqttConnectOptions(); connOpts.setAutomaticReconnect(true); connOpts.setServerURIs(serverURIs); connOpts.setUserName(userName); connOpts.setPassword(getPwd()); connOpts.setCleanSession(cleanSession); connOpts.setMaxInflight(1000 /**默认的值是10,对于我们来说这个值太小!*/); connOpts.setKeepAliveInterval(keepAliveInterval); sampleClient.setCallback(getCallback(this)); sampleClient.connect(connOpts).waitForCompletion(60 * 1000); LOG.info(String.format("mqtt=======客户端%s与rabbitMQ server: %s 建立连接完成,userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName)); return sampleClient; } catch (MqttException me) { throw new RuntimeException(String.format("mqtt=======客户端%s与rabbitMQ server: %s 连接失败!!! userName = %s", getMqttClientId(), JSON.toJSONString(serverURIs), userName), me); } }
Example 8
Source File: DeviceConfig.java From iot-java with Eclipse Public License 1.0 | 6 votes |
public MqttConnectOptions getMqttConnectOptions() throws NoSuchAlgorithmException, KeyManagementException { MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setConnectionTimeout(DEFAULT_CONNECTION_TIMEMOUT); if (getMqttPassword() != null) { connectOptions.setUserName(getMqttUsername()); connectOptions.setPassword(getMqttPassword().toCharArray()); } connectOptions.setCleanSession(this.options.mqtt.cleanStart); connectOptions.setKeepAliveInterval(this.options.mqtt.keepAlive); connectOptions.setMaxInflight(DEFAULT_MAX_INFLIGHT_MESSAGES); connectOptions.setAutomaticReconnect(true); if (!Arrays.asList(1883, 80).contains(options.mqtt.port)) { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); connectOptions.setSocketFactory(sslContext.getSocketFactory()); } return connectOptions; }
Example 9
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 5 votes |
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("\n> "); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); handleCommand(line); } } catch(Exception e) { e.printStackTrace(); } }
Example 10
Source File: MqttLogger.java From json-data-generator with Apache License 2.0 | 5 votes |
public MqttLogger(Map<String, Object> props) throws MqttException { String brokerHost = (String) props.get(BROKER_SERVER_PROP_NAME); Integer brokerPort = (Integer) props.get(BROKER_PORT_PROP_NAME); String brokerAddress = brokerHost + ":" + brokerPort.toString(); String clientId = (String) props.get(CLIENT_ID_PROP_NAME); String username = (String)props.get(USERNAME_PROP_NAME); String password = (String)props.get(PASSWORD_PROP_NAME); topic = (String) props.get(TOPIC_PROP_NAME); Integer _qos = (Integer) props.get(QOS_PROP_NAME); qos = null == _qos ? DEFAULT_QOS : _qos; mqttClient = new MqttClient(brokerAddress, null == clientId ? DEFAULT_CLIENT_ID : clientId); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); if (null != username) { connOpts.setUserName(username); if (null != password) { connOpts.setPassword(password.toCharArray()); } } log.debug("Connecting to broker: "+brokerAddress); mqttClient.connect(connOpts); log.debug("Connected"); }
Example 11
Source File: BlockingClient.java From mqtt-jmeter with Apache License 2.0 | 5 votes |
/** * Constructs an instance of the sample client wrapper * * @param brokerUrl the url of the server 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 userName the username to connect with * @param password the password for the user * @throws MqttException */ public BlockingClient(String brokerUrl, String clientId, boolean cleanSession, String userName, String password, int keepAlive) throws MqttException { this.brokerUrl = brokerUrl; String testPlanFileDir = System.getProperty("java.io.tmpdir") + File.separator + "mqtt" + File.separator + clientId + File.separator + Thread.currentThread().getId(); MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(testPlanFileDir); // Construct the connection options object that contains connection parameters // such as cleanSession and LWT MqttConnectOptions conOpt = new MqttConnectOptions(); conOpt.setCleanSession(cleanSession); if (password != null && !password.isEmpty()) { conOpt.setPassword(password.toCharArray()); } if (userName != null && !userName.isEmpty()) { conOpt.setUserName(userName); } // Setting keep alive time conOpt.setKeepAliveInterval(keepAlive); // Construct an MQTT blocking mode client client = new MqttClient(this.brokerUrl, clientId, dataStore); // Set this wrapper as the callback handler client.setCallback(this); // Connect to the MQTT server log.info("Connecting to " + brokerUrl + " with client ID '" + client.getClientId() + "' and cleanSession is " + String.valueOf(cleanSession) + " as a blocking client"); client.connect(conOpt); log.info("Connected"); }
Example 12
Source File: CustomAction.java From itracing2 with GNU General Public License v2.0 | 5 votes |
@Override public void run() { final Matcher matcher = pattern.matcher(this.domain); if (matcher.matches()) { String login = matcher.group(2); String password = matcher.group(3); String host = matcher.group(4); String port = matcher.group(5); String topic = matcher.group(6); if (port == null) { port = "1883"; } try { final MqttClient client = new MqttClient("tcp://" + host + ":" + port, MqttClient.generateClientId(), new MemoryPersistence() ); final MqttConnectOptions options = new MqttConnectOptions(); if (login != null && password != null) { options.setUserName(login); options.setPassword(password.toCharArray()); } client.connect(options); if (client.isConnected()) { client.publish(topic, payload.getBytes(), 0, false); client.disconnect(); } } catch (MqttException e) { Log.d(TAG, "exception", e); } } }
Example 13
Source File: MqttFacade.java From iaf with Apache License 2.0 | 5 votes |
public void configure() throws ConfigurationException { if (StringUtils.isEmpty(getClientId())) { throw new ConfigurationException("clientId must be specified"); } if (StringUtils.isEmpty(getBrokerUrl())) { throw new ConfigurationException("brokerUrl must be specified"); } if (StringUtils.isEmpty(getTopic())) { throw new ConfigurationException("topic must be specified"); } if (StringUtils.isEmpty(getPersistenceDirectory())) { throw new ConfigurationException("persistenceDirectory must be specified"); } connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(isCleanSession()); connectOptions.setAutomaticReconnect(isAutomaticReconnect()); connectOptions.setConnectionTimeout(getTimeout()); connectOptions.setKeepAliveInterval(getKeepAliveInterval()); connectOptions.setMqttVersion(MqttConnectOptions.MQTT_VERSION_DEFAULT); //Default: 0, V3.1: 3, V3.1.1: 4 if(!StringUtils.isEmpty(getAuthAlias()) || (!StringUtils.isEmpty(getUsername()) && !StringUtils.isEmpty(getPassword()))) { CredentialFactory credentialFactory = new CredentialFactory(getAuthAlias(), getUsername(), getPassword()); connectOptions.setUserName(credentialFactory.getUsername()); connectOptions.setPassword(credentialFactory.getPassword().toCharArray()); } MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(getPersistenceDirectory()); try { client = new MqttClient(brokerUrl, clientId, dataStore); } catch (MqttException e) { throw new ConfigurationException("Could not create client", e); } }
Example 14
Source File: TrafficService.java From AirMapSDK-Android with Apache License 2.0 | 4 votes |
/** * Initialize an TrafficService to receive traffic alerts and situational awareness * * @param context An Android Context */ public TrafficService(Context context) { String clientId = UUID.randomUUID().toString(); client = new MqttAndroidClient(context, mqttBaseUrl, clientId); client.setCallback(new MqttEventCallback()); options = new MqttConnectOptions(); options.setCleanSession(true); options.setKeepAliveInterval(15); options.setPassword(AirMap.getInstance().getAuthToken().toCharArray()); connectionState = ConnectionState.Disconnected; allTraffic = new CopyOnWriteArrayList<>(); //Thread safe list listeners = new ArrayList<>(); checkForUpdatedFlight = false; currentFlightCallback = new CurrentFlightAirMapCallback(); actionListener = new MqttActionCallback(); new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { clearOldTraffic(); updateTrafficProjections(); } }, 0, 1000); //Clear old traffic every second new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (checkForUpdatedFlight) { AirMap.getCurrentFlight(new AirMapCallback<AirMapFlight>() { @Override public void onSuccess(AirMapFlight response) { if (response != null && !response.getFlightId().equals(flightId)) { connect(); } } @Override public void onError(AirMapException e) { e.printStackTrace(); } }); } } }, 0, 1000 * 60); //Update current flight every minute handler = new Handler(Looper.getMainLooper()); }
Example 15
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
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(); } }
Example 16
Source File: MqttClientHandler.java From SI with BSD 2-Clause "Simplified" License | 4 votes |
private void connect(String brokerURL, String userName, String password, boolean ssl, boolean cleanSession) throws Exception { MqttConnectOptions connOpt = new MqttConnectOptions(); connOpt.setCleanSession(cleanSession); connOpt.setKeepAliveInterval(keepAliveInterval); if (userName != null) { connOpt.setUserName(userName); } if (password != null) { connOpt.setPassword(password.toCharArray()); } if(ssl) { // SSLContext sslContext = SSLContext.getInstance("TLS"); // TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // KeyStore keyStore = KeyStore.getInstance("JKS"); // InputStream in = new FileInputStream(KEY_STORE_LOCATION); // keyStore.load(in, KEY_STORE_PASSWORD.toCharArray()); // // trustManagerFactory.init(keyStore); // sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom()); // // connOpt.setSocketFactory(sslContext.getSocketFactory()); // connOpt.setSocketFactory(SSLSocketFactory.getDefault()); } // mqttClient = new MqttAsyncClient(brokerURL, clientID); mqttClient = new MqttClient(brokerURL, clientID); mqttClient.setCallback(this); mqttClient.connect(connOpt); // mqttClient.connect(connOpt, new IMqttActionListener() { // // @Override // public void onSuccess(IMqttToken asyncActionToken) { // // TODO Auto-generated method stub // try { // setSubscribe(); // } catch (Exception e) { // log.error("Subscription exception: ", e); // } // } // // @Override // public void onFailure(IMqttToken asyncActionToken, Throwable exception) { // // TODO Auto-generated method stub // // } // // }); log.debug("MQTT] connected to mqtt borker."); // pingSender = new TimerPingSender(); // pingSender.schedule((keepAliveInterval-5)*1000); // pingSender.start(); // MqttDeliveryToken token = new MqttDeliveryToken(getClientId()); // MqttPingReq pingMsg = new MqttPingReq(); // mqttClient. sendNoWait(pingMsg, token); }
Example 17
Source File: MqttListener.java From micro-integrator with Apache License 2.0 | 4 votes |
public void initAsyncClient() { mqttAsyncClient = confac.getMqttAsyncClient(this.name); MqttClientManager clientManager = MqttClientManager.getInstance(); String inboundIdentifier = clientManager .buildIdentifier(mqttAsyncClient.getClientId(), confac.getServerHost(), confac.getServerPort()); if (!clientManager.hasMqttCallback(inboundIdentifier)) { //registering callback for the first time connectOptions = new MqttConnectOptions(); connectOptions.setCleanSession(cleanSession); if (userName != null && password != null) { connectOptions.setUserName(userName); connectOptions.setPassword(password.toCharArray()); } if (socketFactory != null) { connectOptions.setSocketFactory(socketFactory); } mqttAsyncCallback = new MqttAsyncCallback(mqttAsyncClient, injectHandler, confac, connectOptions, mqttProperties); mqttAsyncCallback.setName(params.getName()); connectionConsumer = new MqttConnectionConsumer(connectOptions, mqttAsyncClient, confac, mqttProperties, name); mqttAsyncCallback.setMqttConnectionConsumer(connectionConsumer); mqttAsyncClient.setCallback(mqttAsyncCallback); //here we register the callback handler clientManager.registerMqttCallback(inboundIdentifier, mqttAsyncCallback); } else { //has previously registered callback we just update the reference //in other words has previous un-destroyed callback //this is a manually tenant loading case //should clear the previously set tenant loading flags for the inbound identifier clientManager.unRegisterInboundTenantLoadingFlag(inboundIdentifier); mqttAsyncCallback = clientManager.getMqttCallback(inboundIdentifier); mqttAsyncCallback.setName(params.getName()); connectOptions = mqttAsyncCallback.getMqttConnectionOptions(); connectionConsumer = mqttAsyncCallback.getMqttConnectionConsumer(); //but we need to update injectHandler due to recreation of synapse environment mqttAsyncCallback.updateInjectHandler(injectHandler); } }
Example 18
Source File: SparkplugRaspberryPiExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
/** * 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; }
Example 19
Source File: SparkplugExample.java From Sparkplug with Eclipse Public License 1.0 | 4 votes |
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(); } }
Example 20
Source File: MQTTClientBuilder.java From pentaho-kettle with Apache License 2.0 | 4 votes |
private MqttConnectOptions getOptions() { MqttConnectOptions options = new MqttConnectOptions(); if ( isSecure ) { setSSLProps( options ); } if ( !StringUtil.isEmpty( username ) ) { options.setUserName( username ); } if ( !StringUtil.isEmpty( password ) ) { options.setPassword( password.toCharArray() ); } if ( !StringUtil.isEmpty( keepAliveInterval ) ) { options.setKeepAliveInterval( Integer.parseInt( keepAliveInterval ) ); } if ( !StringUtil.isEmpty( maxInflight ) ) { options.setMaxInflight( Integer.parseInt( maxInflight ) ); } if ( !StringUtil.isEmpty( connectionTimeout ) ) { options.setConnectionTimeout( Integer.parseInt( connectionTimeout ) ); } if ( !StringUtil.isEmpty( cleanSession ) ) { options.setCleanSession( BooleanUtils.toBoolean( cleanSession ) ); } if ( !StringUtil.isEmpty( serverUris ) ) { options.setServerURIs( Arrays.stream( serverUris.split( ";" ) ).map( uri -> getProtocol() + uri ).toArray( String[]::new ) ); } if ( !StringUtil.isEmpty( mqttVersion ) ) { options.setMqttVersion( Integer.parseInt( mqttVersion ) ); } if ( !StringUtil.isEmpty( automaticReconnect ) ) { options.setAutomaticReconnect( BooleanUtils.toBoolean( automaticReconnect ) ); } return options; }