/** * get MqttClient by clientKey * @param clientKey * @return * @throws MqttException */ public static MqttClient getMqttClient(String serverURI, String clientId,StringRedisTemplate redisTemplate) throws MqttException{ String clientKey=serverURI.concat(clientId); if(clientMap.get(clientKey)==null){ lock.lock(); if(clientMap.get(clientKey)==null){ MqttClientPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(serverURI, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); MqttCallback callback = new IMMqttCallBack(client,redisTemplate); client.setCallback(callback); connOpts.setCleanSession(true); client.connect(connOpts); clientMap.put(clientKey, client); } lock.unlock(); } return clientMap.get(clientKey); }
public MqttClientPersistence getPersistence() { if (StringUtils.isEmpty(type) || type.equals("memory")) { log.info("Initializing default memory persistence!"); return new MemoryPersistence(); } else if (type.equals("file")) { if (StringUtils.isEmpty(path)) { log.info("Initializing default file persistence!"); return new MqttDefaultFilePersistence(); } else { log.info("Initializing file persistence using directory: {}", path); return new MqttDefaultFilePersistence(path); } } else { log.error("Unknown persistence option: {}. Only 'memory' and 'file' are supported at the moment!", type); throw new IllegalArgumentException("Unknown persistence option: " + type + "!"); } }
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; } }
private void initializeMqttClient() throws MqttException, IOException, NoSuchAlgorithmException, InvalidKeySpecException { mqttClient = new MqttClient(cloudIotOptions.getBrokerUrl(), cloudIotOptions.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(CloudIotOptions.UNUSED_ACCOUNT_NAME); // generate the jwt password options.setPassword(mqttAuth.createJwt(cloudIotOptions.getProjectId())); mqttClient.connect(options); mReady.set(true); }
@Bean public MqttPahoClientFactory mqttClientFactory() { DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory(); factory.setServerURIs(mqttProperties.getUrl()); factory.setUserName(mqttProperties.getUsername()); factory.setPassword(mqttProperties.getPassword()); factory.setCleanSession(mqttProperties.isCleanSession()); factory.setConnectionTimeout(mqttProperties.getConnectionTimeout()); factory.setKeepAliveInterval(mqttProperties.getKeepAliveInterval()); if (ObjectUtils.nullSafeEquals(mqttProperties.getPersistence(), "file")) { factory.setPersistence(new MqttDefaultFilePersistence(mqttProperties.getPersistenceDirectory())); } else if (ObjectUtils.nullSafeEquals(mqttProperties.getPersistence(), "memory")) { factory.setPersistence(new MemoryPersistence()); } return factory; }
@Test public void testMQtt() throws Exception { CountDownLatch latch = new CountDownLatch(1); MqttClient client = new MqttClient("tcp://localhost:" + MQTT_PORT, MqttClient.generateClientId(), new MemoryPersistence()); client.connect(); MqttComponent mqtt = new MqttComponent(); mqtt.client = client; Publisher<byte[]> fromTopic = mqtt.from("input", byte[].class); Subscriber<byte[]> toTopic = mqtt.to("output", byte[].class); Flux.from(fromTopic) .log() .subscribe(toTopic); client.subscribe("output", (topic, message) -> { result = new Integer(new String(message.getPayload())); latch.countDown(); }); client.publish("input", new MqttMessage(new Integer(2).toString().getBytes())); client.publish("input", new MqttMessage(new Integer(2).toString().getBytes())); latch.await(100, TimeUnit.SECONDS); Assert.assertEquals(2, result, 0.1); client.disconnect(); client.close(); }
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(); } }
/** * * @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); } }
@Bean public MqttPahoClientFactory mqttClientFactory() { AuthConfiguration.AdminUser defaultUser = raptorConfiguration.getAuth().getServiceUser(); if (defaultUser == null) { throw new RuntimeException("Missing service user. Review raptor.yml configuration file under auth.users section"); } DispatcherConfiguration dispatcherConfig = raptorConfiguration.getDispatcher(); DefaultMqttPahoClientFactory f = new DefaultMqttPahoClientFactory(); log.debug("Using local broker user {}", defaultUser.getUsername()); f.setUserName(defaultUser.getUsername()); f.setPassword(defaultUser.getPassword()); f.setServerURIs(dispatcherConfig.getUri()); f.setCleanSession(true); f.setPersistence(new MemoryPersistence()); return f; }
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); } }
@Test public void disconnectedByClient(TestContext context) { Async async = context.async(); try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence); client.connect(); client.disconnect(); // give more time to the MqttClient to update its connection state this.vertx.setTimer(1000, t1 -> { async.complete(); }); async.await(); context.assertTrue(!client.isConnected() && !this.endpoint.isConnected()); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }
@Test public void refusedBadUsernamePassword(TestContext context) { this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD; try { MemoryPersistence persistence = new MemoryPersistence(); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName("wrong_username"); options.setPassword("wrong_password".toCharArray()); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence); client.connect(options); context.fail(); } catch (MqttException e) { context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_FAILED_AUTHENTICATION); } }
@Test public void refusedUnacceptableProtocolVersion(TestContext context) { this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_UNACCEPTABLE_PROTOCOL_VERSION; try { MemoryPersistence persistence = new MemoryPersistence(); MqttConnectOptions options = new MqttConnectOptions(); // trying the old 3.1 options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence); client.connect(options); context.fail(); } catch (MqttException e) { context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_PROTOCOL_VERSION); } }
@Test public void connectionAlreadyAccepted(TestContext context) throws Exception { this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED; MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence); client.connect(); try { // try to accept a connection already accepted this.endpoint.accept(false); context.fail(); } catch (IllegalStateException e) { // Ok } }
@Test public void refusedClientIdZeroBytes(TestContext context) { this.expectedReturnCode = MqttConnectReturnCode.CONNECTION_REFUSED_IDENTIFIER_REJECTED; try { MemoryPersistence persistence = new MemoryPersistence(); MqttConnectOptions options = new MqttConnectOptions(); options.setCleanSession(false); options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "", persistence); client.connect(options); context.fail(); } catch (MqttException e) { context.assertTrue(e.getReasonCode() == MqttException.REASON_CODE_INVALID_CLIENT_ID); context.assertNotNull(rejection); } }
@Test public void testInvalidClientIdentifier(TestContext context) throws Exception { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "invalid-id-with-24-chars", persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setMqttVersion(MQTT_VERSION_3_1); try { client.connect(options); context.assertTrue(false); } catch (MqttException ignore) { context.assertTrue(true); } }
@Test public void testValidClientIdentifier(TestContext context) throws Exception { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "id-madeof-23-characters", persistence); MqttConnectOptions options = new MqttConnectOptions(); options.setMqttVersion(MQTT_VERSION_3_1); try { client.connect(options); context.assertTrue(true); } catch (MqttException ignore) { context.assertTrue(false); } }
private void subscribe(TestContext context, String topic, int expectedQos) { this.async = context.async(); try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_SERVER_HOST, MQTT_SERVER_PORT), "12345", persistence); client.connect(); String[] topics = new String[]{topic}; int[] qos = new int[]{expectedQos}; // after calling subscribe, the qos is replaced with granted QoS that should be the same client.subscribe(topics, qos); this.async.await(); context.assertTrue(qos[0] == expectedQos); } catch (MqttException e) { context.assertTrue(!topic.equals(MQTT_TOPIC_FAILURE) ? false : true); e.printStackTrace(); } }
/** * 服务初始化回调函数 */ @Override public void onCreate() { super.onCreate(); /**创建一个Handler*/ mConnHandler = new Handler(); try { /**新建一个本地临时存储数据的目录,该目录存储将要发送到服务器的数据,直到数据被发送到服务器*/ mDataStore = new MqttDefaultFilePersistence(getCacheDir().getAbsolutePath()); } catch(Exception e) { e.printStackTrace(); /**新建一个内存临时存储数据的目录*/ mDataStore = null; mMemStore = new MemoryPersistence(); } /**连接的参数选项*/ mOpts = new MqttConnectOptions(); /**删除以前的Session*/ mOpts.setCleanSession(MQTT_CLEAN_SESSION); // Do not set keep alive interval on mOpts we keep track of it with alarm's /**定时器用来实现心跳*/ mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); /**管理网络连接*/ mConnectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); }
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); } }
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"); }
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(); } }
public CopyOfMyMqttCloudClient(String cloudTopic, String cloudBrokerAddress, String clientId) { this._cloudTopic = cloudTopic; this._cloudBrokerAddress = cloudBrokerAddress; this._clientId = clientId; MemoryPersistence persistence = new MemoryPersistence(); try { this._mqCloudClient = new MqttClient(this._cloudBrokerAddress, "sfdf", 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(); } }
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); } }
private void mqttReceiver(TestContext context, String topic, int qos) { try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), CLIENT_ID, persistence); client.connect(); client.subscribe(topic, qos, (t, m) -> { LOG.info("topic: {}, message: {}", t, m); this.async.complete(); }); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }
@Test public void subscribe(TestContext context) { try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), SUBSCRIBER_ID, persistence); client.connect(); String[] topics = new String[]{ MQTT_TOPIC }; int[] qos = new int[]{ 1 }; // after calling subscribe, the qos is replaced with granted QoS that should be the same client.subscribe(topics, qos); context.assertTrue(qos[0] == 1); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }
private void mqttReceiver(TestContext context, String topic, int qos) { try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("ssl://%s:%d", MQTT_BIND_ADDRESS, MQTT_TLS_LISTEN_PORT), SUBSCRIBER_ID, persistence); client.connect(); client.subscribe(topic, qos, (t, m) -> { LOG.info("topic: {}, message: {}", t, m); this.async.complete(); }); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }
private void mqttReceiver(TestContext context, String topic, int qos) { try { MemoryPersistence persistence = new MemoryPersistence(); MqttClient client = new MqttClient(String.format("tcp://%s:%d", MQTT_BIND_ADDRESS, MQTT_LISTEN_PORT), SUBSCRIBER_ID, persistence); client.connect(); client.subscribe(topic, qos, (t, m) -> { LOG.info("topic: {}, message: {}", t, m); this.receivedQos = m.getQos(); this.async.complete(); }); } catch (MqttException e) { context.assertTrue(false); e.printStackTrace(); } }
public void init() throws MqttException { try { String url = mqttProperties.getHostname() + ":" + mqttProperties.getPort(); LOGGER.info("Opening MQTT connection: '{}'", url); LOGGER.info("properties: {}", mqttProperties); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(mqttProperties.getUsername()); connectOptions.setPassword(mqttProperties.getPassword().toCharArray()); connectOptions.setCleanSession(false); client = new MqttClient(url, mqttProperties.getClientName(), new MemoryPersistence()); client.setCallback(onMessageArrived); client.connect(connectOptions); client.subscribe(mqttProperties.getTopic()); } catch (MqttException e) { LOGGER.error(e.getMessage(), e); throw e; } }
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()); } }
private void createMQTTConnection() throws TransportConfigException { _connOpts = new MqttConnectOptions(); _connOpts.setCleanSession(true); _connOpts.setKeepAliveInterval(30); if (_username != null && !_username.isEmpty()) _connOpts.setUserName(_username); if (_password != null && !_password.isEmpty()) _connOpts.setPassword(_password.toCharArray()); _persistence = new MemoryPersistence(); try { _mqttClient = new MqttClient(_broker, _clientId, _persistence); LOGGER.fine("Connecting to broker [" + _broker + "]"); _mqttClient.connect(_connOpts); _topic = _mqttClient.getTopic(_topicName); LOGGER.fine("Connected MQTT Client [" + _clientId + "] to broker [" + _broker + "]"); } catch (MqttException me) { throw new TransportConfigException("Error connecting [" + _clientId + "] broker [" + _broker + "]", me); } }
private void connectMqtt() throws MqttException { String url = (ssl ? "ssl://" : "tcp://") + host + ":" + Integer.toString(port); mqttClient = new MqttClient(url, MqttClient.generateClientId(), new MemoryPersistence()); MqttConnectOptions options = new MqttConnectOptions(); // Connect with username and password if both are available. if (username != null && password != null && !username.isEmpty() && password.length > 0) { options.setUserName(username); options.setPassword(password); } if (ssl) { // Support TLS only (1.0-1.2) as even SSL 3.0 has well known exploits java.util.Properties sslProperties = new java.util.Properties(); sslProperties.setProperty("com.ibm.ssl.protocol", "TLS"); options.setSSLProperties(sslProperties); } options.setCleanSession(true); mqttClient.connect(options); }
public void start() { MemoryPersistence persistence = new MemoryPersistence(); try { String serverURI = "tcp://"+brokerAddress.getHostString()+":"+brokerAddress.getPort(); mqttClient = new MqttClient(serverURI, endpointID, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(true); LOG.info("Connecting endpoint "+ endpointID + " to broker: "+serverURI); mqttClient.connect(connOpts); LOG.info("Connected"); } catch(MqttException me) { LOG.error("reason "+me.getReasonCode()); LOG.error("msg "+me.getMessage()); LOG.error("loc "+me.getLocalizedMessage()); LOG.error("cause "+me.getCause()); LOG.error("excep "+me); me.printStackTrace(); } }
private MqttClient lookupClientConnection() { int clientIndex = PipeReader.readInt(input, MQTTFROM.FIELD_CLIENT_INDEX_LOC); MqttClient client = connnection[clientIndex]; if (null==client) { String clientId = PipeReader.readASCII(input, MQTTFROM.FIELD_CLIENT_ID_LOC, new StringBuilder()).toString(); assert(clientId.length()<=23); String server = PipeReader.readASCII(input, MQTTFROM.FIELD_SERVER_URI_LOC, new StringBuilder()).toString(); try { client = connnection[clientIndex] = new MqttClient(server, clientId, new MemoryPersistence()); // client.connect(connOptions); } catch (MqttException e) { throw new RuntimeException(e); }//must be smaller than 23 chars } assert(PipeReader.readASCII(input, MQTTFROM.FIELD_CLIENT_ID_LOC, new StringBuilder()).toString().equals(client.getClientId())); assert(PipeReader.readASCII(input, MQTTFROM.FIELD_SERVER_URI_LOC, new StringBuilder()).toString().equals(client.getServerURI())); return client; }
private synchronized MqttClient _getInstance() throws MqttException, SystemException { if (_mqttClient == null) { String serverURI = PrefsPropsUtil.getString( PortletPropsKeys.MQTT_BROKER_URL, PortletPropsValues.MQTT_BROKER_URL); String clientID = PrefsPropsUtil.getString( PortletPropsKeys.MQTT_BROKER_CLIENTID, PortletPropsValues.MQTT_BROKER_CLIENTID); MemoryPersistence persistence = new MemoryPersistence(); _mqttClient = new MqttClient(serverURI, clientID, persistence); _mqttClient.setCallback(this); } return _mqttClient; }
@Test public void testMqtt() throws MqttException, InterruptedException { final CountDownLatch messageReceived = new CountDownLatch(1); MqttClient client = new MqttClient(mqttServer.getConnectString(), UUID.randomUUID().toString(), new MemoryPersistence()); client.connect(); client.setCallback(new MqttCallback() { @Override public void connectionLost(Throwable cause) { } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { messageReceived.countDown(); } @Override public void deliveryComplete(IMqttDeliveryToken token) { } }); client.subscribe(TOPIC_NAME_TEST); client.publish(TOPIC_NAME_TEST, UUID.randomUUID().toString().getBytes(), 0, false); assertTrue(messageReceived.await(MQTT_TIMEOUT_MS, TimeUnit.MILLISECONDS)); client.disconnect(); }
public void init() throws MqttException { try { String url = mqttProperties.getHostname() + ":" + mqttProperties.getPort(); LOGGER.info("Opening MQTT connection: '{}'", url); MqttConnectOptions connectOptions = new MqttConnectOptions(); connectOptions.setUserName(mqttProperties.getUsername()); connectOptions.setPassword(mqttProperties.getPassword().toCharArray()); client = new MqttClient(url, mqttProperties.getTopic(), new MemoryPersistence()); client.setCallback(onFeatureVectorArrived); client.connect(connectOptions); client.subscribe(mqttProperties.getTopic()); } catch (MqttException e) { LOGGER.error(e.getMessage(), e); throw e; } }