Search in sources :

Example 6 with MqttServer

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());
        }
    });
}
Also used : MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) AbstractVerticle(io.vertx.core.AbstractVerticle) Runner(io.vertx.example.mqtt.util.Runner) MqttServer(io.vertx.mqtt.MqttServer) ArrayList(java.util.ArrayList) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) MqttServer(io.vertx.mqtt.MqttServer) List(java.util.List) ArrayList(java.util.ArrayList)

Example 7 with MqttServer

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());
        }
    });
}
Also used : MqttServerOptions(io.vertx.mqtt.MqttServerOptions) MqttServer(io.vertx.mqtt.MqttServer)

Example 8 with MqttServer

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));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) HttpURLConnection(java.net.HttpURLConnection) TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) ArgumentMatchers(org.mockito.ArgumentMatchers) ProtonDelivery(io.vertx.proton.ProtonDelivery) MqttConnectReturnCode(io.netty.handler.codec.mqtt.MqttConnectReturnCode) TenantConstants(org.eclipse.hono.util.TenantConstants) RunWith(org.junit.runner.RunWith) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Context(io.vertx.core.Context) MqttServer(io.vertx.mqtt.MqttServer) Assert.assertThat(org.junit.Assert.assertThat) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) TenantClient(org.eclipse.hono.client.TenantClient) MessageSender(org.eclipse.hono.client.MessageSender) BiConsumer(java.util.function.BiConsumer) Timeout(org.junit.rules.Timeout) Message(org.apache.qpid.proton.message.Message) RegistrationClient(org.eclipse.hono.client.RegistrationClient) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) HonoClient(org.eclipse.hono.client.HonoClient) Before(org.junit.Before) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) AfterClass(org.junit.AfterClass) UsernamePasswordCredentials(org.eclipse.hono.service.auth.device.UsernamePasswordCredentials) DeviceCredentials(org.eclipse.hono.service.auth.device.DeviceCredentials) Vertx(io.vertx.core.Vertx) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) HonoClientBasedAuthProvider(org.eclipse.hono.service.auth.device.HonoClientBasedAuthProvider) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) MqttAuth(io.vertx.mqtt.MqttAuth) Device(org.eclipse.hono.service.auth.device.Device) Handler(io.vertx.core.Handler) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) Async(io.vertx.ext.unit.Async) MqttServer(io.vertx.mqtt.MqttServer) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 9 with MqttServer

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);
}
Also used : ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttServer(io.vertx.mqtt.MqttServer) Test(org.junit.Test)

Example 10 with MqttServer

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());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ProtocolAdapterProperties(org.eclipse.hono.config.ProtocolAdapterProperties) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) MqttServer(io.vertx.mqtt.MqttServer) Test(org.junit.Test)

Aggregations

MqttServer (io.vertx.mqtt.MqttServer)13 MqttEndpoint (io.vertx.mqtt.MqttEndpoint)8 ProtocolAdapterProperties (org.eclipse.hono.config.ProtocolAdapterProperties)8 Buffer (io.vertx.core.buffer.Buffer)7 Test (org.junit.Test)7 MqttPublishMessage (io.vertx.mqtt.messages.MqttPublishMessage)6 ProtonDelivery (io.vertx.proton.ProtonDelivery)5 MqttQoS (io.netty.handler.codec.mqtt.MqttQoS)4 AsyncResult (io.vertx.core.AsyncResult)4 Handler (io.vertx.core.Handler)4 ClientErrorException (org.eclipse.hono.client.ClientErrorException)4 UsernamePasswordCredentials (org.eclipse.hono.service.auth.device.UsernamePasswordCredentials)4 MqttConnectReturnCode (io.netty.handler.codec.mqtt.MqttConnectReturnCode)3 Context (io.vertx.core.Context)3 Future (io.vertx.core.Future)3 Vertx (io.vertx.core.Vertx)3 JsonObject (io.vertx.core.json.JsonObject)3 Async (io.vertx.ext.unit.Async)3 TestContext (io.vertx.ext.unit.TestContext)3 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)3