use of org.eclipse.paho.client.mqttv3.MqttCallback in project camel by apache.
the class PahoConsumer method doStart.
@Override
protected void doStart() throws Exception {
super.doStart();
String topic = getEndpoint().getTopic();
getEndpoint().getClient().subscribe(topic);
getEndpoint().getClient().setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable cause) {
LOG.debug("MQTT broker connection lost due " + cause.getMessage(), cause);
}
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
LOG.debug("Message arrived on topic: {} -> {}", topic, message);
Exchange exchange = getEndpoint().createExchange(message, topic);
getAsyncProcessor().process(exchange, new AsyncCallback() {
@Override
public void done(boolean doneSync) {
// noop
}
});
}
@Override
public void deliveryComplete(IMqttDeliveryToken token) {
LOG.debug("Delivery complete. Token: {}", token);
}
});
}
use of org.eclipse.paho.client.mqttv3.MqttCallback in project yoo_home_Android by culturer.
the class MQTTService method initMQ.
private void initMQ() {
// 服务器地址(协议+地址+端口号)
String uri = host;
client = new MqttAndroidClient(this, uri, 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 anki-battle-showcase by adessoAG.
the class MqttService method connect.
public void connect() {
try {
// test.mosquitto.org broker.hivemq.com
mqttClient = new MqttClient("tcp://localhost:1883", "anki-battle", new MemoryPersistence());
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(false);
log.info("Connecting to MQTT broker: localhost:1883");
mqttClient.connect(connOpts);
log.info("Connected to MQTT broker");
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
log.info("MQTT connection lost");
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) {
try {
log.debug("MQTT message arrived: topic=" + s + "; message=" + mqttMessage.toString());
String temp = mqttMessage.toString();
byte[] hm = mqttMessage.getPayload();
JSONObject json = new JSONObject(mqttMessage.toString());
// get topic, where topic is identifier for vehicle
// get corresponding vehicle v
// v.exexute command
String topic = s.split("_")[0];
List<DynamicBody> vehicles = world.getDynamicBodies();
Vehicle wantedVehicle = null;
for (int i = 0; i < vehicles.size(); i++) {
Vehicle currentVehicle = ((Vehicle) vehicles.get(i));
if (topic.equals(currentVehicle.getName())) {
wantedVehicle = currentVehicle;
break;
}
}
String commandType = (String) json.get("type");
int speed;
Command command = null;
int track;
switch(commandType) {
case ("accelerate"):
speed = Integer.parseInt((String) json.get("velocity"));
command = new AccelerateCommand(speed);
break;
case ("brake"):
speed = Integer.parseInt((String) json.get("velocity"));
command = new BrakeCommand(speed);
break;
case ("change track"):
val lane = Double.parseDouble((String) json.get("track"));
command = new ChangeLaneCommand(lane);
break;
case ("uTurn"):
command = new UTurnCommand();
break;
case ("fireRocket"):
command = new FireRocketCommand("");
break;
case ("putMine"):
command = new PutMineCommand();
break;
}
if (command != null) {
command.execute(wantedVehicle);
} else {
log.debug("No Command");
}
} catch (Exception e) {
log.error("Error while parsing MQTT message", e);
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
} catch (MqttException e) {
log.debug("exception during initialising service");
e.printStackTrace();
}
}
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.stop();
}
}
use of org.eclipse.paho.client.mqttv3.MqttCallback in project spring-integration by spring-projects.
the class MqttAdapterTests method testInboundOptionsApplied.
@Test
public void testInboundOptionsApplied() throws Exception {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
factory.setCleanSession(false);
factory.setConnectionTimeout(23);
factory.setKeepAliveInterval(45);
factory.setPassword("pass");
MemoryPersistence persistence = new MemoryPersistence();
factory.setPersistence(persistence);
final SocketFactory socketFactory = mock(SocketFactory.class);
factory.setSocketFactory(socketFactory);
final Properties props = new Properties();
factory.setSslProperties(props);
factory.setUserName("user");
Will will = new Will("foo", "bar".getBytes(), 2, true);
factory.setWill(will);
factory = spy(factory);
final IMqttClient client = mock(IMqttClient.class);
willAnswer(invocation -> client).given(factory).getClientInstance(anyString(), anyString());
final AtomicBoolean connectCalled = new AtomicBoolean();
final AtomicBoolean failConnection = new AtomicBoolean();
final CountDownLatch waitToFail = new CountDownLatch(1);
final CountDownLatch failInProcess = new CountDownLatch(1);
final CountDownLatch goodConnection = new CountDownLatch(2);
final MqttException reconnectException = new MqttException(MqttException.REASON_CODE_SERVER_CONNECT_ERROR);
willAnswer(invocation -> {
if (failConnection.get()) {
failInProcess.countDown();
waitToFail.await(10, TimeUnit.SECONDS);
throw reconnectException;
}
MqttConnectOptions options = invocation.getArgument(0);
assertEquals(23, options.getConnectionTimeout());
assertEquals(45, options.getKeepAliveInterval());
assertEquals("pass", new String(options.getPassword()));
assertSame(socketFactory, options.getSocketFactory());
assertSame(props, options.getSSLProperties());
assertEquals("user", options.getUserName());
assertEquals("foo", options.getWillDestination());
assertEquals("bar", new String(options.getWillMessage().getPayload()));
assertEquals(2, options.getWillMessage().getQos());
connectCalled.set(true);
goodConnection.countDown();
return null;
}).given(client).connect(any(MqttConnectOptions.class));
final AtomicReference<MqttCallback> callback = new AtomicReference<MqttCallback>();
willAnswer(invocation -> {
callback.set(invocation.getArgument(0));
return null;
}).given(client).setCallback(any(MqttCallback.class));
given(client.isConnected()).willReturn(true);
MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter("foo", "bar", factory, "baz", "fix");
QueueChannel outputChannel = new QueueChannel();
adapter.setOutputChannel(outputChannel);
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
adapter.setTaskScheduler(taskScheduler);
adapter.setBeanFactory(mock(BeanFactory.class));
ApplicationEventPublisher applicationEventPublisher = mock(ApplicationEventPublisher.class);
final BlockingQueue<MqttIntegrationEvent> events = new LinkedBlockingQueue<MqttIntegrationEvent>();
willAnswer(invocation -> {
events.add(invocation.getArgument(0));
return null;
}).given(applicationEventPublisher).publishEvent(any(MqttIntegrationEvent.class));
adapter.setApplicationEventPublisher(applicationEventPublisher);
adapter.setRecoveryInterval(500);
adapter.afterPropertiesSet();
adapter.start();
verify(client, times(1)).connect(any(MqttConnectOptions.class));
assertTrue(connectCalled.get());
MqttMessage message = new MqttMessage("qux".getBytes());
callback.get().messageArrived("baz", message);
Message<?> outMessage = outputChannel.receive(0);
assertNotNull(outMessage);
assertEquals("qux", outMessage.getPayload());
MqttIntegrationEvent event = events.poll(10, TimeUnit.SECONDS);
assertThat(event, instanceOf(MqttSubscribedEvent.class));
assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
// lose connection and make first reconnect fail
failConnection.set(true);
RuntimeException e = new RuntimeException("foo");
adapter.connectionLost(e);
event = events.poll(10, TimeUnit.SECONDS);
assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
assertSame(event.getCause(), e);
assertTrue(failInProcess.await(10, TimeUnit.SECONDS));
waitToFail.countDown();
failConnection.set(false);
event = events.poll(10, TimeUnit.SECONDS);
assertThat(event, instanceOf(MqttConnectionFailedEvent.class));
assertSame(event.getCause(), reconnectException);
// reconnect can now succeed; however, we might have other failures on a slow server (500ms retry).
assertTrue(goodConnection.await(10, TimeUnit.SECONDS));
int n = 0;
while (!(event instanceof MqttSubscribedEvent) && n++ < 20) {
event = events.poll(10, TimeUnit.SECONDS);
}
assertThat(event, instanceOf(MqttSubscribedEvent.class));
assertEquals("Connected and subscribed to [baz, fix]", ((MqttSubscribedEvent) event).getMessage());
taskScheduler.destroy();
}
Aggregations