@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(); }
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"); }
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); } }
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); } }
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()); } }
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 + "]]" ); }
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(); }
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(); } } }
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); } }
@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); }
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); } }
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); }
private String makeClientId ( final String clientId ) { if ( clientId != null ) { return clientId; } return MqttAsyncClient.generateClientId (); }
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"); }
@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); }
public void connect() { try { client = new MqttAsyncClient( (configuration.isSsl() ? "ssl" : "tcp") + "://" + configuration.getHost() + ":" + configuration.getPort(), getClientId(), new MemoryPersistence()); client.setCallback(this); clientOptions = new MqttConnectOptions(); clientOptions.setCleanSession(true); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); clientOptions.setSocketFactory(sslContext.getSocketFactory()); if (configuration.isSsl() && !StringUtils.isEmpty(configuration.getTruststore())) { Properties sslProperties = new Properties(); sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORE, configuration.getTruststore()); sslProperties.put(SSLSocketFactoryFactory.TRUSTSTOREPWD, configuration.getTruststorePassword()); sslProperties.put(SSLSocketFactoryFactory.TRUSTSTORETYPE, "JKS"); sslProperties.put(SSLSocketFactoryFactory.CLIENTAUTH, false); clientOptions.setSSLProperties(sslProperties); } configuration.getCredentials().configure(clientOptions); checkConnection(); if (configuration.getAttributeUpdates() != null) { configuration.getAttributeUpdates().forEach( mapping -> gateway.subscribe(new AttributesUpdateSubscription(mapping.getDeviceNameFilter(), this))); } if (configuration.getServerSideRpc() != null) { configuration.getServerSideRpc() .forEach(mapping -> gateway.subscribe(new RpcCommandSubscription(mapping.getDeviceNameFilter(), this))); } } catch (MqttException | NoSuchAlgorithmException | KeyManagementException e) { log.error("[{}:{}] MQTT broker connection failed!", configuration.getHost(), configuration.getPort(), e); throw new RuntimeException("MQTT broker connection failed!", e); } }
private boolean doConnectBroker() { try { LOG.debug("{} > connect..", url); final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions(); mqttConnectOptions.setUserName("admin"); mqttConnectOptions.setPassword("admin".toCharArray()); mqttConnectOptions.setCleanSession(true); mqttConnectOptions.setWill(pubTopic2Mqtt, "Bye, bye Baby!".getBytes(), 0, false); // client final String tmpDir = System.getProperty("java.io.tmpdir"); final MqttDefaultFilePersistence dataStore = new MqttDefaultFilePersistence(tmpDir); LOG.info("creating MqttAsyncClient for {} and {}", url, clientId); mqttAsyncClient = new MqttAsyncClient(url, clientId, dataStore); // callback mqttAsyncClient.setCallback(this); // connect mqttAsyncClient.connect(mqttConnectOptions).waitForCompletion(); // subscriptions for (final String subTopic : subTopics) { LOG.info("client {} subscribing to {}", clientId, subTopic); mqttAsyncClient.subscribe(subTopic, 0); } LOG.info("{} > mqtt connection established for {}.", url, clientId); return true; } catch (final Throwable throwable) { LOG.error("{} > connection failed. ({})", url, throwable.getMessage()); close(); return false; } }
/** * Default constructor * * @param serverUri the Server URI to connect to * @param clientId the Client ID to connect as * @param connectionType the {@link MqttClientConnectType} this instance will be used as * @param clientPersistence TODO: add description * @throws IllegalArgumentException if the {@code serverUri} is blank or null, the * {@code clientId} is blank or null, or if the {@code connectionType} value is null * @throws MqttException if the underlying {@link MqttAsyncClient} instance cannot be created */ public PahoAsyncMqttClientService(final String serverUri, final String clientId, final MqttClientConnectionType connectionType, final MqttClientPersistence clientPersistence) throws MqttException { super(connectionType); Assert.hasText(serverUri, "'serverUri' must be set!"); Assert.hasText(clientId, "'clientId' must be set!"); this.clientPersistence = clientPersistence; mqttClient = new MqttAsyncClient(serverUri, clientId, this.clientPersistence); mqttClient.setCallback(this); }
private void createMqttAsyncClient(Properties deviceProps) throws MqttException, NoSuchAlgorithmException, KeyManagementException { StringBuilder serverURI = new StringBuilder(); StringBuilder clientId = new StringBuilder(); serverURI.append("ssl://") .append(trimedValue(deviceProps.getProperty("Organization-ID"))) .append(".messaging.internetofthings.ibmcloud.com:8883"); clientId.append("d:") .append(trimedValue(deviceProps.getProperty("Organization-ID"))) .append(":") .append(trimedValue(deviceProps.getProperty("Device-Type"))) .append(":") .append(trimedValue(deviceProps.getProperty("Device-ID"))); MqttConnectOptions conOpt = new MqttConnectOptions(); conOpt.setCleanSession(false); conOpt.setUserName("use-token-auth"); conOpt.setPassword(trimedValue(deviceProps.getProperty("Authentication-Token")).toCharArray()); SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, null, null); conOpt.setSocketFactory(sslContext.getSocketFactory()); mqttAsyncClient = new MqttAsyncClient(serverURI.toString(), clientId.toString()); System.out.println("Trying to connect to URI -> "+serverURI.toString() +" ClientID: "+clientId.toString()); System.out.println("Username : "+conOpt.getUserName()); System.out.println("password : "+new String(conOpt.getPassword())); mqttAsyncClient.connect(conOpt); }
private void itCanPubAndSubToBroker(final String brokerUrl) throws Throwable { // Create async MQTT clients final MqttAsyncClient pubClient = new MqttAsyncClient(brokerUrl, CLIENT_ID + "-pub"); AsyncPahoUtils.connect(pubClient); final MqttAsyncClient subClient = new MqttAsyncClient(brokerUrl, CLIENT_ID + "-sub"); AsyncPahoUtils.connect(subClient); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<MqttMessage> msg = new AtomicReference<MqttMessage>(); // Subscribe final IMqttMessageListener messageListener = new IMqttMessageListener() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { msg.set(message); latch.countDown(); } }; AsyncPahoUtils.subscribe(subClient, TOPIC, messageListener); // Publish the sensor data final byte[] expectedPayload = new byte[] { 'a', 'b', 'c' }; AsyncPahoUtils.publish(pubClient, TOPIC, expectedPayload); // Await message publish and receipt latch.await(); // Get the message received by the callback final MqttMessage receivedMessage = msg.get(); Assert.assertNotNull(receivedMessage); Assert.assertNotNull(receivedMessage.getPayload()); Assert.assertArrayEquals(expectedPayload, receivedMessage.getPayload()); // Close the clients AsyncPahoUtils.disconnect(pubClient); AsyncPahoUtils.disconnect(subClient); }
@Test public void testPushMqttRpcData() throws Exception { String clientId = MqttAsyncClient.generateClientId(); MqttAsyncClient client = new MqttAsyncClient(MQTT_URL, clientId); MqttConnectOptions options = new MqttConnectOptions(); options.setUserName(accessToken); client.connect(options); Thread.sleep(3000); MqttMessage message = new MqttMessage(); message.setPayload("{\"key1\":\"value1\", \"key2\":true, \"key3\": 3.0, \"key4\": 4}".getBytes()); client.publish("v1/devices/me/telemetry", message); String deviceId = savedDevice.getId().getId().toString(); Thread.sleep(1000); List<String> actualKeys = doGetAsync("/api/plugins/telemetry/DEVICE/" + deviceId + "/keys/timeseries", List.class); Set<String> actualKeySet = new HashSet<>(actualKeys); List<String> expectedKeys = Arrays.asList("key1", "key2", "key3", "key4"); Set<String> expectedKeySet = new HashSet<>(expectedKeys); assertEquals(expectedKeySet, actualKeySet); String getTelemetryValuesUrl = "/api/plugins/telemetry/DEVICE/" + deviceId + "/values/timeseries?keys=" + String.join(",", actualKeySet); Map<String, List<Map<String, String>>> values = doGetAsync(getTelemetryValuesUrl, Map.class); assertEquals("value1", values.get("key1").get(0).get("value")); assertEquals("true", values.get("key2").get(0).get("value")); assertEquals("3.0", values.get("key3").get(0).get("value")); assertEquals("4", values.get("key4").get(0).get("value")); }
@NonNull public static IMqttAsyncClient client( @NonNull final String url, @NonNull final String id, @NonNull final MqttClientPersistence persistence) throws MqttException { return new MqttAsyncClient(url, id, persistence); }
public BaseAsyncClient(String brokerUrl, String clientId) throws MqttException { mMqttClient = new MqttAsyncClient(brokerUrl, clientId); // add runtime hook. Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { logger.info("Close " + clientId); IOUtils.closeMqttClientQuite(mMqttClient); logger.info(clientId + " closed"); } }); }
/** * Initializes an object that can be used for sending messages to the broker * which is running on localhost. */ public MoquetteProxyContext() { try { this.dataStore = new MqttDefaultFilePersistence(); this.client = new MqttAsyncClient(getFullMqttBrokerUrl(), MQTT_CLIENT_NAME, dataStore); } catch (MqttException e) { // The exception is thrown when there is an unrecognized MQTT Message in the persistant // storage location. Messages are removed from persistant storage once the broker // sends the message to subscribers (does not wait for confirmation) throw new IllegalStateException("Unrecognized message in the persistent data store location." + " Consider clearing the default persistent storage location."); } }
/** * Initializes an object that can be used for sending messages to the broker * which is running on localhost. * * @param persistenceDir the location of the persistent storage used by the MQTT client library. */ public MoquetteProxyContext(String persistenceDir) { try { dataStore = new MqttDefaultFilePersistence(checkNotNull(persistenceDir)); client = new MqttAsyncClient(getFullMqttBrokerUrl(), MQTT_CLIENT_NAME, dataStore); } catch (MqttException e) { // The exception is thrown when there is an unrecognized MQTT Message in the persistant // storage location. Messages are removed from persistant storage once the broker // sends the message to subscribers (does not wait for confirmation) throw new IllegalStateException("Unrecognized message in the persistent data store location." + " Consider clearing the default persistent storage location."); } }
public void delayedSetupTest(JavaSamplerContext context){ log.debug(myname + ">>>> in setupTest"); host = context.getParameter("HOST"); throttle = Integer.parseInt((context.getParameter("PUBLISHER_THROTTLE"))); acksTimeout = Integer.parseInt((context.getParameter("PUBLISHER_ACKS_TIMEOUT"))); //System.out.println("Publisher acks timeout: " + acksTimeout); clientId = context.getParameter("CLIENT_ID"); if("TRUE".equalsIgnoreCase(context.getParameter("RANDOM_SUFFIX"))){ clientId= MqttPubSub.getClientId(clientId,Integer.parseInt(context.getParameter("SUFFIX_LENGTH"))); } try { log.debug("Host: " + host + "clientID: " + clientId); client = new MqttAsyncClient(host, clientId, new MemoryPersistence()); } catch (MqttException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); //options.setCleanSession(false); options.setCleanSession(Boolean.parseBoolean((context.getParameter("CLEAN_SESSION")))); //System.out.println("Pubs cleansession ====> " + context.getParameter("CLEAN_SESSION")); options.setKeepAliveInterval(0); timeout = Integer.parseInt((context.getParameter("CONNECTION_TIMEOUT"))); myname = context.getParameter("SAMPLER_NAME"); String user = context.getParameter("USER"); String pwd = context.getParameter("PASSWORD"); if (user != null) { options.setUserName(user); if ( pwd!=null ) { options.setPassword(pwd.toCharArray()); } } clientConnect(timeout); client.setCallback(this); }
private Client register(ExpandedConnectionParams connectionParams, int generatedClientNo) throws MqttException { CacheKey cacheKey = new CacheKey(connectionParams, generatedClientNo); String clientId; if (connectionParams.isGeneratedId()) { clientId = MqttAsyncClient.generateClientId(); } else{ clientId = connectionParams.fixedId; } MqttAsyncClientEx clientObj = new MqttAsyncClientEx(connectionParams.getActualServerUri(), clientId, new MemoryPersistence()); Client newClient = new Client(clientObj, createConnectionOptions(connectionParams), !connectionParams.cleanSession && !connectionParams.isGeneratedId()); map.put(cacheKey, newClient); return newClient; }
@Inject public Engine(final Gson gson, final Registry registry, final Config config, final MqttClientPersistence persistence) throws MqttException { String topicPrefix = config.getString(Settings.TOPIC_PREFIX).replaceFirst("^/+", ""); if (!topicPrefix.isEmpty() && !topicPrefix.endsWith("/")) { topicPrefix += "/"; } this.topicPrefix = topicPrefix; this.reconnectInterval = Duration.ofSeconds(config.getLong(Settings.RECONNECT_INTERVAL)); this.gson = Objects.requireNonNull(gson); this.registry = Objects.requireNonNull(registry); this.client = new MqttAsyncClient( config.getString(Settings.BROKER_URL), config.getString(Settings.CLIENT_ID), persistence ); this.client.setCallback(this); { final String username = config.getString(Settings.BROKER_USERNAME); if (username != null && !username.isEmpty()) { this.options.setUserName(username); } } { final String password = config.getString(Settings.BROKER_PASSWORD); if (password != null && !password.isEmpty()) { this.options.setPassword(password.toCharArray()); } } this.options.setCleanSession(true); }
/** * Constructs an instance of the sample client wrapper * * @param brokerUrl * the url 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 quietMode * whether debug should be printed to standard out * @param userName * the username to connect with * @param password * the password for the user * @throws MqttException if an error happens */ public SampleAsyncCallback(String brokerUrl, String clientId, boolean cleanSession, boolean quietMode, String userName, String password) throws MqttException { this.brokerUrl = brokerUrl; this.quietMode = quietMode; this.clean = cleanSession; this.password = password; this.userName = userName; try { // Construct the object that contains connection parameters // such as cleansession and LWAT conOpt = new MqttConnectOptions(); conOpt.setCleanSession(clean); if (password != null) { conOpt.setPassword(this.password.toCharArray()); } if (userName != null) { conOpt.setUserName(this.userName); } // Construct the MqttClient instance client = new MqttAsyncClient(this.brokerUrl, clientId); // Set this wrapper as the callback handler client.setCallback(this); } catch (MqttException e) { e.printStackTrace(); log("Unable to set up client: " + e.toString()); System.exit(1); } }
@Override public boolean initialize() { try { addressBean = getActiveAddressBean( ); serverURI = addressBean.getPredicateValue("uri"); if ( serverURI == null || serverURI.trim().length() == 0 ) { logger.error( "The uri parameter is missing from the MQTT wrapper, initialization failed." ); return false; } clientID = addressBean.getPredicateValue("client_id"); if ( clientID == null || clientID.trim().length() == 0 ) { logger.error( "The client_id parameter is missing from the MQTT wrapper, initialization failed." ); return false; } topic = addressBean.getPredicateValue("topic"); if ( topic == null || topic.trim().length() == 0 ) { logger.error( "The topic parameter is missing from the MQTT wrapper, initialization failed." ); return false; } qos = addressBean.getPredicateValueAsInt("qos", 0); if (qos < 0 || qos > 2) { logger.error( "The qos parameter from MQTT wrapper can be 0, 1 or 2 (found "+qos+"), initialization failed." ); return false; } client = new MqttAsyncClient(serverURI, clientID); client.setCallback(this); client.connect(); }catch (Exception e){ logger.error("Error in instanciating MQTT broker with "+topic+" @ "+serverURI,e); return false; } return true; }
@Override public IMqttAsyncClient create() throws Exception { String broker = conf.getConf(id, MqttClientConf.F_mqtt_broker); MqttAsyncClient mqttClient = new MqttAsyncClient(broker, createClientId(), createPersistence()); mqttClient.connect(createConnectOptions()).waitForCompletion(); return mqttClient; }
public IMqttDeliveryToken publish(String messagePropertyName, MqttMessage mqttMessage, MqttAsyncClient mqttClient) { mqttMessage.setQos(1); mqttMessage.setRetained(true); try { return mqttClient.publish(topic + "/" + name + "/" + messagePropertyName, mqttMessage); } catch (Exception ex) { Logger.getLogger(MQTT2TF.class.getName()).log(Level.SEVERE, null, ex); } return null; }
protected IMqttDeliveryToken update(MqttAsyncClient mqttClient, String property, Object value) { synchronized (this) { if (mqttDeliveryToken == null || mqttDeliveryToken.isComplete()) { try { mqttDeliveryToken = publish(property, toJSONMQTTMessage(value), mqttClient); return mqttDeliveryToken; } catch (Exception ex) { System.out.println("During publish, the following exception occured:" + ex.getStackTrace()); } } return null; } }
public CallbackThresholdStatus(AHandler deviceHandler, String statusTopic, MqttAsyncClient mqttClient) { super(deviceHandler, statusTopic, "callbackThreshold", mqttClient); super.addDescription(Accelerometer.THRESHOLD_OPTION, Character.class, "JSON", "x", "o", "i", "s", "g"); super.addDescription(Accelerometer.THRESHOLD_MIN_X, Short.class, "JSON", "" + Short.MIN_VALUE, "...", "4095"); super.addDescription(Accelerometer.THRESHOLD_MIN_Y, Short.class, "JSON", "" + Short.MIN_VALUE, "...", "4095"); super.addDescription(Accelerometer.THRESHOLD_MIN_Z, Short.class, "JSON", "" + Short.MIN_VALUE, "...", "4095"); super.addDescription(Accelerometer.THRESHOLD_MAX_X, Short.class, "JSON", "" + Short.MIN_VALUE, "...", "4095"); super.addDescription(Accelerometer.THRESHOLD_MAX_Y, Short.class, "JSON", "" + Short.MIN_VALUE, "...", "4095"); super.addDescription(Accelerometer.THRESHOLD_MAX_Z, Short.class, "JSON", "" + Short.MIN_VALUE, "...", "4095"); }
public ColorEvent(AHandler deviceHandler, String eventTopic, MqttAsyncClient mqttClient) { super(deviceHandler, eventTopic, "color", mqttClient); super.addDescription(Color.RED, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.GREEN, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.BLUE, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.CLEAR, Integer.class, "JSON", "0", "...", "65535"); }
public ColorCallbackThresholdStatus(AHandler deviceHandler, String statusTopic, MqttAsyncClient mqttClient) { super(deviceHandler, statusTopic, "colorCallbackThreshold", mqttClient); super.addDescription(Color.THRESHOLD_OPTION, Character.class, "JSON", "x", "o", "i", "s", "g"); super.addDescription(Color.THRESHOLD_MIN_R, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MAX_R, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MIN_G, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MAX_G, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MIN_B, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MAX_B, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MIN_C, Integer.class, "JSON", "0", "...", "65535"); super.addDescription(Color.THRESHOLD_MAX_C, Integer.class, "JSON", "0", "...", "65535"); }
public CoordinatesEvent(AHandler deviceHandler, String eventTopic, MqttAsyncClient mqttClient) { super(deviceHandler, eventTopic, "coordinates", mqttClient); super.addDescription(GPS.LATITUDE, Long.class, "JSON", "" + Long.MIN_VALUE, "...", "" + Long.MAX_VALUE); super.addDescription(GPS.NS, Character.class, "JSON", "N", "S"); super.addDescription(GPS.LONGITUDE, Long.class, "JSON", "" + Long.MIN_VALUE, "...", "" + Long.MAX_VALUE); super.addDescription(GPS.EW, Character.class, "JSON", "E", "W"); super.addDescription(GPS.PDOP, Integer.class, "JSON", "" + Integer.MIN_VALUE, "...", "" + Integer.MAX_VALUE); super.addDescription(GPS.HDOP, Integer.class, "JSON", "" + Integer.MIN_VALUE, "...", "" + Integer.MAX_VALUE); super.addDescription(GPS.VDOP, Integer.class, "JSON", "" + Integer.MIN_VALUE, "...", "" + Integer.MAX_VALUE); super.addDescription(GPS.EPE, Integer.class, "JSON", "" + Integer.MIN_VALUE, "...", "" + Integer.MAX_VALUE); }
public LCD20x4ButtonEvent(AHandler deviceHandler, String eventTopic, MqttAsyncClient mqttClient) { super(deviceHandler, eventTopic, "buttonPressed", mqttClient); super.addDescription(LCD20x4.BUTTON_0, Boolean.class, "JSON", "true,false"); super.addDescription(LCD20x4.BUTTON_1, Boolean.class, "JSON", "true,false"); super.addDescription(LCD20x4.BUTTON_2, Boolean.class, "JSON", "true,false"); super.addDescription(LCD20x4.BUTTON_3, Boolean.class, "JSON", "true,false"); }
public DimSocketBEvent(AHandler deviceHandler, String eventTopic, MqttAsyncClient mqttClient) { super(deviceHandler, eventTopic, "dimSocketB", mqttClient); super.addDescription(RemoteSwitch.ADDRESS, Long.class, "JSON", "0", "...", "67108863"); super.addDescription(RemoteSwitch.UNIT, Short.class, "JSON", "0", "...", "15"); super.addDescription(RemoteSwitch.DIM_VALUE, Short.class, "JSON", "0", "...", "15"); super.addDescription(RemoteSwitch.SWITCHING, Boolean.class, "JSON", "true", "false"); }