use of org.eclipse.paho.client.mqttv3.MqttCallback in project yoo_home_Android by culturer.
the class MQTTService method initMQ.
// 初始化MQ服务
private void initMQ() {
// 服务器地址(协议+地址+端口号)
client = new MqttAndroidClient(this, host, clientId);
// 设置MQTT监听并且接受消息
client.setCallback(mqttCallback);
conOpt = new MqttConnectOptions();
// 清除缓存
conOpt.setCleanSession(false);
// 设置超时时间,单位:秒
conOpt.setConnectionTimeout(0);
// 心跳包发送间隔,单位:秒
conOpt.setKeepAliveInterval(10);
// 用户名
conOpt.setUserName(userName);
// 密码
conOpt.setPassword(passWord.toCharArray());
// last will message
boolean doConnect = true;
String message = "{\"terminal_uid\":\"" + clientId + "\"}";
String topic = myTopic;
Integer qos = 0;
Boolean retained = false;
// 存在内存泄露???
if ((!message.equals("")) || (!topic.equals(""))) {
// 最后的遗嘱
try {
conOpt.setWill(topic, message.getBytes(), qos, retained);
} catch (Exception e) {
Log.i(TAG, "Exception Occured", e);
doConnect = false;
iMqttActionListener.onFailure(null, e);
}
}
if (doConnect) {
doClientConnection();
}
}
use of org.eclipse.paho.client.mqttv3.MqttCallback in project java-docs-samples by GoogleCloudPlatform.
the class MqttCommandsDemo method attachCallback.
/**
* Attaches the callback used when configuration changes occur.
*/
public static void attachCallback(MqttClient client, String deviceId, Screen mainScreen) throws MqttException {
mCallback = new MqttCallback() {
private TextColor mainBgColor = new TextColor.ANSI.RGB(255, 255, 255);
private TextColor myColor;
@Override
public void connectionLost(Throwable cause) {
// Do nothing...
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String payload = new String(message.getPayload());
System.out.println("Payload : " + payload);
// will receive a config with an empty payload.
if (payload == null || payload.length() == 0) {
return;
}
if (isJsonValid(payload)) {
JSONObject data = null;
data = new JSONObject(payload);
// [begin command respond code]
// [end command respond code]
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Do nothing;
}
/**
* Get the color from a string name
*
* @param col name of the color
* @return White if no color is given, otherwise the Color object
*/
TextColor getColor(String col) {
switch(col.toLowerCase()) {
case "black":
myColor = TextColor.ANSI.BLACK;
break;
case "blue":
myColor = TextColor.ANSI.BLUE;
break;
case "cyan":
myColor = TextColor.ANSI.CYAN;
break;
case "green":
myColor = TextColor.ANSI.GREEN;
break;
case "yellow":
myColor = TextColor.ANSI.YELLOW;
break;
case "magneta":
myColor = TextColor.ANSI.MAGENTA;
break;
case "red":
myColor = TextColor.ANSI.RED;
break;
case "white":
myColor = TextColor.ANSI.WHITE;
break;
default:
myColor = TextColor.ANSI.BLACK;
break;
}
return myColor;
}
public boolean isValidColor(JSONObject data, TextColor mainBgColor) throws JSONException {
return data.get("color") instanceof String && !mainBgColor.toColor().equals(getColor((String) data.get("color")));
}
};
// [begin code section]
// [end code section]
String configTopic = String.format("/devices/%s/config", deviceId);
System.out.println(String.format("Listening on %s", configTopic));
client.subscribe(configTopic, 1);
client.setCallback(mCallback);
}
use of org.eclipse.paho.client.mqttv3.MqttCallback in project java-docs-samples by GoogleCloudPlatform.
the class MqttExample method attachCallback.
/**
* Attaches the callback used when configuration changes occur.
*/
protected static void attachCallback(MqttClient client, String deviceId) throws MqttException, UnsupportedEncodingException {
mCallback = new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
// Do nothing...
}
@Override
public void messageArrived(String topic, MqttMessage message) {
try {
String payload = new String(message.getPayload(), StandardCharsets.UTF_8.name());
System.out.println("Payload : " + payload);
// TODO: Insert your parsing / handling of the configuration message here.
//
} catch (UnsupportedEncodingException uee) {
System.err.println(uee);
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// Do nothing;
}
};
String commandTopic = String.format("/devices/%s/commands/#", deviceId);
System.out.println(String.format("Listening on %s", commandTopic));
String configTopic = String.format("/devices/%s/config", deviceId);
System.out.println(String.format("Listening on %s", configTopic));
client.subscribe(configTopic, 1);
client.subscribe(commandTopic, 1);
client.setCallback(mCallback);
}
use of org.eclipse.paho.client.mqttv3.MqttCallback in project wildfly-camel by wildfly-extras.
the class PahoIntegrationTest method testMQTTProducer.
@Test
public void testMQTTProducer() throws Exception {
String conUrl = TestUtils.getResourceValue(getClass(), "/tcp-connection");
CamelContext camelctx = new DefaultCamelContext();
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start").transform(body().prepend("Hello ")).to("paho:" + BrokerSetup.TEST_TOPIC + "?brokerUrl=" + conUrl);
}
});
camelctx.start();
try {
MqttClient client = new MqttClient(conUrl, "MqttClient", new MemoryPersistence());
MqttConnectOptions opts = new MqttConnectOptions();
opts.setCleanSession(true);
client.connect(opts);
client.subscribe(BrokerSetup.TEST_TOPIC, 2);
final List<String> result = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(1);
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
result.add(new String(message.getPayload()));
latch.countDown();
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
ProducerTemplate producer = camelctx.createProducerTemplate();
producer.asyncSendBody("direct:start", "Kermit");
Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
Assert.assertEquals("One message", 1, result.size());
Assert.assertEquals("Hello Kermit", result.get(0));
} finally {
camelctx.close();
}
}
use of org.eclipse.paho.client.mqttv3.MqttCallback in project FogLight-Examples by oci-pronghorn.
the class SubscribeDataMQTT method startup.
@Override
public void startup() {
try {
client = new MqttClient(serverURI, clientId, new MemoryPersistence());
client.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
logger.warn("connection lost, re-subscribe after timeout");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
// call startup again.
startup();
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
logger.info("received MQTT message on topic {}", topic);
commandChannel.publishTopic(publishTopic, w -> {
w.writeUTF(topic);
w.write(message.getPayload());
});
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
}
});
client.connect(connOptions);
// client.setTimeToWait(-1);
client.subscribe(subscriptionTopic, 1);
} catch (MqttException e) {
throw new RuntimeException(e);
}
}
Aggregations