Skip to content

Commit

Permalink
feat: add device discover request
Browse files Browse the repository at this point in the history
Signed-off-by: wei <[email protected]>
  • Loading branch information
instpe committed Dec 9, 2024
1 parent cf32c2c commit 006ee8f
Show file tree
Hide file tree
Showing 23 changed files with 376 additions and 70 deletions.
6 changes: 6 additions & 0 deletions mdtp-client/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@
<artifactId>mdtp-common</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.github.protocol-laboratory</groupId>
<artifactId>mdtp-server</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
</dependencies>

</project>
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
package io.github.protocol.mdtp.client;

import io.github.protocol.mdtp.common.model.CDATHeader;
import io.github.protocol.mdtp.common.model.DeviceDiscoveryRequest;
import io.github.protocol.mdtp.common.model.MdtpPacket;
import io.github.protocol.mdtp.common.model.MessageBodyHeader;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;
import java.io.IOException;

@Slf4j
@Data
public class MdtpClient implements Closeable {
private final MdtpClientConfig config;

private ChannelFuture channelFuture;

private EventLoopGroup group;

public MdtpClient(MdtpClientConfig config) {
Expand All @@ -37,7 +46,7 @@ public void start() throws Exception {
protected void initChannel(SocketChannel ch) throws Exception {
}
});
ChannelFuture channelFuture = bootstrap.connect().sync();
this.channelFuture = bootstrap.connect().sync();
if (channelFuture.isSuccess()) {
log.info("mdtp client started");
} else {
Expand All @@ -55,4 +64,40 @@ public void close() throws IOException {
this.group.shutdownGracefully();
log.info("mdtp client closed");
}

public void sendDeviceDiscoveryRequest(int[] deviceTypes) {
log.info("start to send device discovery request.");
DeviceDiscoveryRequest request = new DeviceDiscoveryRequest();
request.setMessageBodyHeader(MessageBodyHeader.DEVICE_DISCOVERY_REQUEST);
log.info("" + request.getMessageBodyHeader().toShort());
request.setRequestId(request.generateRequestId());

if (deviceTypes == null) {
request.setDeviceTypeCount((byte) 0);

Check warning on line 76 in mdtp-client/src/main/java/io/github/protocol/mdtp/client/MdtpClient.java

View check run for this annotation

Codecov / codecov/patch

mdtp-client/src/main/java/io/github/protocol/mdtp/client/MdtpClient.java#L76

Added line #L76 was not covered by tests
}

if (deviceTypes != null && deviceTypes.length > 0) {
request.setMask((byte) 1);
request.setDeviceTypeCount((byte) deviceTypes.length);
request.setDeviceTypes(deviceTypes);
}

CDATHeader cdatHeader = new CDATHeader();
cdatHeader.setFormatType((byte) 0x02);
cdatHeader.setProtocolVersion((byte) 1);
cdatHeader.setMessageLength((short) 0);
cdatHeader.setTimestamp(System.currentTimeMillis());
cdatHeader.setFlags((byte) 0b01100000);
cdatHeader.setSequenceNumber(0);
cdatHeader.setLogicalChannelId(0);

MdtpPacket packet = new MdtpPacket();
packet.setHeader(cdatHeader);
packet.setSecurityHeader(null);
packet.setBody(request);
packet.setSignature(null);

this.channelFuture.channel().writeAndFlush(packet.toByteBuf(Unpooled.buffer()));
log.info("send device discovery request success: " + packet);
}
}
73 changes: 73 additions & 0 deletions mdtp-client/src/test/java/MdtpClientTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import io.github.protocol.mdtp.client.MdtpClient;
import io.github.protocol.mdtp.client.MdtpClientConfig;
import io.github.protocol.mdtp.server.MdtpServer;
import io.github.protocol.mdtp.server.MdtpServerConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class MdtpClientTest {

private MdtpClientConfig config;
private MdtpClient mdtpClient;

private MdtpServer mdtpServer;
private EventLoopGroup groupMock;
private ChannelFuture channelFutureMock;

@BeforeEach
public void setUp() throws Exception {
MdtpServerConfig mdtpServerConfig = new MdtpServerConfig().host("localhost").port(4146);
mdtpServer = new MdtpServer(mdtpServerConfig);
mdtpServer.start();

config = new MdtpClientConfig().host("localhost").port(4146);
mdtpClient = new MdtpClient(config);

groupMock = mock(EventLoopGroup.class);
channelFutureMock = mock(ChannelFuture.class);

mdtpClient.setGroup(groupMock);
mdtpClient.setChannelFuture(channelFutureMock);
}

@AfterEach
public void close() throws IOException {
mdtpServer.close();
}

@Test
public void testStartConnection() throws Exception {
ChannelFuture channelFutureMock = mock(ChannelFuture.class);
when(channelFutureMock.isSuccess()).thenReturn(false);
mdtpClient.setGroup(null);
mdtpClient.setChannelFuture(channelFutureMock);
mdtpClient.start();
}

@Test
public void testClose() throws IOException {
mdtpClient.close();
verify(groupMock).shutdownGracefully();
}

@Test
public void testSendDeviceDiscoveryRequest() {
Channel channelMock = mock(Channel.class);
when(channelFutureMock.channel()).thenReturn(channelMock);
int[] deviceTypes = {1, 2, 3};
mdtpClient.sendDeviceDiscoveryRequest(deviceTypes);
verify(channelMock).writeAndFlush(any());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package io.github.protocol.mdtp.common.codec;

import io.github.protocol.mdtp.common.model.AbstractMessageBody;
import io.github.protocol.mdtp.common.model.DeviceDiscoveryRequest;
import io.netty.buffer.ByteBuf;

public class DeviceDiscoveryRequestDecoder implements MessageBodyDecoder {
@Override
public AbstractMessageBody handle(ByteBuf in) {
return DeviceDiscoveryRequest.fromByteBuf(in);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package io.github.protocol.mdtp.common.codec;


import io.github.protocol.mdtp.common.model.AbstractMessageBody;
import io.github.protocol.mdtp.common.model.CDATHeader;
import io.github.protocol.mdtp.common.model.MdtpPacket;
import io.github.protocol.mdtp.common.model.MessageBodyHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class MdtpDecoder extends ByteToMessageDecoder {

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

MdtpPacket mdtpPacket = new MdtpPacket();
CDATHeader header = CDATHeader.fromByteBuf(in);

MessageBodyHeader messageBodyHeader = MessageBodyHeader.fromByteBuf(in);
MessageBodyDecoder messageDecode = MessageDecoderFactory.getDecoder(messageBodyHeader);
AbstractMessageBody messageBody = messageDecode.handle(in);
messageBody.setMessageBodyHeader(messageBodyHeader);

mdtpPacket.setHeader(header);
mdtpPacket.setBody(messageBody);

out.add(mdtpPacket);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package io.github.protocol.mdtp.common.codec;

import io.github.protocol.mdtp.common.model.AbstractMessageBody;
import io.netty.buffer.ByteBuf;

public interface MessageBodyDecoder {
AbstractMessageBody handle(ByteBuf in);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package io.github.protocol.mdtp.common.codec;

import io.github.protocol.mdtp.common.model.MessageBodyHeader;

import java.util.HashMap;
import java.util.Map;

public class MessageDecoderFactory {

Check warning on line 8 in mdtp-common/src/main/java/io/github/protocol/mdtp/common/codec/MessageDecoderFactory.java

View check run for this annotation

Codecov / codecov/patch

mdtp-common/src/main/java/io/github/protocol/mdtp/common/codec/MessageDecoderFactory.java#L8

Added line #L8 was not covered by tests

private static final Map<Short, MessageBodyDecoder> decoders = new HashMap<>();

static {
decoders.put(MessageBodyHeader.DEVICE_DISCOVERY_REQUEST.toShort(), new DeviceDiscoveryRequestDecoder());
}

public static MessageBodyDecoder getDecoder(MessageBodyHeader header) {
return decoders.get(header.toShort());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,15 @@

@Data
public abstract class AbstractMessageBody {
private short messageBodyHeader;

public void setMessageBodyHeader(MessageType messageType, ServiceGroup serviceGroup, DiscoveryServiceCode serviceCode) {
this.messageBodyHeader = 0;
this.messageBodyHeader |= (short) (messageType.getCode() & 0b111);
this.messageBodyHeader |= (short) ((serviceGroup.getCode() & 0b1111111) << 3);
this.messageBodyHeader |= (short) ((serviceCode.getCode() & 0b111111) << 10);
}
private MessageBodyHeader messageBodyHeader;

public short generateRequestId() {
UUID uuid = UUID.randomUUID();
return (short) (uuid.getLeastSignificantBits() & 0xFFFF);
}

public ByteBuf toByteBuf(ByteBuf buffer) {
buffer.writeShort(messageBodyHeader);
messageBodyHeader.toByteBuf(buffer);
return buffer;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,18 @@ public ByteBuf toByteBuf(ByteBuf buffer) {
buffer.writeInt(logicalChannelId);
return buffer;
}

public static CDATHeader fromByteBuf(ByteBuf buffer) {
CDATHeader header = new CDATHeader();

Check warning on line 40 in mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/CDATHeader.java

View check run for this annotation

Codecov / codecov/patch

mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/CDATHeader.java#L40

Added line #L40 was not covered by tests

header.setFormatType(buffer.readByte());
header.setProtocolVersion(buffer.readByte());
header.setMessageLength(buffer.readShort());
header.setTimestamp(buffer.readLong());
header.setFlags(buffer.readByte());
header.setSequenceNumber(buffer.readInt());
header.setLogicalChannelId(buffer.readInt());

Check warning on line 48 in mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/CDATHeader.java

View check run for this annotation

Codecov / codecov/patch

mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/CDATHeader.java#L42-L48

Added lines #L42 - L48 were not covered by tests

return header;

Check warning on line 50 in mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/CDATHeader.java

View check run for this annotation

Codecov / codecov/patch

mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/CDATHeader.java#L50

Added line #L50 was not covered by tests
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@


@Data
public class DeviceDiscoveryRequest extends AbstractMessageBody {
public class DeviceDiscoveryRequest extends AbstractMessageBody{

private short requestId;

private byte mask;
Expand All @@ -19,8 +20,10 @@ public ByteBuf toByteBuf(ByteBuf buffer) {
buffer.writeShort(requestId);
buffer.writeByte(mask);
buffer.writeByte(deviceTypeCount);
for (int deviceType : deviceTypes) {
buffer.writeInt(deviceType);
if (deviceTypeCount > 0) {
for (int deviceType : deviceTypes) {
buffer.writeInt(deviceType);
}
}
return buffer;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,12 @@ public enum DiscoveryServiceCode {
this.description = description;
}

public static DiscoveryServiceCode fromCode(int value) {
for (DiscoveryServiceCode serviceCode : DiscoveryServiceCode.values()) {
if (serviceCode.getCode() == value) {
return serviceCode;
}
}
throw new IllegalArgumentException("Invalid DiscoveryServiceCode: " + value);
}

Check warning on line 26 in mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/DiscoveryServiceCode.java

View check run for this annotation

Codecov / codecov/patch

mdtp-common/src/main/java/io/github/protocol/mdtp/common/model/DiscoveryServiceCode.java#L25-L26

Added lines #L25 - L26 were not covered by tests
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package io.github.protocol.mdtp.common.model;

import io.netty.buffer.ByteBuf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;


@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class MessageBodyHeader {
private MessageType messageType;

private ServiceGroup serviceGroup;

private DiscoveryServiceCode serviceCode;

public static final MessageBodyHeader DEVICE_DISCOVERY_REQUEST =
new MessageBodyHeader(MessageType.REQUEST, ServiceGroup.DISCOVERY_SERVICE, DiscoveryServiceCode.DEVICE_DISCOVERY);

public static final MessageBodyHeader DEVICE_DISCOVERY_RESPONSE =
new MessageBodyHeader(MessageType.RESPONSE, ServiceGroup.DISCOVERY_SERVICE, DiscoveryServiceCode.DEVICE_DISCOVERY);

public short toShort() {
short messageBodyHeader = 0;
messageBodyHeader |= (short) (this.messageType.getCode() & 0b111);
messageBodyHeader |= (short) ((this.serviceGroup.getCode() & 0b1111111) << 3);
messageBodyHeader |= (short) ((this.serviceCode.getCode() & 0b111111) << 10);
return messageBodyHeader;
}

public ByteBuf toByteBuf(ByteBuf buffer) {
buffer.writeShort(toShort());
return buffer;
}

public static MessageBodyHeader fromByteBuf(ByteBuf buffer) {
short messageBodyHeader = buffer.readShort();
MessageType messageType = MessageType.fromCode((short) (messageBodyHeader & 0b111));
ServiceGroup serviceGroup = ServiceGroup.fromCode((short) ((messageBodyHeader >> 3) & 0b1111111));
DiscoveryServiceCode serviceCode = DiscoveryServiceCode.fromCode((short) ((messageBodyHeader >> 10) & 0b111111));
return new MessageBodyHeader(messageType, serviceGroup, serviceCode);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,13 @@ public enum MessageType {
public int getCode() {
return code;
}

public static MessageType fromCode(int value) {
for (MessageType type : MessageType.values()) {
if (type.getCode() == value) {
return type;
}
}
throw new IllegalArgumentException("Invalid MessageType code: " + value);
}
}
Loading

0 comments on commit 006ee8f

Please sign in to comment.