use of io.vertx.mqtt.MqttServer in project vertx-examples by vert-x3.
the class Server method start.
@Override
public void start() throws Exception {
MqttServer mqttServer = MqttServer.create(vertx);
mqttServer.endpointHandler(endpoint -> {
// shows main connect info
System.out.println("MQTT client [" + endpoint.clientIdentifier() + "] request to connect, clean session = " + endpoint.isCleanSession());
if (endpoint.auth() != null) {
System.out.println("[username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "]");
}
if (endpoint.will() != null) {
System.out.println("[will flag = " + endpoint.will().isWillFlag() + " topic = " + endpoint.will().willTopic() + " msg = " + endpoint.will().willMessage() + " QoS = " + endpoint.will().willQos() + " isRetain = " + endpoint.will().isWillRetain() + "]");
}
System.out.println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]");
// accept connection from the remote client
endpoint.accept(false);
// handling requests for subscriptions
endpoint.subscribeHandler(subscribe -> {
List<MqttQoS> grantedQosLevels = new ArrayList<>();
for (MqttTopicSubscription s : subscribe.topicSubscriptions()) {
System.out.println("Subscription for " + s.topicName() + " with QoS " + s.qualityOfService());
grantedQosLevels.add(s.qualityOfService());
}
// ack the subscriptions request
endpoint.subscribeAcknowledge(subscribe.messageId(), grantedQosLevels);
// just as example, publish a message on the first topic with requested QoS
endpoint.publish(subscribe.topicSubscriptions().get(0).topicName(), Buffer.buffer("Hello from the Vert.x MQTT server"), subscribe.topicSubscriptions().get(0).qualityOfService(), false, false);
// specifing handlers for handling QoS 1 and 2
endpoint.publishAcknowledgeHandler(messageId -> {
System.out.println("Received ack for message = " + messageId);
}).publishReceivedHandler(messageId -> {
endpoint.publishRelease(messageId);
}).publishCompletionHandler(messageId -> {
System.out.println("Received ack for message = " + messageId);
});
});
// handling requests for unsubscriptions
endpoint.unsubscribeHandler(unsubscribe -> {
for (String t : unsubscribe.topics()) {
System.out.println("Unsubscription for " + t);
}
// ack the subscriptions request
endpoint.unsubscribeAcknowledge(unsubscribe.messageId());
});
// handling ping from client
endpoint.pingHandler(v -> {
System.out.println("Ping received from client");
});
// handling disconnect message
endpoint.disconnectHandler(v -> {
System.out.println("Received disconnect from client");
});
// handling closing connection
endpoint.closeHandler(v -> {
System.out.println("Connection closed");
});
// handling incoming published messages
endpoint.publishHandler(message -> {
System.out.println("Just received message on [" + message.topicName() + "] payload [" + message.payload() + "] with QoS [" + message.qosLevel() + "]");
if (message.qosLevel() == MqttQoS.AT_LEAST_ONCE) {
endpoint.publishAcknowledge(message.messageId());
} else if (message.qosLevel() == MqttQoS.EXACTLY_ONCE) {
endpoint.publishReceived(message.messageId());
}
}).publishReleaseHandler(messageId -> {
endpoint.publishComplete(messageId);
});
}).listen(1883, "0.0.0.0", ar -> {
if (ar.succeeded()) {
System.out.println("MQTT server is listening on port " + mqttServer.actualPort());
} else {
System.err.println("Error on starting the server" + ar.cause().getMessage());
}
});
}
use of io.vertx.mqtt.MqttServer in project vertx-examples by vert-x3.
the class Server method start.
@Override
public void start() throws Exception {
MqttServerOptions options = new MqttServerOptions().setPort(1883).setHost("0.0.0.0");
MqttServer server = MqttServer.create(vertx, options);
server.endpointHandler(endpoint -> {
System.out.println("connected client " + endpoint.clientIdentifier());
endpoint.publishHandler(message -> {
System.out.println("Just received message on [" + message.topicName() + "] payload [" + message.payload() + "] with QoS [" + message.qosLevel() + "]");
});
endpoint.accept(false);
});
server.listen(ar -> {
if (ar.succeeded()) {
System.out.println("MQTT server started and listening on port " + server.actualPort());
} else {
System.err.println("MQTT server error on start" + ar.cause().getMessage());
}
});
}
use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testStartup.
/**
* Verifies that an MQTT server is bound to the insecure port during startup and connections
* to required services have been established.
*
* @param ctx The helper to use for running async tests on vertx.
*/
@SuppressWarnings("unchecked")
@Test
public void testStartup(final TestContext ctx) {
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
final Async startup = ctx.async();
final Future<Void> startupTracker = Future.future();
startupTracker.setHandler(ctx.asyncAssertSuccess(s -> {
startup.complete();
}));
adapter.start(startupTracker);
startup.await();
verify(server).listen(any(Handler.class));
verify(server).endpointHandler(any(Handler.class));
}
use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testEndpointHandlerFailsWithoutConnect.
// TODO: startup fail test
/**
* Verifies that a connection attempt from a device is refused if the adapter is not
* connected to all of the services it depends on.
*/
@Test
public void testEndpointHandlerFailsWithoutConnect() {
// GIVEN an endpoint
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
adapter.handleEndpointConnection(endpoint);
verify(endpoint).reject(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
}
use of io.vertx.mqtt.MqttServer in project hono by eclipse.
the class AbstractVertxBasedMqttProtocolAdapterTest method testUploadMessageSupportsShortAndLongEndpointNames.
/**
* Verifies that the adapter will accept uploading messages to valid endpoint names.
*
* @param ctx The vert.x test context.
*/
@Test
public void testUploadMessageSupportsShortAndLongEndpointNames(final TestContext ctx) {
// GIVEN an adapter with a downstream event consumer
final MqttServer server = getMqttServer(false);
final AbstractVertxBasedMqttProtocolAdapter<ProtocolAdapterProperties> adapter = getAdapter(server);
givenATelemetrySenderForOutcome(Future.succeededFuture(mock(ProtonDelivery.class)));
givenAnEventSenderForOutcome(Future.succeededFuture(mock(ProtonDelivery.class)));
// WHEN a device publishes an event
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isConnected()).thenReturn(Boolean.TRUE);
final Buffer payload = Buffer.buffer("some payload");
final MqttPublishMessage messageFromDevice = mock(MqttPublishMessage.class);
when(messageFromDevice.qosLevel()).thenReturn(MqttQoS.AT_LEAST_ONCE);
when(messageFromDevice.messageId()).thenReturn(5555555);
when(messageFromDevice.payload()).thenReturn(payload);
final MqttContext context = new MqttContext(messageFromDevice, endpoint);
ResourceIdentifier resourceId = ResourceIdentifier.from("telemetry", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("event", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("t", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("e", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertSuccess());
resourceId = ResourceIdentifier.from("unknown", "my-tenant", "4712");
adapter.uploadMessage(context, resourceId, payload).setHandler(ctx.asyncAssertFailure());
}
Aggregations