Showing
23 changed files
with
1321 additions
and
2126 deletions
@@ -83,6 +83,10 @@ | @@ -83,6 +83,10 @@ | ||
83 | </dependency> | 83 | </dependency> |
84 | <dependency> | 84 | <dependency> |
85 | <groupId>org.thingsboard.common.transport</groupId> | 85 | <groupId>org.thingsboard.common.transport</groupId> |
86 | + <artifactId>tcp</artifactId> | ||
87 | + </dependency> | ||
88 | + <dependency> | ||
89 | + <groupId>org.thingsboard.common.transport</groupId> | ||
86 | <artifactId>http</artifactId> | 90 | <artifactId>http</artifactId> |
87 | </dependency> | 91 | </dependency> |
88 | <dependency> | 92 | <dependency> |
application/src/main/java/org/thingsboard/server/service/install/DefaultSystemDataLoaderService.java
@@ -176,7 +176,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { | @@ -176,7 +176,7 @@ public class DefaultSystemDataLoaderService implements SystemDataLoaderService { | ||
176 | 176 | ||
177 | @Override | 177 | @Override |
178 | public void createSysAdmin() { | 178 | public void createSysAdmin() { |
179 | - createUser(Authority.SYS_ADMIN, null, null, "sysadmin@thingsboard.org", "sysadmin"); | 179 | + createUser(Authority.SYS_ADMIN, null, null, "sysadmin@qq.com", "sysadmin"); |
180 | } | 180 | } |
181 | 181 | ||
182 | @Override | 182 | @Override |
@@ -170,9 +170,9 @@ ui: | @@ -170,9 +170,9 @@ ui: | ||
170 | database: | 170 | database: |
171 | ts_max_intervals: "${DATABASE_TS_MAX_INTERVALS:700}" # Max number of DB queries generated by single API call to fetch telemetry records | 171 | ts_max_intervals: "${DATABASE_TS_MAX_INTERVALS:700}" # Max number of DB queries generated by single API call to fetch telemetry records |
172 | ts: | 172 | ts: |
173 | - type: "${DATABASE_TS_TYPE:sql}" # cassandra, sql, or timescale (for hybrid mode, DATABASE_TS_TYPE value should be cassandra, or timescale) | 173 | + type: "${DATABASE_TS_TYPE:timescale}" # cassandra, sql, or timescale (for hybrid mode, DATABASE_TS_TYPE value should be cassandra, or timescale) |
174 | ts_latest: | 174 | ts_latest: |
175 | - type: "${DATABASE_TS_LATEST_TYPE:sql}" # cassandra, sql, or timescale (for hybrid mode, DATABASE_TS_TYPE value should be cassandra, or timescale) | 175 | + type: "${DATABASE_TS_LATEST_TYPE:timescale}" # cassandra, sql, or timescale (for hybrid mode, DATABASE_TS_TYPE value should be cassandra, or timescale) |
176 | 176 | ||
177 | # note: timescale works only with postgreSQL database for DATABASE_ENTITIES_TYPE. | 177 | # note: timescale works only with postgreSQL database for DATABASE_ENTITIES_TYPE. |
178 | 178 | ||
@@ -539,9 +539,9 @@ spring: | @@ -539,9 +539,9 @@ spring: | ||
539 | database-platform: "${SPRING_JPA_DATABASE_PLATFORM:org.hibernate.dialect.PostgreSQLDialect}" | 539 | database-platform: "${SPRING_JPA_DATABASE_PLATFORM:org.hibernate.dialect.PostgreSQLDialect}" |
540 | datasource: | 540 | datasource: |
541 | driverClassName: "${SPRING_DRIVER_CLASS_NAME:org.postgresql.Driver}" | 541 | driverClassName: "${SPRING_DRIVER_CLASS_NAME:org.postgresql.Driver}" |
542 | - url: "${SPRING_DATASOURCE_URL:jdbc:postgresql://47.99.141.212:20638/thingsboard-3.3.4}" | 542 | + url: "${SPRING_DATASOURCE_URL:jdbc:postgresql://47.99.141.212:20638/timescale-3.3.4}" |
543 | username: "${SPRING_DATASOURCE_USERNAME:postgres}" | 543 | username: "${SPRING_DATASOURCE_USERNAME:postgres}" |
544 | - password: "${SPRING_DATASOURCE_PASSWORD:Vrr861!@waja}" | 544 | + password: "${SPRING_DATASOURCE_PASSWORD:Xga751++nqnk}" |
545 | # url: "${SPRING_DATASOURCE_URL:jdbc:postgresql://101.133.234.90:28776/thingsboard-3.3.2}" | 545 | # url: "${SPRING_DATASOURCE_URL:jdbc:postgresql://101.133.234.90:28776/thingsboard-3.3.2}" |
546 | # username: "${SPRING_DATASOURCE_USERNAME:postgres}" | 546 | # username: "${SPRING_DATASOURCE_USERNAME:postgres}" |
547 | # password: "${SPRING_DATASOURCE_PASSWORD:Bua312!!iwcw}" | 547 | # password: "${SPRING_DATASOURCE_PASSWORD:Bua312!!iwcw}" |
@@ -1196,8 +1196,8 @@ file: | @@ -1196,8 +1196,8 @@ file: | ||
1196 | staticUrl: /oss/files/** #oss静态访问路径 只有type = local需要 | 1196 | staticUrl: /oss/files/** #oss静态访问路径 只有type = local需要 |
1197 | randomFileName: ${file.storage.randomFileName} | 1197 | randomFileName: ${file.storage.randomFileName} |
1198 | minio: | 1198 | minio: |
1199 | - minioUrl: ${MINIO_URL:https://dev.thingskit.com:9000} #minio储存地址 | ||
1200 | -# minioUrl: https://demo.thingskit.com:9000 #minio储存地址 | 1199 | +# minioUrl: ${MINIO_URL:https://dev.thingskit.com:9000} #minio储存地址 |
1200 | + minioUrl: https://demo.thingskit.com:9000 #minio储存地址 | ||
1201 | minioName: ${MINIO_NAME:YunTeng} #minio账户 | 1201 | minioName: ${MINIO_NAME:YunTeng} #minio账户 |
1202 | minioPass: ${MINIO_PWD:YunTeng123456} #minio访问密码 | 1202 | minioPass: ${MINIO_PWD:YunTeng123456} #minio访问密码 |
1203 | bucketName: yunteng #minio储存桶名称 | 1203 | bucketName: yunteng #minio储存桶名称 |
@@ -26,10 +26,11 @@ public class TcpDeviceProfileTransportConfiguration implements DeviceProfileTran | @@ -26,10 +26,11 @@ public class TcpDeviceProfileTransportConfiguration implements DeviceProfileTran | ||
26 | @NoXss | 26 | @NoXss |
27 | private TcpDataTypeEnum dataFormat = TcpDataTypeEnum.HEX; | 27 | private TcpDataTypeEnum dataFormat = TcpDataTypeEnum.HEX; |
28 | private String scriptId; | 28 | private String scriptId; |
29 | + private String pingText; | ||
29 | 30 | ||
30 | @Override | 31 | @Override |
31 | public DeviceTransportType getType() { | 32 | public DeviceTransportType getType() { |
32 | - return DeviceTransportType.MQTT; | 33 | + return DeviceTransportType.TCP; |
33 | } | 34 | } |
34 | 35 | ||
35 | 36 |
@@ -27,7 +27,7 @@ | @@ -27,7 +27,7 @@ | ||
27 | <artifactId>tcp</artifactId> | 27 | <artifactId>tcp</artifactId> |
28 | <packaging>jar</packaging> | 28 | <packaging>jar</packaging> |
29 | 29 | ||
30 | - <name>Thingsboard TPC Transport Common</name> | 30 | + <name>Thingsboard TCP Transport Common</name> |
31 | <url>https://thingsboard.io</url> | 31 | <url>https://thingsboard.io</url> |
32 | 32 | ||
33 | <properties> | 33 | <properties> |
@@ -25,7 +25,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; | @@ -25,7 +25,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; | ||
25 | import org.springframework.stereotype.Component; | 25 | import org.springframework.stereotype.Component; |
26 | import org.thingsboard.server.common.transport.TransportContext; | 26 | import org.thingsboard.server.common.transport.TransportContext; |
27 | import org.thingsboard.server.transport.tcp.adaptors.JsonTcpAdaptor; | 27 | import org.thingsboard.server.transport.tcp.adaptors.JsonTcpAdaptor; |
28 | -import org.thingsboard.server.transport.tcp.adaptors.ProtoTcpAdaptor; | ||
29 | 28 | ||
30 | import javax.annotation.PostConstruct; | 29 | import javax.annotation.PostConstruct; |
31 | import java.net.InetSocketAddress; | 30 | import java.net.InetSocketAddress; |
@@ -45,18 +44,15 @@ public class TcpTransportContext extends TransportContext { | @@ -45,18 +44,15 @@ public class TcpTransportContext extends TransportContext { | ||
45 | 44 | ||
46 | @Getter | 45 | @Getter |
47 | @Autowired | 46 | @Autowired |
48 | - private JsonTcpAdaptor jsonMqttAdaptor; | 47 | + private JsonTcpAdaptor jsonTcpAdaptor; |
49 | 48 | ||
50 | - @Getter | ||
51 | - @Autowired | ||
52 | - private ProtoTcpAdaptor protoMqttAdaptor; | ||
53 | 49 | ||
54 | @Getter | 50 | @Getter |
55 | - @Value("${transport.mqtt.netty.max_payload_size}") | 51 | + @Value("${transport.tcp.netty.max_payload_size}") |
56 | private Integer maxPayloadSize; | 52 | private Integer maxPayloadSize; |
57 | 53 | ||
58 | @Getter | 54 | @Getter |
59 | - @Value("${transport.mqtt.ssl.skip_validity_check_for_client_cert:false}") | 55 | + @Value("${transport.tcp.ssl.skip_validity_check_for_client_cert:false}") |
60 | private boolean skipValidityCheckForClientCert; | 56 | private boolean skipValidityCheckForClientCert; |
61 | 57 | ||
62 | @Getter | 58 | @Getter |
@@ -64,15 +60,15 @@ public class TcpTransportContext extends TransportContext { | @@ -64,15 +60,15 @@ public class TcpTransportContext extends TransportContext { | ||
64 | private SslHandler sslHandler; | 60 | private SslHandler sslHandler; |
65 | 61 | ||
66 | @Getter | 62 | @Getter |
67 | - @Value("${transport.mqtt.msg_queue_size_per_device_limit:100}") | 63 | + @Value("${transport.tcp.msg_queue_size_per_device_limit:100}") |
68 | private int messageQueueSizePerDeviceLimit; | 64 | private int messageQueueSizePerDeviceLimit; |
69 | 65 | ||
70 | @Getter | 66 | @Getter |
71 | - @Value("${transport.mqtt.timeout:10000}") | 67 | + @Value("${transport.tcp.timeout:10000}") |
72 | private long timeout; | 68 | private long timeout; |
73 | 69 | ||
74 | @Getter | 70 | @Getter |
75 | - @Value("${transport.mqtt.proxy_enabled:false}") | 71 | + @Value("${transport.tcp.proxy_enabled:false}") |
76 | private boolean proxyEnabled; | 72 | private boolean proxyEnabled; |
77 | 73 | ||
78 | private final AtomicInteger connectionsCounter = new AtomicInteger(); | 74 | private final AtomicInteger connectionsCounter = new AtomicInteger(); |
@@ -15,43 +15,25 @@ | @@ -15,43 +15,25 @@ | ||
15 | */ | 15 | */ |
16 | package org.thingsboard.server.transport.tcp; | 16 | package org.thingsboard.server.transport.tcp; |
17 | 17 | ||
18 | -import com.fasterxml.jackson.databind.JsonNode; | ||
19 | import com.google.gson.JsonParseException; | 18 | import com.google.gson.JsonParseException; |
19 | +import io.netty.buffer.ByteBuf; | ||
20 | +import io.netty.buffer.Unpooled; | ||
20 | import io.netty.channel.ChannelFuture; | 21 | import io.netty.channel.ChannelFuture; |
21 | import io.netty.channel.ChannelHandlerContext; | 22 | import io.netty.channel.ChannelHandlerContext; |
22 | import io.netty.channel.ChannelInboundHandlerAdapter; | 23 | import io.netty.channel.ChannelInboundHandlerAdapter; |
23 | -import io.netty.handler.codec.mqtt.MqttConnAckMessage; | ||
24 | -import io.netty.handler.codec.mqtt.MqttConnAckVariableHeader; | ||
25 | -import io.netty.handler.codec.mqtt.MqttConnectMessage; | ||
26 | -import io.netty.handler.codec.mqtt.MqttConnectReturnCode; | ||
27 | -import io.netty.handler.codec.mqtt.MqttFixedHeader; | ||
28 | -import io.netty.handler.codec.mqtt.MqttMessage; | ||
29 | -import io.netty.handler.codec.mqtt.MqttMessageIdVariableHeader; | ||
30 | -import io.netty.handler.codec.mqtt.MqttPubAckMessage; | ||
31 | -import io.netty.handler.codec.mqtt.MqttPublishMessage; | ||
32 | -import io.netty.handler.codec.mqtt.MqttQoS; | ||
33 | -import io.netty.handler.codec.mqtt.MqttSubAckMessage; | ||
34 | -import io.netty.handler.codec.mqtt.MqttSubAckPayload; | ||
35 | -import io.netty.handler.codec.mqtt.MqttSubscribeMessage; | ||
36 | -import io.netty.handler.codec.mqtt.MqttTopicSubscription; | ||
37 | -import io.netty.handler.codec.mqtt.MqttUnsubscribeMessage; | 24 | +import io.netty.handler.codec.mqtt.*; |
38 | import io.netty.handler.ssl.SslHandler; | 25 | import io.netty.handler.ssl.SslHandler; |
39 | -import io.netty.util.CharsetUtil; | ||
40 | import io.netty.util.ReferenceCountUtil; | 26 | import io.netty.util.ReferenceCountUtil; |
41 | import io.netty.util.concurrent.Future; | 27 | import io.netty.util.concurrent.Future; |
42 | import io.netty.util.concurrent.GenericFutureListener; | 28 | import io.netty.util.concurrent.GenericFutureListener; |
43 | import lombok.extern.slf4j.Slf4j; | 29 | import lombok.extern.slf4j.Slf4j; |
44 | import org.apache.commons.lang3.StringUtils; | 30 | import org.apache.commons.lang3.StringUtils; |
45 | -import org.thingsboard.server.common.data.DataConstants; | ||
46 | -import org.thingsboard.server.common.data.Device; | ||
47 | -import org.thingsboard.server.common.data.DeviceProfile; | ||
48 | -import org.thingsboard.server.common.data.DeviceTransportType; | ||
49 | -import org.thingsboard.server.common.data.TransportPayloadType; | 31 | +import org.thingsboard.server.common.data.*; |
50 | import org.thingsboard.server.common.data.device.profile.MqttTopics; | 32 | import org.thingsboard.server.common.data.device.profile.MqttTopics; |
51 | import org.thingsboard.server.common.data.id.DeviceId; | 33 | import org.thingsboard.server.common.data.id.DeviceId; |
52 | import org.thingsboard.server.common.data.id.OtaPackageId; | 34 | import org.thingsboard.server.common.data.id.OtaPackageId; |
53 | import org.thingsboard.server.common.data.ota.OtaPackageType; | 35 | import org.thingsboard.server.common.data.ota.OtaPackageType; |
54 | -import org.thingsboard.server.common.data.rpc.RpcStatus; | 36 | +import org.thingsboard.server.common.data.yunteng.enums.TcpDataTypeEnum; |
55 | import org.thingsboard.server.common.msg.EncryptionUtil; | 37 | import org.thingsboard.server.common.msg.EncryptionUtil; |
56 | import org.thingsboard.server.common.msg.tools.TbRateLimitsException; | 38 | import org.thingsboard.server.common.msg.tools.TbRateLimitsException; |
57 | import org.thingsboard.server.common.transport.SessionMsgListener; | 39 | import org.thingsboard.server.common.transport.SessionMsgListener; |
@@ -59,10 +41,7 @@ import org.thingsboard.server.common.transport.TransportService; | @@ -59,10 +41,7 @@ import org.thingsboard.server.common.transport.TransportService; | ||
59 | import org.thingsboard.server.common.transport.TransportServiceCallback; | 41 | import org.thingsboard.server.common.transport.TransportServiceCallback; |
60 | import org.thingsboard.server.common.transport.adaptor.AdaptorException; | 42 | import org.thingsboard.server.common.transport.adaptor.AdaptorException; |
61 | import org.thingsboard.server.common.transport.auth.SessionInfoCreator; | 43 | import org.thingsboard.server.common.transport.auth.SessionInfoCreator; |
62 | -import org.thingsboard.server.common.transport.auth.TransportDeviceInfo; | ||
63 | import org.thingsboard.server.common.transport.auth.ValidateDeviceCredentialsResponse; | 44 | import org.thingsboard.server.common.transport.auth.ValidateDeviceCredentialsResponse; |
64 | -import org.thingsboard.server.common.transport.service.DefaultTransportService; | ||
65 | -import org.thingsboard.server.common.transport.service.SessionMetaData; | ||
66 | import org.thingsboard.server.common.transport.util.SslUtil; | 45 | import org.thingsboard.server.common.transport.util.SslUtil; |
67 | import org.thingsboard.server.gen.transport.TransportProtos; | 46 | import org.thingsboard.server.gen.transport.TransportProtos; |
68 | import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsg; | 47 | import org.thingsboard.server.gen.transport.TransportProtos.ProvisionDeviceResponseMsg; |
@@ -70,37 +49,26 @@ import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceX509Ce | @@ -70,37 +49,26 @@ import org.thingsboard.server.gen.transport.TransportProtos.ValidateDeviceX509Ce | ||
70 | import org.thingsboard.server.queue.scheduler.SchedulerComponent; | 49 | import org.thingsboard.server.queue.scheduler.SchedulerComponent; |
71 | import org.thingsboard.server.transport.tcp.adaptors.TcpTransportAdaptor; | 50 | import org.thingsboard.server.transport.tcp.adaptors.TcpTransportAdaptor; |
72 | import org.thingsboard.server.transport.tcp.session.DeviceSessionCtx; | 51 | import org.thingsboard.server.transport.tcp.session.DeviceSessionCtx; |
73 | -import org.thingsboard.server.transport.tcp.session.GatewaySessionHandler; | ||
74 | -import org.thingsboard.server.transport.tcp.session.MqttTopicMatcher; | 52 | +import org.thingsboard.server.transport.tcp.session.TCPMessage; |
53 | +import org.thingsboard.server.transport.tcp.util.ByteUtils; | ||
75 | 54 | ||
76 | import javax.net.ssl.SSLPeerUnverifiedException; | 55 | import javax.net.ssl.SSLPeerUnverifiedException; |
77 | -import java.io.IOException; | ||
78 | import java.net.InetSocketAddress; | 56 | import java.net.InetSocketAddress; |
79 | import java.security.cert.Certificate; | 57 | import java.security.cert.Certificate; |
80 | import java.security.cert.X509Certificate; | 58 | import java.security.cert.X509Certificate; |
81 | -import java.util.ArrayList; | ||
82 | import java.util.List; | 59 | import java.util.List; |
83 | import java.util.Optional; | 60 | import java.util.Optional; |
84 | import java.util.UUID; | 61 | import java.util.UUID; |
85 | -import java.util.concurrent.Callable; | ||
86 | import java.util.concurrent.ConcurrentHashMap; | 62 | import java.util.concurrent.ConcurrentHashMap; |
87 | import java.util.concurrent.ConcurrentMap; | 63 | import java.util.concurrent.ConcurrentMap; |
88 | -import java.util.concurrent.TimeUnit; | ||
89 | import java.util.regex.Matcher; | 64 | import java.util.regex.Matcher; |
90 | import java.util.regex.Pattern; | 65 | import java.util.regex.Pattern; |
91 | 66 | ||
92 | import static com.amazonaws.util.StringUtils.UTF8; | 67 | import static com.amazonaws.util.StringUtils.UTF8; |
93 | import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.CONNECTION_ACCEPTED; | 68 | import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.CONNECTION_ACCEPTED; |
94 | import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED; | 69 | import static io.netty.handler.codec.mqtt.MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED; |
95 | -import static io.netty.handler.codec.mqtt.MqttMessageType.CONNACK; | ||
96 | -import static io.netty.handler.codec.mqtt.MqttMessageType.CONNECT; | ||
97 | -import static io.netty.handler.codec.mqtt.MqttMessageType.PINGRESP; | ||
98 | -import static io.netty.handler.codec.mqtt.MqttMessageType.PUBACK; | ||
99 | -import static io.netty.handler.codec.mqtt.MqttMessageType.SUBACK; | ||
100 | -import static io.netty.handler.codec.mqtt.MqttMessageType.UNSUBACK; | ||
101 | -import static io.netty.handler.codec.mqtt.MqttQoS.AT_LEAST_ONCE; | ||
102 | -import static io.netty.handler.codec.mqtt.MqttQoS.AT_MOST_ONCE; | ||
103 | -import static io.netty.handler.codec.mqtt.MqttQoS.FAILURE; | 70 | +import static io.netty.handler.codec.mqtt.MqttMessageType.*; |
71 | +import static io.netty.handler.codec.mqtt.MqttQoS.*; | ||
104 | import static org.thingsboard.server.common.transport.service.DefaultTransportService.SESSION_EVENT_MSG_CLOSED; | 72 | import static org.thingsboard.server.common.transport.service.DefaultTransportService.SESSION_EVENT_MSG_CLOSED; |
105 | import static org.thingsboard.server.common.transport.service.DefaultTransportService.SESSION_EVENT_MSG_OPEN; | 73 | import static org.thingsboard.server.common.transport.service.DefaultTransportService.SESSION_EVENT_MSG_OPEN; |
106 | 74 | ||
@@ -123,11 +91,11 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -123,11 +91,11 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
123 | private final TransportService transportService; | 91 | private final TransportService transportService; |
124 | private final SchedulerComponent scheduler; | 92 | private final SchedulerComponent scheduler; |
125 | private final SslHandler sslHandler; | 93 | private final SslHandler sslHandler; |
126 | - private final ConcurrentMap<MqttTopicMatcher, Integer> mqttQoSMap; | ||
127 | 94 | ||
95 | + | ||
96 | + /**需要处理的消息队列,例如:需要下发给设备的,设备上传的。*/ | ||
128 | final DeviceSessionCtx deviceSessionCtx; | 97 | final DeviceSessionCtx deviceSessionCtx; |
129 | volatile InetSocketAddress address; | 98 | volatile InetSocketAddress address; |
130 | - volatile GatewaySessionHandler gatewaySessionHandler; | ||
131 | 99 | ||
132 | private final ConcurrentHashMap<String, String> otaPackSessions; | 100 | private final ConcurrentHashMap<String, String> otaPackSessions; |
133 | private final ConcurrentHashMap<String, Integer> chunkSizes; | 101 | private final ConcurrentHashMap<String, Integer> chunkSizes; |
@@ -144,8 +112,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -144,8 +112,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
144 | this.transportService = context.getTransportService(); | 112 | this.transportService = context.getTransportService(); |
145 | this.scheduler = context.getScheduler(); | 113 | this.scheduler = context.getScheduler(); |
146 | this.sslHandler = sslHandler; | 114 | this.sslHandler = sslHandler; |
147 | - this.mqttQoSMap = new ConcurrentHashMap<>(); | ||
148 | - this.deviceSessionCtx = new DeviceSessionCtx(sessionId, mqttQoSMap, context); | 115 | + this.deviceSessionCtx = new DeviceSessionCtx(sessionId, context); |
149 | this.otaPackSessions = new ConcurrentHashMap<>(); | 116 | this.otaPackSessions = new ConcurrentHashMap<>(); |
150 | this.chunkSizes = new ConcurrentHashMap<>(); | 117 | this.chunkSizes = new ConcurrentHashMap<>(); |
151 | this.rpcAwaitingAck = new ConcurrentHashMap<>(); | 118 | this.rpcAwaitingAck = new ConcurrentHashMap<>(); |
@@ -165,21 +132,18 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -165,21 +132,18 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
165 | 132 | ||
166 | @Override | 133 | @Override |
167 | public void channelRead(ChannelHandlerContext ctx, Object msg) { | 134 | public void channelRead(ChannelHandlerContext ctx, Object msg) { |
168 | - log.trace("[{}] Processing msg: {}", sessionId, msg); | 135 | + log.trace("【{}】 Processing msg: 【{}】", sessionId, msg); |
169 | if (address == null) { | 136 | if (address == null) { |
170 | address = getAddress(ctx); | 137 | address = getAddress(ctx); |
171 | } | 138 | } |
172 | try { | 139 | try { |
173 | - if (msg instanceof MqttMessage) { | ||
174 | - MqttMessage message = (MqttMessage) msg; | ||
175 | - if (message.decoderResult().isSuccess()) { | ||
176 | - processMqttMsg(ctx, message); | ||
177 | - } else { | ||
178 | - log.error("[{}] Message decoding failed: {}", sessionId, message.decoderResult().cause().getMessage()); | ||
179 | - ctx.close(); | ||
180 | - } | 140 | + if (msg instanceof ByteBuf) { |
141 | + ByteBuf message = (ByteBuf) msg; | ||
142 | + | ||
143 | + processTcpMsg(ctx, ByteUtils.buf2Bytes(message)); | ||
144 | + | ||
181 | } else { | 145 | } else { |
182 | - log.debug("[{}] Received non mqtt message: {}", sessionId, msg.getClass().getSimpleName()); | 146 | + log.debug("【{}】 Received non tcp message: 【{}】", sessionId, msg.getClass().getSimpleName()); |
183 | ctx.close(); | 147 | ctx.close(); |
184 | } | 148 | } |
185 | } finally { | 149 | } finally { |
@@ -200,19 +164,12 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -200,19 +164,12 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
200 | return address; | 164 | return address; |
201 | } | 165 | } |
202 | 166 | ||
203 | - void processMqttMsg(ChannelHandlerContext ctx, MqttMessage msg) { | ||
204 | - if (msg.fixedHeader() == null) { | ||
205 | - log.info("[{}:{}] Invalid message received", address.getHostName(), address.getPort()); | ||
206 | - ctx.close(); | ||
207 | - return; | ||
208 | - } | 167 | + void processTcpMsg(ChannelHandlerContext ctx, byte[] msg) { |
209 | deviceSessionCtx.setChannel(ctx); | 168 | deviceSessionCtx.setChannel(ctx); |
210 | - if (CONNECT.equals(msg.fixedHeader().messageType())) { | ||
211 | - processConnect(ctx, (MqttConnectMessage) msg); | ||
212 | - } else if (deviceSessionCtx.isProvisionOnly()) { | ||
213 | - processProvisionSessionMsg(ctx, msg); | 169 | + if (deviceSessionCtx.getDeviceInfo() == null || deviceSessionCtx.getDeviceProfile() == null) { |
170 | + processConnect(ctx, ByteUtils.getString(msg, ByteUtils.UTF_8)); | ||
214 | } else { | 171 | } else { |
215 | - enqueueRegularSessionMsg(ctx, msg); | 172 | + enqueueRegularSessionMsg(ctx,msg); |
216 | } | 173 | } |
217 | } | 174 | } |
218 | 175 | ||
@@ -225,12 +182,12 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -225,12 +182,12 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
225 | try { | 182 | try { |
226 | if (topicName.equals(MqttTopics.DEVICE_PROVISION_REQUEST_TOPIC)) { | 183 | if (topicName.equals(MqttTopics.DEVICE_PROVISION_REQUEST_TOPIC)) { |
227 | try { | 184 | try { |
228 | - TransportProtos.ProvisionDeviceRequestMsg provisionRequestMsg = deviceSessionCtx.getContext().getJsonMqttAdaptor().convertToProvisionRequestMsg(deviceSessionCtx, mqttMsg); | 185 | + TransportProtos.ProvisionDeviceRequestMsg provisionRequestMsg = deviceSessionCtx.getContext().getJsonTcpAdaptor().convertToProvisionRequestMsg(deviceSessionCtx, mqttMsg); |
229 | transportService.process(provisionRequestMsg, new DeviceProvisionCallback(ctx, msgId, provisionRequestMsg)); | 186 | transportService.process(provisionRequestMsg, new DeviceProvisionCallback(ctx, msgId, provisionRequestMsg)); |
230 | log.trace("[{}][{}] Processing provision publish msg [{}][{}]!", sessionId, deviceSessionCtx.getDeviceId(), topicName, msgId); | 187 | log.trace("[{}][{}] Processing provision publish msg [{}][{}]!", sessionId, deviceSessionCtx.getDeviceId(), topicName, msgId); |
231 | } catch (Exception e) { | 188 | } catch (Exception e) { |
232 | if (e instanceof JsonParseException || (e.getCause() != null && e.getCause() instanceof JsonParseException)) { | 189 | if (e instanceof JsonParseException || (e.getCause() != null && e.getCause() instanceof JsonParseException)) { |
233 | - TransportProtos.ProvisionDeviceRequestMsg provisionRequestMsg = deviceSessionCtx.getContext().getProtoMqttAdaptor().convertToProvisionRequestMsg(deviceSessionCtx, mqttMsg); | 190 | + TransportProtos.ProvisionDeviceRequestMsg provisionRequestMsg = deviceSessionCtx.getContext().getAscallAdaptor().convertToProvisionRequestMsg(deviceSessionCtx, mqttMsg); |
234 | transportService.process(provisionRequestMsg, new DeviceProvisionCallback(ctx, msgId, provisionRequestMsg)); | 191 | transportService.process(provisionRequestMsg, new DeviceProvisionCallback(ctx, msgId, provisionRequestMsg)); |
235 | deviceSessionCtx.setProvisionPayloadType(TransportPayloadType.PROTOBUF); | 192 | deviceSessionCtx.setProvisionPayloadType(TransportPayloadType.PROTOBUF); |
236 | log.trace("[{}][{}] Processing provision publish msg [{}][{}]!", sessionId, deviceSessionCtx.getDeviceId(), topicName, msgId); | 193 | log.trace("[{}][{}] Processing provision publish msg [{}][{}]!", sessionId, deviceSessionCtx.getDeviceId(), topicName, msgId); |
@@ -259,7 +216,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -259,7 +216,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
259 | } | 216 | } |
260 | } | 217 | } |
261 | 218 | ||
262 | - void enqueueRegularSessionMsg(ChannelHandlerContext ctx, MqttMessage msg) { | 219 | + void enqueueRegularSessionMsg(ChannelHandlerContext ctx, byte[] msg) { |
263 | final int queueSize = deviceSessionCtx.getMsgQueueSize(); | 220 | final int queueSize = deviceSessionCtx.getMsgQueueSize(); |
264 | if (queueSize >= context.getMessageQueueSizePerDeviceLimit()) { | 221 | if (queueSize >= context.getMessageQueueSizePerDeviceLimit()) { |
265 | log.info("Closing current session because msq queue size for device {} exceed limit {} with msgQueueSize counter {} and actual queue size {}", | 222 | log.info("Closing current session because msq queue size for device {} exceed limit {} with msgQueueSize counter {} and actual queue size {}", |
@@ -268,10 +225,12 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -268,10 +225,12 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
268 | return; | 225 | return; |
269 | } | 226 | } |
270 | 227 | ||
271 | - deviceSessionCtx.addToQueue(msg); | 228 | + deviceSessionCtx.addToQueue(new TCPMessage(MqttMessageType.PUBLISH,msg)); |
272 | processMsgQueue(ctx); //Under the normal conditions the msg queue will contain 0 messages. Many messages will be processed on device connect event in separate thread pool | 229 | processMsgQueue(ctx); //Under the normal conditions the msg queue will contain 0 messages. Many messages will be processed on device connect event in separate thread pool |
273 | } | 230 | } |
274 | 231 | ||
232 | + | ||
233 | + | ||
275 | void processMsgQueue(ChannelHandlerContext ctx) { | 234 | void processMsgQueue(ChannelHandlerContext ctx) { |
276 | if (!deviceSessionCtx.isConnected()) { | 235 | if (!deviceSessionCtx.isConnected()) { |
277 | log.trace("[{}][{}] Postpone processing msg due to device is not connected. Msg queue size is {}", sessionId, deviceSessionCtx.getDeviceId(), deviceSessionCtx.getMsgQueueSize()); | 236 | log.trace("[{}][{}] Postpone processing msg due to device is not connected. Msg queue size is {}", sessionId, deviceSessionCtx.getDeviceId(), deviceSessionCtx.getMsgQueueSize()); |
@@ -280,175 +239,143 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -280,175 +239,143 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
280 | deviceSessionCtx.tryProcessQueuedMsgs(msg -> processRegularSessionMsg(ctx, msg)); | 239 | deviceSessionCtx.tryProcessQueuedMsgs(msg -> processRegularSessionMsg(ctx, msg)); |
281 | } | 240 | } |
282 | 241 | ||
283 | - void processRegularSessionMsg(ChannelHandlerContext ctx, MqttMessage msg) { | ||
284 | - switch (msg.fixedHeader().messageType()) { | 242 | + void processRegularSessionMsg(ChannelHandlerContext ctx, TCPMessage msg) { |
243 | + switch (msg.getMessageType()) { | ||
285 | case PUBLISH: | 244 | case PUBLISH: |
286 | - processPublish(ctx, (MqttPublishMessage) msg); | 245 | + processPublish(ctx, msg); |
287 | break; | 246 | break; |
288 | case SUBSCRIBE: | 247 | case SUBSCRIBE: |
289 | - processSubscribe(ctx, (MqttSubscribeMessage) msg); | 248 | +// processSubscribe(ctx, (MqttSubscribeMessage) msg); |
290 | break; | 249 | break; |
291 | case UNSUBSCRIBE: | 250 | case UNSUBSCRIBE: |
292 | - processUnsubscribe(ctx, (MqttUnsubscribeMessage) msg); | ||
293 | - break; | ||
294 | - case PINGREQ: | ||
295 | - if (checkConnected(ctx, msg)) { | ||
296 | - ctx.writeAndFlush(new MqttMessage(new MqttFixedHeader(PINGRESP, false, AT_MOST_ONCE, false, 0))); | ||
297 | - transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
298 | - } | 251 | +// processUnsubscribe(ctx, (MqttUnsubscribeMessage) msg); |
299 | break; | 252 | break; |
253 | + | ||
300 | case DISCONNECT: | 254 | case DISCONNECT: |
301 | ctx.close(); | 255 | ctx.close(); |
302 | break; | 256 | break; |
303 | case PUBACK: | 257 | case PUBACK: |
304 | - int msgId = ((MqttPubAckMessage) msg).variableHeader().messageId(); | ||
305 | - TransportProtos.ToDeviceRpcRequestMsg rpcRequest = rpcAwaitingAck.remove(msgId); | ||
306 | - if (rpcRequest != null) { | ||
307 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); | ||
308 | - } | 258 | +// int msgId = ((MqttPubAckMessage) msg).variableHeader().messageId(); |
259 | +// TransportProtos.ToDeviceRpcRequestMsg rpcRequest = rpcAwaitingAck.remove(msgId); | ||
260 | +// if (rpcRequest != null) { | ||
261 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); | ||
262 | +// } | ||
309 | break; | 263 | break; |
310 | default: | 264 | default: |
311 | break; | 265 | break; |
312 | } | 266 | } |
313 | } | 267 | } |
314 | 268 | ||
315 | - private void processPublish(ChannelHandlerContext ctx, MqttPublishMessage mqttMsg) { | 269 | + private ByteBuf toDeviceMsg(byte[] msgs){ |
270 | + return Unpooled.copiedBuffer(msgs); | ||
271 | + } | ||
272 | + | ||
273 | + private String textFromMessage(byte[] payload){ | ||
274 | + if(deviceSessionCtx.getPayloadType().equals(TcpDataTypeEnum.ASCII)){ | ||
275 | + return ByteUtils.getString(payload,ByteUtils.UTF_8); | ||
276 | + }else{ | ||
277 | + return ByteUtils.bytesToHex(payload); | ||
278 | + } | ||
279 | + } | ||
280 | + private void processPublish(ChannelHandlerContext ctx, TCPMessage mqttMsg) { | ||
316 | if (!checkConnected(ctx, mqttMsg)) { | 281 | if (!checkConnected(ctx, mqttMsg)) { |
317 | return; | 282 | return; |
318 | } | 283 | } |
319 | - String topicName = mqttMsg.variableHeader().topicName(); | ||
320 | - int msgId = mqttMsg.variableHeader().packetId(); | ||
321 | - log.trace("[{}][{}] Processing publish msg [{}][{}]!", sessionId, deviceSessionCtx.getDeviceId(), topicName, msgId); | ||
322 | - | ||
323 | - if (topicName.startsWith(MqttTopics.BASE_GATEWAY_API_TOPIC)) { | ||
324 | - if (gatewaySessionHandler != null) { | ||
325 | - handleGatewayPublishMsg(ctx, topicName, msgId, mqttMsg); | ||
326 | - transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
327 | - } | ||
328 | - } else { | ||
329 | - processDevicePublish(ctx, mqttMsg, topicName, msgId); | 284 | + if(deviceSessionCtx.getPingText().equals(mqttMsg.getMessage())){ |
285 | + ctx.channel().writeAndFlush(toDeviceMsg(mqttMsg.getMessage())); | ||
286 | + transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
287 | + return; | ||
330 | } | 288 | } |
331 | - } | 289 | + String dataStr = textFromMessage(mqttMsg.getMessage()); |
290 | + log.trace("[{}][{}] Processing publish msg [{}]!", sessionId, deviceSessionCtx.getDeviceId(), dataStr); | ||
332 | 291 | ||
333 | - private void handleGatewayPublishMsg(ChannelHandlerContext ctx, String topicName, int msgId, MqttPublishMessage mqttMsg) { | ||
334 | - try { | ||
335 | - switch (topicName) { | ||
336 | - case MqttTopics.GATEWAY_TELEMETRY_TOPIC: | ||
337 | - gatewaySessionHandler.onDeviceTelemetry(mqttMsg); | ||
338 | - break; | ||
339 | - case MqttTopics.GATEWAY_CLAIM_TOPIC: | ||
340 | - gatewaySessionHandler.onDeviceClaim(mqttMsg); | ||
341 | - break; | ||
342 | - case MqttTopics.GATEWAY_ATTRIBUTES_TOPIC: | ||
343 | - gatewaySessionHandler.onDeviceAttributes(mqttMsg); | ||
344 | - break; | ||
345 | - case MqttTopics.GATEWAY_ATTRIBUTES_REQUEST_TOPIC: | ||
346 | - gatewaySessionHandler.onDeviceAttributesRequest(mqttMsg); | ||
347 | - break; | ||
348 | - case MqttTopics.GATEWAY_RPC_TOPIC: | ||
349 | - gatewaySessionHandler.onDeviceRpcResponse(mqttMsg); | ||
350 | - break; | ||
351 | - case MqttTopics.GATEWAY_CONNECT_TOPIC: | ||
352 | - gatewaySessionHandler.onDeviceConnect(mqttMsg); | ||
353 | - break; | ||
354 | - case MqttTopics.GATEWAY_DISCONNECT_TOPIC: | ||
355 | - gatewaySessionHandler.onDeviceDisconnect(mqttMsg); | ||
356 | - break; | ||
357 | - default: | ||
358 | - ack(ctx, msgId); | ||
359 | - } | ||
360 | - } catch (RuntimeException e) { | ||
361 | - log.warn("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e); | ||
362 | - ctx.close(); | ||
363 | - } catch (AdaptorException e) { | ||
364 | - log.debug("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e); | ||
365 | - ctx.close(); | ||
366 | - } | 292 | + processDevicePublish(ctx, mqttMsg, topicName, msgId); |
367 | } | 293 | } |
368 | 294 | ||
295 | + | ||
369 | private void processDevicePublish(ChannelHandlerContext ctx, MqttPublishMessage mqttMsg, String topicName, int msgId) { | 296 | private void processDevicePublish(ChannelHandlerContext ctx, MqttPublishMessage mqttMsg, String topicName, int msgId) { |
370 | try { | 297 | try { |
371 | - Matcher fwMatcher; | 298 | +// Matcher fwMatcher; |
372 | TcpTransportAdaptor payloadAdaptor = deviceSessionCtx.getPayloadAdaptor(); | 299 | TcpTransportAdaptor payloadAdaptor = deviceSessionCtx.getPayloadAdaptor(); |
373 | - if (deviceSessionCtx.isDeviceAttributesTopic(topicName)) { | ||
374 | - TransportProtos.PostAttributeMsg postAttributeMsg = payloadAdaptor.convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
375 | - transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
376 | - } else if (deviceSessionCtx.isDeviceTelemetryTopic(topicName)) { | ||
377 | - TransportProtos.PostTelemetryMsg postTelemetryMsg = payloadAdaptor.convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
378 | - transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
379 | - } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX)) { | ||
380 | - TransportProtos.GetAttributeRequestMsg getAttributeMsg = payloadAdaptor.convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX); | ||
381 | - transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
382 | - attrReqTopicType = TopicType.V1; | ||
383 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_TOPIC)) { | ||
384 | - TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = payloadAdaptor.convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_TOPIC); | ||
385 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
386 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_TOPIC)) { | ||
387 | - TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = payloadAdaptor.convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_TOPIC); | ||
388 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
389 | - toServerRpcSubTopicType = TopicType.V1; | ||
390 | - } else if (topicName.equals(MqttTopics.DEVICE_CLAIM_TOPIC)) { | ||
391 | - TransportProtos.ClaimDeviceMsg claimDeviceMsg = payloadAdaptor.convertToClaimDevice(deviceSessionCtx, mqttMsg); | ||
392 | - transportService.process(deviceSessionCtx.getSessionInfo(), claimDeviceMsg, getPubAckCallback(ctx, msgId, claimDeviceMsg)); | ||
393 | - } else if ((fwMatcher = FW_REQUEST_PATTERN.matcher(topicName)).find()) { | ||
394 | - getOtaPackageCallback(ctx, mqttMsg, msgId, fwMatcher, OtaPackageType.FIRMWARE); | ||
395 | - } else if ((fwMatcher = SW_REQUEST_PATTERN.matcher(topicName)).find()) { | ||
396 | - getOtaPackageCallback(ctx, mqttMsg, msgId, fwMatcher, OtaPackageType.SOFTWARE); | ||
397 | - } else if (topicName.equals(MqttTopics.DEVICE_TELEMETRY_SHORT_TOPIC)) { | ||
398 | - TransportProtos.PostTelemetryMsg postTelemetryMsg = payloadAdaptor.convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
399 | - transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
400 | - } else if (topicName.equals(MqttTopics.DEVICE_TELEMETRY_SHORT_JSON_TOPIC)) { | ||
401 | - TransportProtos.PostTelemetryMsg postTelemetryMsg = context.getJsonMqttAdaptor().convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
402 | - transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
403 | - } else if (topicName.equals(MqttTopics.DEVICE_TELEMETRY_SHORT_PROTO_TOPIC)) { | ||
404 | - TransportProtos.PostTelemetryMsg postTelemetryMsg = context.getProtoMqttAdaptor().convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
405 | - transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
406 | - } else if (topicName.equals(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC)) { | ||
407 | - TransportProtos.PostAttributeMsg postAttributeMsg = payloadAdaptor.convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
408 | - transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
409 | - } else if (topicName.equals(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC)) { | ||
410 | - TransportProtos.PostAttributeMsg postAttributeMsg = context.getJsonMqttAdaptor().convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
411 | - transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
412 | - } else if (topicName.equals(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC)) { | ||
413 | - TransportProtos.PostAttributeMsg postAttributeMsg = context.getProtoMqttAdaptor().convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
414 | - transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
415 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_SHORT_JSON_TOPIC)) { | ||
416 | - TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = context.getJsonMqttAdaptor().convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_JSON_TOPIC); | ||
417 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
418 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_SHORT_PROTO_TOPIC)) { | ||
419 | - TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = context.getProtoMqttAdaptor().convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_PROTO_TOPIC); | ||
420 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
421 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_SHORT_TOPIC)) { | ||
422 | - TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = payloadAdaptor.convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_TOPIC); | ||
423 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
424 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_SHORT_JSON_TOPIC)) { | ||
425 | - TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = context.getJsonMqttAdaptor().convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_JSON_TOPIC); | ||
426 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
427 | - toServerRpcSubTopicType = TopicType.V2_JSON; | ||
428 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_SHORT_PROTO_TOPIC)) { | ||
429 | - TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = context.getProtoMqttAdaptor().convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_PROTO_TOPIC); | ||
430 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
431 | - toServerRpcSubTopicType = TopicType.V2_PROTO; | ||
432 | - } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_SHORT_TOPIC)) { | ||
433 | - TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = payloadAdaptor.convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_TOPIC); | ||
434 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
435 | - toServerRpcSubTopicType = TopicType.V2; | ||
436 | - } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_JSON_TOPIC_PREFIX)) { | ||
437 | - TransportProtos.GetAttributeRequestMsg getAttributeMsg = context.getJsonMqttAdaptor().convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_JSON_TOPIC_PREFIX); | ||
438 | - transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
439 | - attrReqTopicType = TopicType.V2_JSON; | ||
440 | - } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_PROTO_TOPIC_PREFIX)) { | ||
441 | - TransportProtos.GetAttributeRequestMsg getAttributeMsg = context.getProtoMqttAdaptor().convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_PROTO_TOPIC_PREFIX); | ||
442 | - transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
443 | - attrReqTopicType = TopicType.V2_PROTO; | ||
444 | - } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_TOPIC_PREFIX)) { | ||
445 | - TransportProtos.GetAttributeRequestMsg getAttributeMsg = payloadAdaptor.convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_TOPIC_PREFIX); | ||
446 | - transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
447 | - attrReqTopicType = TopicType.V2; | ||
448 | - } else { | ||
449 | - transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
450 | - ack(ctx, msgId); | ||
451 | - } | 300 | + TransportProtos.PostTelemetryMsg postTelemetryMsg = payloadAdaptor.convertToPostTelemetry(deviceSessionCtx, mqttMsg); |
301 | + transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
302 | +// if (deviceSessionCtx.isDeviceAttributesTopic(topicName)) { | ||
303 | +// TransportProtos.PostAttributeMsg postAttributeMsg = payloadAdaptor.convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
304 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
305 | +// } else if (deviceSessionCtx.isDeviceTelemetryTopic(topicName)) { | ||
306 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX)) { | ||
307 | +// TransportProtos.GetAttributeRequestMsg getAttributeMsg = payloadAdaptor.convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_TOPIC_PREFIX); | ||
308 | +// transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
309 | +// attrReqTopicType = TopicType.V1; | ||
310 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_TOPIC)) { | ||
311 | +// TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = payloadAdaptor.convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_TOPIC); | ||
312 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
313 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_TOPIC)) { | ||
314 | +// TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = payloadAdaptor.convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_TOPIC); | ||
315 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
316 | +// toServerRpcSubTopicType = TopicType.V1; | ||
317 | +// } else if (topicName.equals(MqttTopics.DEVICE_CLAIM_TOPIC)) { | ||
318 | +// TransportProtos.ClaimDeviceMsg claimDeviceMsg = payloadAdaptor.convertToClaimDevice(deviceSessionCtx, mqttMsg); | ||
319 | +// transportService.process(deviceSessionCtx.getSessionInfo(), claimDeviceMsg, getPubAckCallback(ctx, msgId, claimDeviceMsg)); | ||
320 | +// } else if ((fwMatcher = FW_REQUEST_PATTERN.matcher(topicName)).find()) { | ||
321 | +// getOtaPackageCallback(ctx, mqttMsg, msgId, fwMatcher, OtaPackageType.FIRMWARE); | ||
322 | +// } else if ((fwMatcher = SW_REQUEST_PATTERN.matcher(topicName)).find()) { | ||
323 | +// getOtaPackageCallback(ctx, mqttMsg, msgId, fwMatcher, OtaPackageType.SOFTWARE); | ||
324 | +// } else if (topicName.equals(MqttTopics.DEVICE_TELEMETRY_SHORT_TOPIC)) { | ||
325 | +// TransportProtos.PostTelemetryMsg postTelemetryMsg = payloadAdaptor.convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
326 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
327 | +// } else if (topicName.equals(MqttTopics.DEVICE_TELEMETRY_SHORT_JSON_TOPIC)) { | ||
328 | +// TransportProtos.PostTelemetryMsg postTelemetryMsg = context.getJsonMqttAdaptor().convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
329 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
330 | +// } else if (topicName.equals(MqttTopics.DEVICE_TELEMETRY_SHORT_PROTO_TOPIC)) { | ||
331 | +// TransportProtos.PostTelemetryMsg postTelemetryMsg = context.getAscallAdaptor().convertToPostTelemetry(deviceSessionCtx, mqttMsg); | ||
332 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(ctx, msgId, postTelemetryMsg)); | ||
333 | +// } else if (topicName.equals(MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC)) { | ||
334 | +// TransportProtos.PostAttributeMsg postAttributeMsg = payloadAdaptor.convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
335 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
336 | +// } else if (topicName.equals(MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC)) { | ||
337 | +// TransportProtos.PostAttributeMsg postAttributeMsg = context.getJsonMqttAdaptor().convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
338 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
339 | +// } else if (topicName.equals(MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC)) { | ||
340 | +// TransportProtos.PostAttributeMsg postAttributeMsg = context.getAscallAdaptor().convertToPostAttributes(deviceSessionCtx, mqttMsg); | ||
341 | +// transportService.process(deviceSessionCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(ctx, msgId, postAttributeMsg)); | ||
342 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_SHORT_JSON_TOPIC)) { | ||
343 | +// TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = context.getJsonMqttAdaptor().convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_JSON_TOPIC); | ||
344 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
345 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_SHORT_PROTO_TOPIC)) { | ||
346 | +// TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = context.getAscallAdaptor().convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_PROTO_TOPIC); | ||
347 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
348 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_RESPONSE_SHORT_TOPIC)) { | ||
349 | +// TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = payloadAdaptor.convertToDeviceRpcResponse(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_TOPIC); | ||
350 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(ctx, msgId, rpcResponseMsg)); | ||
351 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_SHORT_JSON_TOPIC)) { | ||
352 | +// TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = context.getJsonMqttAdaptor().convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_JSON_TOPIC); | ||
353 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
354 | +// toServerRpcSubTopicType = TopicType.V2_JSON; | ||
355 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_SHORT_PROTO_TOPIC)) { | ||
356 | +// TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = context.getAscallAdaptor().convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_PROTO_TOPIC); | ||
357 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
358 | +// toServerRpcSubTopicType = TopicType.V2_PROTO; | ||
359 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_RPC_REQUESTS_SHORT_TOPIC)) { | ||
360 | +// TransportProtos.ToServerRpcRequestMsg rpcRequestMsg = payloadAdaptor.convertToServerRpcRequest(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_TOPIC); | ||
361 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequestMsg, getPubAckCallback(ctx, msgId, rpcRequestMsg)); | ||
362 | +// toServerRpcSubTopicType = TopicType.V2; | ||
363 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_JSON_TOPIC_PREFIX)) { | ||
364 | +// TransportProtos.GetAttributeRequestMsg getAttributeMsg = context.getJsonMqttAdaptor().convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_JSON_TOPIC_PREFIX); | ||
365 | +// transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
366 | +// attrReqTopicType = TopicType.V2_JSON; | ||
367 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_PROTO_TOPIC_PREFIX)) { | ||
368 | +// TransportProtos.GetAttributeRequestMsg getAttributeMsg = context.getAscallAdaptor().convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_PROTO_TOPIC_PREFIX); | ||
369 | +// transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
370 | +// attrReqTopicType = TopicType.V2_PROTO; | ||
371 | +// } else if (topicName.startsWith(MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_TOPIC_PREFIX)) { | ||
372 | +// TransportProtos.GetAttributeRequestMsg getAttributeMsg = payloadAdaptor.convertToGetAttributes(deviceSessionCtx, mqttMsg, MqttTopics.DEVICE_ATTRIBUTES_REQUEST_SHORT_TOPIC_PREFIX); | ||
373 | +// transportService.process(deviceSessionCtx.getSessionInfo(), getAttributeMsg, getPubAckCallback(ctx, msgId, getAttributeMsg)); | ||
374 | +// attrReqTopicType = TopicType.V2; | ||
375 | +// } else { | ||
376 | +// transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
377 | +// ack(ctx, msgId); | ||
378 | +// } | ||
452 | } catch (AdaptorException e) { | 379 | } catch (AdaptorException e) { |
453 | log.debug("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e); | 380 | log.debug("[{}] Failed to process publish msg [{}][{}]", sessionId, topicName, msgId, e); |
454 | log.info("[{}] Closing current session due to invalid publish msg [{}][{}]", sessionId, topicName, msgId); | 381 | log.info("[{}] Closing current session due to invalid publish msg [{}][{}]", sessionId, topicName, msgId); |
@@ -526,18 +453,18 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -526,18 +453,18 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
526 | 453 | ||
527 | @Override | 454 | @Override |
528 | public void onSuccess(TransportProtos.ProvisionDeviceResponseMsg provisionResponseMsg) { | 455 | public void onSuccess(TransportProtos.ProvisionDeviceResponseMsg provisionResponseMsg) { |
529 | - log.trace("[{}] Published msg: {}", sessionId, msg); | ||
530 | - ack(ctx, msgId); | ||
531 | - try { | ||
532 | - if (deviceSessionCtx.getProvisionPayloadType().equals(TransportPayloadType.JSON)) { | ||
533 | - deviceSessionCtx.getContext().getJsonMqttAdaptor().convertToPublish(deviceSessionCtx, provisionResponseMsg).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
534 | - } else { | ||
535 | - deviceSessionCtx.getContext().getProtoMqttAdaptor().convertToPublish(deviceSessionCtx, provisionResponseMsg).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
536 | - } | ||
537 | - scheduler.schedule((Callable<ChannelFuture>) ctx::close, 60, TimeUnit.SECONDS); | ||
538 | - } catch (Exception e) { | ||
539 | - log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
540 | - } | 456 | +// log.trace("[{}] Published msg: {}", sessionId, msg); |
457 | +// ack(ctx, msgId); | ||
458 | +// try { | ||
459 | +// if (deviceSessionCtx.getProvisionPayloadType().equals(TransportPayloadType.JSON)) { | ||
460 | +// deviceSessionCtx.getContext().getJsonMqttAdaptor().convertToPublish(deviceSessionCtx, provisionResponseMsg).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
461 | +// } else { | ||
462 | +// deviceSessionCtx.getContext().getAscallAdaptor().convertToPublish(deviceSessionCtx, provisionResponseMsg).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
463 | +// } | ||
464 | +// scheduler.schedule((Callable<ChannelFuture>) ctx::close, 60, TimeUnit.SECONDS); | ||
465 | +// } catch (Exception e) { | ||
466 | +// log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
467 | +// } | ||
541 | } | 468 | } |
542 | 469 | ||
543 | @Override | 470 | @Override |
@@ -604,164 +531,157 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -604,164 +531,157 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
604 | } | 531 | } |
605 | 532 | ||
606 | private void processSubscribe(ChannelHandlerContext ctx, MqttSubscribeMessage mqttMsg) { | 533 | private void processSubscribe(ChannelHandlerContext ctx, MqttSubscribeMessage mqttMsg) { |
607 | - if (!checkConnected(ctx, mqttMsg)) { | ||
608 | - return; | ||
609 | - } | ||
610 | - log.trace("[{}] Processing subscription [{}]!", sessionId, mqttMsg.variableHeader().messageId()); | ||
611 | - List<Integer> grantedQoSList = new ArrayList<>(); | ||
612 | - boolean activityReported = false; | ||
613 | - for (MqttTopicSubscription subscription : mqttMsg.payload().topicSubscriptions()) { | ||
614 | - String topic = subscription.topicName(); | ||
615 | - MqttQoS reqQoS = subscription.qualityOfService(); | ||
616 | - try { | ||
617 | - switch (topic) { | ||
618 | - case MqttTopics.DEVICE_ATTRIBUTES_TOPIC: { | ||
619 | - processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V1); | ||
620 | - activityReported = true; | ||
621 | - break; | ||
622 | - } | ||
623 | - case MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC: { | ||
624 | - processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2); | ||
625 | - activityReported = true; | ||
626 | - break; | ||
627 | - } | ||
628 | - case MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC: { | ||
629 | - processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_JSON); | ||
630 | - activityReported = true; | ||
631 | - break; | ||
632 | - } | ||
633 | - case MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC: { | ||
634 | - processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_PROTO); | ||
635 | - activityReported = true; | ||
636 | - break; | ||
637 | - } | ||
638 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC: { | ||
639 | - processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V1); | ||
640 | - activityReported = true; | ||
641 | - break; | ||
642 | - } | ||
643 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC: { | ||
644 | - processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2); | ||
645 | - activityReported = true; | ||
646 | - break; | ||
647 | - } | ||
648 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC: { | ||
649 | - processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_JSON); | ||
650 | - activityReported = true; | ||
651 | - break; | ||
652 | - } | ||
653 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC: { | ||
654 | - processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_PROTO); | ||
655 | - activityReported = true; | ||
656 | - break; | ||
657 | - } | ||
658 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_TOPIC: | ||
659 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_TOPIC: | ||
660 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_JSON_TOPIC: | ||
661 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_PROTO_TOPIC: | ||
662 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC: | ||
663 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_TOPIC: | ||
664 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_JSON_TOPIC: | ||
665 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_PROTO_TOPIC: | ||
666 | - case MqttTopics.GATEWAY_ATTRIBUTES_TOPIC: | ||
667 | - case MqttTopics.GATEWAY_RPC_TOPIC: | ||
668 | - case MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC: | ||
669 | - case MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC: | ||
670 | - case MqttTopics.DEVICE_FIRMWARE_RESPONSES_TOPIC: | ||
671 | - case MqttTopics.DEVICE_FIRMWARE_ERROR_TOPIC: | ||
672 | - case MqttTopics.DEVICE_SOFTWARE_RESPONSES_TOPIC: | ||
673 | - case MqttTopics.DEVICE_SOFTWARE_ERROR_TOPIC: | ||
674 | - registerSubQoS(topic, grantedQoSList, reqQoS); | ||
675 | - break; | ||
676 | - default: | ||
677 | - log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topic, reqQoS); | ||
678 | - grantedQoSList.add(FAILURE.value()); | ||
679 | - break; | ||
680 | - } | ||
681 | - } catch (Exception e) { | ||
682 | - log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topic, reqQoS, e); | ||
683 | - grantedQoSList.add(FAILURE.value()); | ||
684 | - } | ||
685 | - } | ||
686 | - if (!activityReported) { | ||
687 | - transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
688 | - } | ||
689 | - ctx.writeAndFlush(createSubAckMessage(mqttMsg.variableHeader().messageId(), grantedQoSList)); | ||
690 | - } | 534 | +// if (!checkConnected(ctx, mqttMsg)) { |
535 | +// return; | ||
536 | +// } | ||
537 | +// log.trace("[{}] Processing subscription [{}]!", sessionId, mqttMsg.variableHeader().messageId()); | ||
538 | +// List<Integer> grantedQoSList = new ArrayList<>(); | ||
539 | +// boolean activityReported = false; | ||
540 | +// for (MqttTopicSubscription subscription : mqttMsg.payload().topicSubscriptions()) { | ||
541 | +// String topic = subscription.topicName(); | ||
542 | +// MqttQoS reqQoS = subscription.qualityOfService(); | ||
543 | +// try { | ||
544 | +// switch (topic) { | ||
545 | +// case MqttTopics.DEVICE_ATTRIBUTES_TOPIC: { | ||
546 | +// processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V1); | ||
547 | +// activityReported = true; | ||
548 | +// break; | ||
549 | +// } | ||
550 | +// case MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC: { | ||
551 | +// processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2); | ||
552 | +// activityReported = true; | ||
553 | +// break; | ||
554 | +// } | ||
555 | +// case MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC: { | ||
556 | +// processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_JSON); | ||
557 | +// activityReported = true; | ||
558 | +// break; | ||
559 | +// } | ||
560 | +// case MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC: { | ||
561 | +// processAttributesSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_PROTO); | ||
562 | +// activityReported = true; | ||
563 | +// break; | ||
564 | +// } | ||
565 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC: { | ||
566 | +// processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V1); | ||
567 | +// activityReported = true; | ||
568 | +// break; | ||
569 | +// } | ||
570 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC: { | ||
571 | +// processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2); | ||
572 | +// activityReported = true; | ||
573 | +// break; | ||
574 | +// } | ||
575 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC: { | ||
576 | +// processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_JSON); | ||
577 | +// activityReported = true; | ||
578 | +// break; | ||
579 | +// } | ||
580 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC: { | ||
581 | +// processRpcSubscribe(grantedQoSList, topic, reqQoS, TopicType.V2_PROTO); | ||
582 | +// activityReported = true; | ||
583 | +// break; | ||
584 | +// } | ||
585 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_TOPIC: | ||
586 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_TOPIC: | ||
587 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_JSON_TOPIC: | ||
588 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_PROTO_TOPIC: | ||
589 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC: | ||
590 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_TOPIC: | ||
591 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_JSON_TOPIC: | ||
592 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_PROTO_TOPIC: | ||
593 | +// case MqttTopics.GATEWAY_ATTRIBUTES_TOPIC: | ||
594 | +// case MqttTopics.GATEWAY_RPC_TOPIC: | ||
595 | +// case MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC: | ||
596 | +// case MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC: | ||
597 | +// case MqttTopics.DEVICE_FIRMWARE_RESPONSES_TOPIC: | ||
598 | +// case MqttTopics.DEVICE_FIRMWARE_ERROR_TOPIC: | ||
599 | +// case MqttTopics.DEVICE_SOFTWARE_RESPONSES_TOPIC: | ||
600 | +// | ||
601 | +// break; | ||
602 | +// default: | ||
603 | +// log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topic, reqQoS); | ||
604 | +// grantedQoSList.add(FAILURE.value()); | ||
605 | +// break; | ||
606 | +// } | ||
607 | +// } catch (Exception e) { | ||
608 | +// log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topic, reqQoS, e); | ||
609 | +// grantedQoSList.add(FAILURE.value()); | ||
610 | +// } | ||
611 | +// } | ||
612 | +// if (!activityReported) { | ||
613 | +// transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
614 | +// } | ||
615 | +// ctx.writeAndFlush(createSubAckMessage(mqttMsg.variableHeader().messageId(), grantedQoSList)); | ||
616 | + } | ||
617 | + | ||
618 | +// private void processRpcSubscribe(List<Integer> grantedQoSList, String topic, MqttQoS reqQoS, TopicType topicType) { | ||
619 | +// transportService.process(deviceSessionCtx.getSessionInfo(), TransportProtos.SubscribeToRPCMsg.newBuilder().build(), null); | ||
620 | +// rpcSubTopicType = topicType; | ||
621 | +// } | ||
622 | +// | ||
623 | +// private void processAttributesSubscribe(List<Integer> grantedQoSList, String topic, MqttQoS reqQoS, TopicType topicType) { | ||
624 | +// transportService.process(deviceSessionCtx.getSessionInfo(), TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().build(), null); | ||
625 | +// attrSubTopicType = topicType; | ||
626 | +// } | ||
691 | 627 | ||
692 | - private void processRpcSubscribe(List<Integer> grantedQoSList, String topic, MqttQoS reqQoS, TopicType topicType) { | ||
693 | - transportService.process(deviceSessionCtx.getSessionInfo(), TransportProtos.SubscribeToRPCMsg.newBuilder().build(), null); | ||
694 | - rpcSubTopicType = topicType; | ||
695 | - registerSubQoS(topic, grantedQoSList, reqQoS); | ||
696 | - } | ||
697 | 628 | ||
698 | - private void processAttributesSubscribe(List<Integer> grantedQoSList, String topic, MqttQoS reqQoS, TopicType topicType) { | ||
699 | - transportService.process(deviceSessionCtx.getSessionInfo(), TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().build(), null); | ||
700 | - attrSubTopicType = topicType; | ||
701 | - registerSubQoS(topic, grantedQoSList, reqQoS); | ||
702 | - } | ||
703 | - | ||
704 | - private void registerSubQoS(String topic, List<Integer> grantedQoSList, MqttQoS reqQoS) { | ||
705 | - grantedQoSList.add(getMinSupportedQos(reqQoS)); | ||
706 | - mqttQoSMap.put(new MqttTopicMatcher(topic), getMinSupportedQos(reqQoS)); | ||
707 | - } | ||
708 | 629 | ||
709 | private void processUnsubscribe(ChannelHandlerContext ctx, MqttUnsubscribeMessage mqttMsg) { | 630 | private void processUnsubscribe(ChannelHandlerContext ctx, MqttUnsubscribeMessage mqttMsg) { |
710 | - if (!checkConnected(ctx, mqttMsg)) { | ||
711 | - return; | ||
712 | - } | ||
713 | - boolean activityReported = false; | ||
714 | - log.trace("[{}] Processing subscription [{}]!", sessionId, mqttMsg.variableHeader().messageId()); | ||
715 | - for (String topicName : mqttMsg.payload().topics()) { | ||
716 | - mqttQoSMap.remove(new MqttTopicMatcher(topicName)); | ||
717 | - try { | ||
718 | - switch (topicName) { | ||
719 | - case MqttTopics.DEVICE_ATTRIBUTES_TOPIC: | ||
720 | - case MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC: | ||
721 | - case MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC: | ||
722 | - case MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC: { | ||
723 | - transportService.process(deviceSessionCtx.getSessionInfo(), | ||
724 | - TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().setUnsubscribe(true).build(), null); | ||
725 | - activityReported = true; | ||
726 | - break; | ||
727 | - } | ||
728 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC: | ||
729 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC: | ||
730 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC: | ||
731 | - case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC: { | ||
732 | - transportService.process(deviceSessionCtx.getSessionInfo(), | ||
733 | - TransportProtos.SubscribeToRPCMsg.newBuilder().setUnsubscribe(true).build(), null); | ||
734 | - activityReported = true; | ||
735 | - break; | ||
736 | - } | ||
737 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_TOPIC: | ||
738 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_TOPIC: | ||
739 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_JSON_TOPIC: | ||
740 | - case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_PROTO_TOPIC: | ||
741 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC: | ||
742 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_TOPIC: | ||
743 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_JSON_TOPIC: | ||
744 | - case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_PROTO_TOPIC: | ||
745 | - case MqttTopics.GATEWAY_ATTRIBUTES_TOPIC: | ||
746 | - case MqttTopics.GATEWAY_RPC_TOPIC: | ||
747 | - case MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC: | ||
748 | - case MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC: | ||
749 | - case MqttTopics.DEVICE_FIRMWARE_RESPONSES_TOPIC: | ||
750 | - case MqttTopics.DEVICE_FIRMWARE_ERROR_TOPIC: | ||
751 | - case MqttTopics.DEVICE_SOFTWARE_RESPONSES_TOPIC: | ||
752 | - case MqttTopics.DEVICE_SOFTWARE_ERROR_TOPIC: { | ||
753 | - activityReported = true; | ||
754 | - break; | ||
755 | - } | ||
756 | - } | ||
757 | - } catch (Exception e) { | ||
758 | - log.debug("[{}] Failed to process unsubscription [{}] to [{}]", sessionId, mqttMsg.variableHeader().messageId(), topicName); | ||
759 | - } | ||
760 | - } | ||
761 | - if (!activityReported) { | ||
762 | - transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
763 | - } | ||
764 | - ctx.writeAndFlush(createUnSubAckMessage(mqttMsg.variableHeader().messageId())); | 631 | +// if (!checkConnected(ctx, mqttMsg)) { |
632 | +// return; | ||
633 | +// } | ||
634 | +// boolean activityReported = false; | ||
635 | +// log.trace("[{}] Processing subscription [{}]!", sessionId, mqttMsg.variableHeader().messageId()); | ||
636 | +// for (String topicName : mqttMsg.payload().topics()) { | ||
637 | +// try { | ||
638 | +// switch (topicName) { | ||
639 | +// case MqttTopics.DEVICE_ATTRIBUTES_TOPIC: | ||
640 | +// case MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC: | ||
641 | +// case MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC: | ||
642 | +// case MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC: { | ||
643 | +// transportService.process(deviceSessionCtx.getSessionInfo(), | ||
644 | +// TransportProtos.SubscribeToAttributeUpdatesMsg.newBuilder().setUnsubscribe(true).build(), null); | ||
645 | +// activityReported = true; | ||
646 | +// break; | ||
647 | +// } | ||
648 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_TOPIC: | ||
649 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_TOPIC: | ||
650 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_JSON_TOPIC: | ||
651 | +// case MqttTopics.DEVICE_RPC_REQUESTS_SUB_SHORT_PROTO_TOPIC: { | ||
652 | +// transportService.process(deviceSessionCtx.getSessionInfo(), | ||
653 | +// TransportProtos.SubscribeToRPCMsg.newBuilder().setUnsubscribe(true).build(), null); | ||
654 | +// activityReported = true; | ||
655 | +// break; | ||
656 | +// } | ||
657 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_TOPIC: | ||
658 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_TOPIC: | ||
659 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_JSON_TOPIC: | ||
660 | +// case MqttTopics.DEVICE_RPC_RESPONSE_SUB_SHORT_PROTO_TOPIC: | ||
661 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_TOPIC: | ||
662 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_TOPIC: | ||
663 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_JSON_TOPIC: | ||
664 | +// case MqttTopics.DEVICE_ATTRIBUTES_RESPONSES_SHORT_PROTO_TOPIC: | ||
665 | +// case MqttTopics.GATEWAY_ATTRIBUTES_TOPIC: | ||
666 | +// case MqttTopics.GATEWAY_RPC_TOPIC: | ||
667 | +// case MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC: | ||
668 | +// case MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC: | ||
669 | +// case MqttTopics.DEVICE_FIRMWARE_RESPONSES_TOPIC: | ||
670 | +// case MqttTopics.DEVICE_FIRMWARE_ERROR_TOPIC: | ||
671 | +// case MqttTopics.DEVICE_SOFTWARE_RESPONSES_TOPIC: | ||
672 | +// case MqttTopics.DEVICE_SOFTWARE_ERROR_TOPIC: { | ||
673 | +// activityReported = true; | ||
674 | +// break; | ||
675 | +// } | ||
676 | +// } | ||
677 | +// } catch (Exception e) { | ||
678 | +// log.debug("[{}] Failed to process unsubscription [{}] to [{}]", sessionId, mqttMsg.variableHeader().messageId(), topicName); | ||
679 | +// } | ||
680 | +// } | ||
681 | +// if (!activityReported) { | ||
682 | +// transportService.reportActivity(deviceSessionCtx.getSessionInfo()); | ||
683 | +// } | ||
684 | +// ctx.writeAndFlush(createUnSubAckMessage(mqttMsg.variableHeader().messageId())); | ||
765 | } | 685 | } |
766 | 686 | ||
767 | private MqttMessage createUnSubAckMessage(int msgId) { | 687 | private MqttMessage createUnSubAckMessage(int msgId) { |
@@ -771,47 +691,39 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -771,47 +691,39 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
771 | return new MqttMessage(mqttFixedHeader, mqttMessageIdVariableHeader); | 691 | return new MqttMessage(mqttFixedHeader, mqttMessageIdVariableHeader); |
772 | } | 692 | } |
773 | 693 | ||
774 | - void processConnect(ChannelHandlerContext ctx, MqttConnectMessage msg) { | ||
775 | - log.debug("[{}][{}] Processing connect msg for client: {}!", address, sessionId, msg.payload().clientIdentifier()); | ||
776 | - String userName = msg.payload().userName(); | ||
777 | - String clientId = msg.payload().clientIdentifier(); | ||
778 | - if (DataConstants.PROVISION.equals(userName) || DataConstants.PROVISION.equals(clientId)) { | 694 | + void processConnect(ChannelHandlerContext ctx, String accessToken) { |
695 | + log.debug("[{}][{}] Processing connect msg for client: {}!", address, sessionId, accessToken); | ||
696 | + | ||
697 | + if (DataConstants.PROVISION.equals(accessToken) || DataConstants.PROVISION.equals(accessToken)) { | ||
779 | deviceSessionCtx.setProvisionOnly(true); | 698 | deviceSessionCtx.setProvisionOnly(true); |
780 | - ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED, msg)); | 699 | + ctx.writeAndFlush(createTcpConnAckMsg(CONNECTION_ACCEPTED)); |
781 | } else { | 700 | } else { |
782 | X509Certificate cert; | 701 | X509Certificate cert; |
783 | if (sslHandler != null && (cert = getX509Certificate()) != null) { | 702 | if (sslHandler != null && (cert = getX509Certificate()) != null) { |
784 | - processX509CertConnect(ctx, cert, msg); | 703 | +// processX509CertConnect(ctx, cert, msg); |
785 | } else { | 704 | } else { |
786 | - processAuthTokenConnect(ctx, msg); | 705 | + processAuthTokenConnect(ctx, accessToken); |
787 | } | 706 | } |
788 | } | 707 | } |
789 | } | 708 | } |
790 | 709 | ||
791 | - private void processAuthTokenConnect(ChannelHandlerContext ctx, MqttConnectMessage connectMessage) { | ||
792 | - String userName = connectMessage.payload().userName(); | ||
793 | - log.debug("[{}][{}] Processing connect msg for client with user name: {}!", address, sessionId, userName); | ||
794 | - TransportProtos.ValidateBasicMqttCredRequestMsg.Builder request = TransportProtos.ValidateBasicMqttCredRequestMsg.newBuilder() | ||
795 | - .setClientId(connectMessage.payload().clientIdentifier()); | ||
796 | - if (userName != null) { | ||
797 | - request.setUserName(userName); | ||
798 | - } | ||
799 | - byte[] passwordBytes = connectMessage.payload().passwordInBytes(); | ||
800 | - if (passwordBytes != null) { | ||
801 | - String password = new String(passwordBytes, CharsetUtil.UTF_8); | ||
802 | - request.setPassword(password); | ||
803 | - } | ||
804 | - transportService.process(DeviceTransportType.MQTT, request.build(), | 710 | + private void processAuthTokenConnect(ChannelHandlerContext ctx, String accessToken) { |
711 | + | ||
712 | + log.debug("[{}][{}] Processing connect msg for client with user name: {}!", address, sessionId, accessToken); | ||
713 | + TransportProtos.ValidateDeviceTokenRequestMsg.Builder request = TransportProtos.ValidateDeviceTokenRequestMsg.newBuilder() | ||
714 | + .setToken(accessToken); | ||
715 | + | ||
716 | + transportService.process(DeviceTransportType.TCP, request.build(), | ||
805 | new TransportServiceCallback<>() { | 717 | new TransportServiceCallback<>() { |
806 | @Override | 718 | @Override |
807 | public void onSuccess(ValidateDeviceCredentialsResponse msg) { | 719 | public void onSuccess(ValidateDeviceCredentialsResponse msg) { |
808 | - onValidateDeviceResponse(msg, ctx, connectMessage); | 720 | + onValidateDeviceResponse(msg, ctx); |
809 | } | 721 | } |
810 | 722 | ||
811 | @Override | 723 | @Override |
812 | public void onError(Throwable e) { | 724 | public void onError(Throwable e) { |
813 | - log.trace("[{}] Failed to process credentials: {}", address, userName, e); | ||
814 | - ctx.writeAndFlush(createMqttConnAckMsg(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE, connectMessage)); | 725 | + log.trace("[{}] Failed to process credentials: {}", address, accessToken, e); |
726 | + ctx.writeAndFlush(createTcpConnAckMsg(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE)); | ||
815 | ctx.close(); | 727 | ctx.close(); |
816 | } | 728 | } |
817 | }); | 729 | }); |
@@ -828,19 +740,19 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -828,19 +740,19 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
828 | new TransportServiceCallback<>() { | 740 | new TransportServiceCallback<>() { |
829 | @Override | 741 | @Override |
830 | public void onSuccess(ValidateDeviceCredentialsResponse msg) { | 742 | public void onSuccess(ValidateDeviceCredentialsResponse msg) { |
831 | - onValidateDeviceResponse(msg, ctx, connectMessage); | 743 | + onValidateDeviceResponse(msg, ctx); |
832 | } | 744 | } |
833 | 745 | ||
834 | @Override | 746 | @Override |
835 | public void onError(Throwable e) { | 747 | public void onError(Throwable e) { |
836 | log.trace("[{}] Failed to process credentials: {}", address, sha3Hash, e); | 748 | log.trace("[{}] Failed to process credentials: {}", address, sha3Hash, e); |
837 | - ctx.writeAndFlush(createMqttConnAckMsg(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE, connectMessage)); | 749 | + ctx.writeAndFlush(createTcpConnAckMsg(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE)); |
838 | ctx.close(); | 750 | ctx.close(); |
839 | } | 751 | } |
840 | }); | 752 | }); |
841 | } catch (Exception e) { | 753 | } catch (Exception e) { |
842 | context.onAuthFailure(address); | 754 | context.onAuthFailure(address); |
843 | - ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED, connectMessage)); | 755 | + ctx.writeAndFlush(createTcpConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED)); |
844 | log.trace("[{}] X509 auth failure: {}", sessionId, address, e); | 756 | log.trace("[{}] X509 auth failure: {}", sessionId, address, e); |
845 | ctx.close(); | 757 | ctx.close(); |
846 | } | 758 | } |
@@ -859,12 +771,8 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -859,12 +771,8 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
859 | return null; | 771 | return null; |
860 | } | 772 | } |
861 | 773 | ||
862 | - private MqttConnAckMessage createMqttConnAckMsg(MqttConnectReturnCode returnCode, MqttConnectMessage msg) { | ||
863 | - MqttFixedHeader mqttFixedHeader = | ||
864 | - new MqttFixedHeader(CONNACK, false, AT_MOST_ONCE, false, 0); | ||
865 | - MqttConnAckVariableHeader mqttConnAckVariableHeader = | ||
866 | - new MqttConnAckVariableHeader(returnCode, !msg.variableHeader().isCleanSession()); | ||
867 | - return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader); | 774 | + private ByteBuf createTcpConnAckMsg(MqttConnectReturnCode msg) { |
775 | + return Unpooled.copiedBuffer(ByteUtils.hexStr2Bytes(msg.name())); | ||
868 | } | 776 | } |
869 | 777 | ||
870 | @Override | 778 | @Override |
@@ -890,9 +798,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -890,9 +798,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
890 | return new MqttSubAckMessage(mqttFixedHeader, mqttMessageIdVariableHeader, mqttSubAckPayload); | 798 | return new MqttSubAckMessage(mqttFixedHeader, mqttMessageIdVariableHeader, mqttSubAckPayload); |
891 | } | 799 | } |
892 | 800 | ||
893 | - private static int getMinSupportedQos(MqttQoS reqQoS) { | ||
894 | - return Math.min(reqQoS.value(), MAX_SUPPORTED_QOS_LVL.value()); | ||
895 | - } | 801 | + |
896 | 802 | ||
897 | public static MqttPubAckMessage createMqttPubAckMsg(int requestId) { | 803 | public static MqttPubAckMessage createMqttPubAckMsg(int requestId) { |
898 | MqttFixedHeader mqttFixedHeader = | 804 | MqttFixedHeader mqttFixedHeader = |
@@ -902,7 +808,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -902,7 +808,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
902 | return new MqttPubAckMessage(mqttFixedHeader, mqttMsgIdVariableHeader); | 808 | return new MqttPubAckMessage(mqttFixedHeader, mqttMsgIdVariableHeader); |
903 | } | 809 | } |
904 | 810 | ||
905 | - private boolean checkConnected(ChannelHandlerContext ctx, MqttMessage msg) { | 811 | + private boolean checkConnected(ChannelHandlerContext ctx, TCPMessage msg) { |
906 | if (deviceSessionCtx.isConnected()) { | 812 | if (deviceSessionCtx.isConnected()) { |
907 | return true; | 813 | return true; |
908 | } else { | 814 | } else { |
@@ -911,23 +817,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -911,23 +817,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
911 | } | 817 | } |
912 | } | 818 | } |
913 | 819 | ||
914 | - private void checkGatewaySession(SessionMetaData sessionMetaData) { | ||
915 | - TransportDeviceInfo device = deviceSessionCtx.getDeviceInfo(); | ||
916 | - try { | ||
917 | - JsonNode infoNode = context.getMapper().readTree(device.getAdditionalInfo()); | ||
918 | - if (infoNode != null) { | ||
919 | - JsonNode gatewayNode = infoNode.get("gateway"); | ||
920 | - if (gatewayNode != null && gatewayNode.asBoolean()) { | ||
921 | - gatewaySessionHandler = new GatewaySessionHandler(deviceSessionCtx, sessionId); | ||
922 | - if (infoNode.has(DefaultTransportService.OVERWRITE_ACTIVITY_TIME) && infoNode.get(DefaultTransportService.OVERWRITE_ACTIVITY_TIME).isBoolean()) { | ||
923 | - sessionMetaData.setOverwriteActivityTime(infoNode.get(DefaultTransportService.OVERWRITE_ACTIVITY_TIME).asBoolean()); | ||
924 | - } | ||
925 | - } | ||
926 | - } | ||
927 | - } catch (IOException e) { | ||
928 | - log.trace("[{}][{}] Failed to fetch device additional info", sessionId, device.getDeviceName(), e); | ||
929 | - } | ||
930 | - } | 820 | + |
931 | 821 | ||
932 | @Override | 822 | @Override |
933 | public void operationComplete(Future<? super Void> future) throws Exception { | 823 | public void operationComplete(Future<? super Void> future) throws Exception { |
@@ -940,19 +830,16 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -940,19 +830,16 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
940 | log.debug("[{}] Client disconnected!", sessionId); | 830 | log.debug("[{}] Client disconnected!", sessionId); |
941 | transportService.process(deviceSessionCtx.getSessionInfo(), SESSION_EVENT_MSG_CLOSED, null); | 831 | transportService.process(deviceSessionCtx.getSessionInfo(), SESSION_EVENT_MSG_CLOSED, null); |
942 | transportService.deregisterSession(deviceSessionCtx.getSessionInfo()); | 832 | transportService.deregisterSession(deviceSessionCtx.getSessionInfo()); |
943 | - if (gatewaySessionHandler != null) { | ||
944 | - gatewaySessionHandler.onGatewayDisconnect(); | ||
945 | - } | ||
946 | deviceSessionCtx.setDisconnected(); | 833 | deviceSessionCtx.setDisconnected(); |
947 | } | 834 | } |
948 | deviceSessionCtx.release(); | 835 | deviceSessionCtx.release(); |
949 | } | 836 | } |
950 | 837 | ||
951 | 838 | ||
952 | - private void onValidateDeviceResponse(ValidateDeviceCredentialsResponse msg, ChannelHandlerContext ctx, MqttConnectMessage connectMessage) { | 839 | + private void onValidateDeviceResponse(ValidateDeviceCredentialsResponse msg, ChannelHandlerContext ctx) { |
953 | if (!msg.hasDeviceInfo()) { | 840 | if (!msg.hasDeviceInfo()) { |
954 | context.onAuthFailure(address); | 841 | context.onAuthFailure(address); |
955 | - ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED, connectMessage)); | 842 | + ctx.writeAndFlush(createTcpConnAckMsg(CONNECTION_REFUSED_NOT_AUTHORIZED)); |
956 | ctx.close(); | 843 | ctx.close(); |
957 | } else { | 844 | } else { |
958 | context.onAuthSuccess(address); | 845 | context.onAuthSuccess(address); |
@@ -962,9 +849,8 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -962,9 +849,8 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
962 | transportService.process(deviceSessionCtx.getSessionInfo(), SESSION_EVENT_MSG_OPEN, new TransportServiceCallback<Void>() { | 849 | transportService.process(deviceSessionCtx.getSessionInfo(), SESSION_EVENT_MSG_OPEN, new TransportServiceCallback<Void>() { |
963 | @Override | 850 | @Override |
964 | public void onSuccess(Void msg) { | 851 | public void onSuccess(Void msg) { |
965 | - SessionMetaData sessionMetaData = transportService.registerAsyncSession(deviceSessionCtx.getSessionInfo(), TcpTransportHandler.this); | ||
966 | - checkGatewaySession(sessionMetaData); | ||
967 | - ctx.writeAndFlush(createMqttConnAckMsg(CONNECTION_ACCEPTED, connectMessage)); | 852 | + transportService.registerAsyncSession(deviceSessionCtx.getSessionInfo(), TcpTransportHandler.this); |
853 | + ctx.writeAndFlush(createTcpConnAckMsg(CONNECTION_ACCEPTED)); | ||
968 | deviceSessionCtx.setConnected(true); | 854 | deviceSessionCtx.setConnected(true); |
969 | log.debug("[{}] Client connected!", sessionId); | 855 | log.debug("[{}] Client connected!", sessionId); |
970 | transportService.getCallbackExecutor().execute(() -> processMsgQueue(ctx)); //this callback will execute in Producer worker thread and hard or blocking work have to be submitted to the separate thread. | 856 | transportService.getCallbackExecutor().execute(() -> processMsgQueue(ctx)); //this callback will execute in Producer worker thread and hard or blocking work have to be submitted to the separate thread. |
@@ -977,7 +863,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -977,7 +863,7 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
977 | } else { | 863 | } else { |
978 | log.warn("[{}] Failed to submit session event", sessionId, e); | 864 | log.warn("[{}] Failed to submit session event", sessionId, e); |
979 | } | 865 | } |
980 | - ctx.writeAndFlush(createMqttConnAckMsg(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE, connectMessage)); | 866 | + ctx.writeAndFlush(createTcpConnAckMsg(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE)); |
981 | ctx.close(); | 867 | ctx.close(); |
982 | } | 868 | } |
983 | }); | 869 | }); |
@@ -986,26 +872,26 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -986,26 +872,26 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
986 | 872 | ||
987 | @Override | 873 | @Override |
988 | public void onGetAttributesResponse(TransportProtos.GetAttributeResponseMsg response) { | 874 | public void onGetAttributesResponse(TransportProtos.GetAttributeResponseMsg response) { |
989 | - log.trace("[{}] Received get attributes response", sessionId); | ||
990 | - String topicBase = attrReqTopicType.getAttributesResponseTopicBase(); | ||
991 | - TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(attrReqTopicType); | ||
992 | - try { | ||
993 | - adaptor.convertToPublish(deviceSessionCtx, response, topicBase).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
994 | - } catch (Exception e) { | ||
995 | - log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
996 | - } | 875 | +// log.trace("[{}] Received get attributes response", sessionId); |
876 | +// String topicBase = attrReqTopicType.getAttributesResponseTopicBase(); | ||
877 | +// TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(attrReqTopicType); | ||
878 | +// try { | ||
879 | +// adaptor.convertToPublish(deviceSessionCtx, response, topicBase).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
880 | +// } catch (Exception e) { | ||
881 | +// log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
882 | +// } | ||
997 | } | 883 | } |
998 | 884 | ||
999 | @Override | 885 | @Override |
1000 | public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg notification) { | 886 | public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg notification) { |
1001 | - log.trace("[{}] Received attributes update notification to device", sessionId); | ||
1002 | - String topic = attrSubTopicType.getAttributesSubTopic(); | ||
1003 | - TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(attrSubTopicType); | ||
1004 | - try { | ||
1005 | - adaptor.convertToPublish(deviceSessionCtx, notification, topic).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
1006 | - } catch (Exception e) { | ||
1007 | - log.trace("[{}] Failed to convert device attributes update to MQTT msg", sessionId, e); | ||
1008 | - } | 887 | +// log.trace("[{}] Received attributes update notification to device", sessionId); |
888 | +// String topic = attrSubTopicType.getAttributesSubTopic(); | ||
889 | +// TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(attrSubTopicType); | ||
890 | +// try { | ||
891 | +// adaptor.convertToPublish(deviceSessionCtx, notification, topic).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
892 | +// } catch (Exception e) { | ||
893 | +// log.trace("[{}] Failed to convert device attributes update to MQTT msg", sessionId, e); | ||
894 | +// } | ||
1009 | } | 895 | } |
1010 | 896 | ||
1011 | @Override | 897 | @Override |
@@ -1016,52 +902,52 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | @@ -1016,52 +902,52 @@ public class TcpTransportHandler extends ChannelInboundHandlerAdapter implements | ||
1016 | 902 | ||
1017 | @Override | 903 | @Override |
1018 | public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) { | 904 | public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) { |
1019 | - log.trace("[{}] Received RPC command to device", sessionId); | ||
1020 | - String baseTopic = rpcSubTopicType.getRpcRequestTopicBase(); | ||
1021 | - TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(rpcSubTopicType); | ||
1022 | - try { | ||
1023 | - adaptor.convertToPublish(deviceSessionCtx, rpcRequest, baseTopic).ifPresent(payload -> { | ||
1024 | - int msgId = ((MqttPublishMessage) payload).variableHeader().packetId(); | ||
1025 | - if (isAckExpected(payload)) { | ||
1026 | - rpcAwaitingAck.put(msgId, rpcRequest); | ||
1027 | - context.getScheduler().schedule(() -> { | ||
1028 | - TransportProtos.ToDeviceRpcRequestMsg msg = rpcAwaitingAck.remove(msgId); | ||
1029 | - if (msg != null) { | ||
1030 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.TIMEOUT, TransportServiceCallback.EMPTY); | ||
1031 | - } | ||
1032 | - }, Math.max(0, Math.min(deviceSessionCtx.getContext().getTimeout(), rpcRequest.getExpirationTime() - System.currentTimeMillis())), TimeUnit.MILLISECONDS); | ||
1033 | - } | ||
1034 | - var cf = publish(payload, deviceSessionCtx); | ||
1035 | - cf.addListener(result -> { | ||
1036 | - if (result.cause() == null) { | ||
1037 | - if (!isAckExpected(payload)) { | ||
1038 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); | ||
1039 | - } else if (rpcRequest.getPersisted()) { | ||
1040 | - transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.SENT, TransportServiceCallback.EMPTY); | ||
1041 | - } | ||
1042 | - } else { | ||
1043 | - // TODO: send error | ||
1044 | - } | ||
1045 | - }); | ||
1046 | - }); | ||
1047 | - } catch (Exception e) { | ||
1048 | - transportService.process(deviceSessionCtx.getSessionInfo(), | ||
1049 | - TransportProtos.ToDeviceRpcResponseMsg.newBuilder() | ||
1050 | - .setRequestId(rpcRequest.getRequestId()).setError("Failed to convert device RPC command to MQTT msg").build(), TransportServiceCallback.EMPTY); | ||
1051 | - log.trace("[{}] Failed to convert device RPC command to MQTT msg", sessionId, e); | ||
1052 | - } | 905 | +// log.trace("[{}] Received RPC command to device", sessionId); |
906 | +// String baseTopic = rpcSubTopicType.getRpcRequestTopicBase(); | ||
907 | +// TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(rpcSubTopicType); | ||
908 | +// try { | ||
909 | +// adaptor.convertToPublish(deviceSessionCtx, rpcRequest, baseTopic).ifPresent(payload -> { | ||
910 | +// int msgId = ((MqttPublishMessage) payload).variableHeader().packetId(); | ||
911 | +// if (isAckExpected(payload)) { | ||
912 | +// rpcAwaitingAck.put(msgId, rpcRequest); | ||
913 | +// context.getScheduler().schedule(() -> { | ||
914 | +// TransportProtos.ToDeviceRpcRequestMsg msg = rpcAwaitingAck.remove(msgId); | ||
915 | +// if (msg != null) { | ||
916 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.TIMEOUT, TransportServiceCallback.EMPTY); | ||
917 | +// } | ||
918 | +// }, Math.max(0, Math.min(deviceSessionCtx.getContext().getTimeout(), rpcRequest.getExpirationTime() - System.currentTimeMillis())), TimeUnit.MILLISECONDS); | ||
919 | +// } | ||
920 | +// var cf = publish(payload, deviceSessionCtx); | ||
921 | +// cf.addListener(result -> { | ||
922 | +// if (result.cause() == null) { | ||
923 | +// if (!isAckExpected(payload)) { | ||
924 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); | ||
925 | +// } else if (rpcRequest.getPersisted()) { | ||
926 | +// transportService.process(deviceSessionCtx.getSessionInfo(), rpcRequest, RpcStatus.SENT, TransportServiceCallback.EMPTY); | ||
927 | +// } | ||
928 | +// } else { | ||
929 | +// // TODO: send error | ||
930 | +// } | ||
931 | +// }); | ||
932 | +// }); | ||
933 | +// } catch (Exception e) { | ||
934 | +// transportService.process(deviceSessionCtx.getSessionInfo(), | ||
935 | +// TransportProtos.ToDeviceRpcResponseMsg.newBuilder() | ||
936 | +// .setRequestId(rpcRequest.getRequestId()).setError("Failed to convert device RPC command to MQTT msg").build(), TransportServiceCallback.EMPTY); | ||
937 | +// log.trace("[{}] Failed to convert device RPC command to MQTT msg", sessionId, e); | ||
938 | +// } | ||
1053 | } | 939 | } |
1054 | 940 | ||
1055 | @Override | 941 | @Override |
1056 | public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg rpcResponse) { | 942 | public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg rpcResponse) { |
1057 | - log.trace("[{}] Received RPC response from server", sessionId); | ||
1058 | - String baseTopic = toServerRpcSubTopicType.getRpcResponseTopicBase(); | ||
1059 | - TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(toServerRpcSubTopicType); | ||
1060 | - try { | ||
1061 | - adaptor.convertToPublish(deviceSessionCtx, rpcResponse, baseTopic).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
1062 | - } catch (Exception e) { | ||
1063 | - log.trace("[{}] Failed to convert device RPC command to MQTT msg", sessionId, e); | ||
1064 | - } | 943 | +// log.trace("[{}] Received RPC response from server", sessionId); |
944 | +// String baseTopic = toServerRpcSubTopicType.getRpcResponseTopicBase(); | ||
945 | +// TcpTransportAdaptor adaptor = deviceSessionCtx.getAdaptor(toServerRpcSubTopicType); | ||
946 | +// try { | ||
947 | +// adaptor.convertToPublish(deviceSessionCtx, rpcResponse, baseTopic).ifPresent(deviceSessionCtx.getChannel()::writeAndFlush); | ||
948 | +// } catch (Exception e) { | ||
949 | +// log.trace("[{}] Failed to convert device RPC command to MQTT msg", sessionId, e); | ||
950 | +// } | ||
1065 | } | 951 | } |
1066 | 952 | ||
1067 | private ChannelFuture publish(MqttMessage message, DeviceSessionCtx deviceSessionCtx) { | 953 | private ChannelFuture publish(MqttMessage message, DeviceSessionCtx deviceSessionCtx) { |
@@ -21,6 +21,8 @@ import io.netty.channel.socket.SocketChannel; | @@ -21,6 +21,8 @@ import io.netty.channel.socket.SocketChannel; | ||
21 | import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; | 21 | import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; |
22 | import io.netty.handler.codec.mqtt.MqttDecoder; | 22 | import io.netty.handler.codec.mqtt.MqttDecoder; |
23 | import io.netty.handler.codec.mqtt.MqttEncoder; | 23 | import io.netty.handler.codec.mqtt.MqttEncoder; |
24 | +import io.netty.handler.codec.string.StringDecoder; | ||
25 | +import io.netty.handler.codec.string.StringEncoder; | ||
24 | import io.netty.handler.ssl.SslHandler; | 26 | import io.netty.handler.ssl.SslHandler; |
25 | import org.thingsboard.server.transport.tcp.limits.IpFilter; | 27 | import org.thingsboard.server.transport.tcp.limits.IpFilter; |
26 | import org.thingsboard.server.transport.tcp.limits.ProxyIpFilter; | 28 | import org.thingsboard.server.transport.tcp.limits.ProxyIpFilter; |
@@ -52,8 +54,8 @@ public class TcpTransportServerInitializer extends ChannelInitializer<SocketChan | @@ -52,8 +54,8 @@ public class TcpTransportServerInitializer extends ChannelInitializer<SocketChan | ||
52 | sslHandler = context.getSslHandlerProvider().getSslHandler(); | 54 | sslHandler = context.getSslHandlerProvider().getSslHandler(); |
53 | pipeline.addLast(sslHandler); | 55 | pipeline.addLast(sslHandler); |
54 | } | 56 | } |
55 | - pipeline.addLast("decoder", new MqttDecoder(context.getMaxPayloadSize())); | ||
56 | - pipeline.addLast("encoder", MqttEncoder.INSTANCE); | 57 | +// pipeline.addLast("decoder", new StringDecoder()); |
58 | +// pipeline.addLast("encoder", new StringEncoder()); | ||
57 | 59 | ||
58 | TcpTransportHandler handler = new TcpTransportHandler(context, sslHandler); | 60 | TcpTransportHandler handler = new TcpTransportHandler(context, sslHandler); |
59 | 61 |
@@ -43,7 +43,7 @@ import java.net.InetSocketAddress; | @@ -43,7 +43,7 @@ import java.net.InetSocketAddress; | ||
43 | @Slf4j | 43 | @Slf4j |
44 | public class TcpTransportService implements TbTransportService { | 44 | public class TcpTransportService implements TbTransportService { |
45 | 45 | ||
46 | - public static AttributeKey<InetSocketAddress> ADDRESS = AttributeKey.newInstance("SRC_ADDRESS"); | 46 | + public static AttributeKey<InetSocketAddress> ADDRESS = AttributeKey.newInstance("TCP_SRC_ADDRESS"); |
47 | 47 | ||
48 | @Value("${transport.tcp.bind_address}") | 48 | @Value("${transport.tcp.bind_address}") |
49 | private String host; | 49 | private String host; |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/TopicType.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp; | ||
17 | - | ||
18 | -import lombok.Getter; | ||
19 | -import org.thingsboard.server.common.data.device.profile.MqttTopics; | ||
20 | - | ||
21 | -public enum TopicType { | ||
22 | - | ||
23 | - V1(MqttTopics.DEVICE_ATTRIBUTES_RESPONSE_TOPIC_PREFIX, MqttTopics.DEVICE_ATTRIBUTES_TOPIC, MqttTopics.DEVICE_RPC_REQUESTS_TOPIC, MqttTopics.DEVICE_RPC_RESPONSE_TOPIC), | ||
24 | - V2(MqttTopics.DEVICE_ATTRIBUTES_RESPONSE_SHORT_TOPIC_PREFIX, MqttTopics.DEVICE_ATTRIBUTES_SHORT_TOPIC, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_TOPIC, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_TOPIC), | ||
25 | - V2_JSON(MqttTopics.DEVICE_ATTRIBUTES_RESPONSE_SHORT_JSON_TOPIC_PREFIX, MqttTopics.DEVICE_ATTRIBUTES_SHORT_JSON_TOPIC, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_JSON_TOPIC, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_JSON_TOPIC), | ||
26 | - V2_PROTO(MqttTopics.DEVICE_ATTRIBUTES_RESPONSE_SHORT_PROTO_TOPIC_PREFIX, MqttTopics.DEVICE_ATTRIBUTES_SHORT_PROTO_TOPIC, MqttTopics.DEVICE_RPC_REQUESTS_SHORT_PROTO_TOPIC, MqttTopics.DEVICE_RPC_RESPONSE_SHORT_PROTO_TOPIC); | ||
27 | - | ||
28 | - @Getter | ||
29 | - private final String attributesResponseTopicBase; | ||
30 | - | ||
31 | - @Getter | ||
32 | - private final String attributesSubTopic; | ||
33 | - | ||
34 | - @Getter | ||
35 | - private final String rpcRequestTopicBase; | ||
36 | - | ||
37 | - @Getter | ||
38 | - private final String rpcResponseTopicBase; | ||
39 | - | ||
40 | - TopicType(String attributesRequestTopicBase, String attributesSubTopic, String rpcRequestTopicBase, String rpcResponseTopicBase) { | ||
41 | - this.attributesResponseTopicBase = attributesRequestTopicBase; | ||
42 | - this.attributesSubTopic = attributesSubTopic; | ||
43 | - this.rpcRequestTopicBase = rpcRequestTopicBase; | ||
44 | - this.rpcResponseTopicBase = rpcResponseTopicBase; | ||
45 | - } | ||
46 | -} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/adaptors/BackwardCompatibilityAdaptor.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp.adaptors; | ||
17 | - | ||
18 | -import io.netty.handler.codec.mqtt.MqttMessage; | ||
19 | -import io.netty.handler.codec.mqtt.MqttPublishMessage; | ||
20 | -import lombok.AllArgsConstructor; | ||
21 | -import lombok.Data; | ||
22 | -import lombok.extern.slf4j.Slf4j; | ||
23 | -import org.thingsboard.server.common.data.ota.OtaPackageType; | ||
24 | -import org.thingsboard.server.common.transport.adaptor.AdaptorException; | ||
25 | -import org.thingsboard.server.gen.transport.TransportProtos; | ||
26 | -import org.thingsboard.server.transport.tcp.session.MqttDeviceAwareSessionContext; | ||
27 | - | ||
28 | -import java.util.Optional; | ||
29 | - | ||
30 | -@Data | ||
31 | -@AllArgsConstructor | ||
32 | -@Slf4j | ||
33 | -public class BackwardCompatibilityAdaptor implements TcpTransportAdaptor { | ||
34 | - | ||
35 | - private TcpTransportAdaptor protoAdaptor; | ||
36 | - private TcpTransportAdaptor jsonAdaptor; | ||
37 | - | ||
38 | - @Override | ||
39 | - public TransportProtos.PostTelemetryMsg convertToPostTelemetry(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
40 | - try { | ||
41 | - return protoAdaptor.convertToPostTelemetry(ctx, inbound); | ||
42 | - } catch (AdaptorException e) { | ||
43 | - log.trace("[{}] failed to process post telemetry request msg: {} due to: ", ctx.getSessionId(), inbound, e); | ||
44 | - return jsonAdaptor.convertToPostTelemetry(ctx, inbound); | ||
45 | - } | ||
46 | - } | ||
47 | - | ||
48 | - @Override | ||
49 | - public TransportProtos.PostAttributeMsg convertToPostAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
50 | - try { | ||
51 | - return protoAdaptor.convertToPostAttributes(ctx, inbound); | ||
52 | - } catch (AdaptorException e) { | ||
53 | - log.trace("[{}] failed to process post attributes request msg: {} due to: ", ctx.getSessionId(), inbound, e); | ||
54 | - return jsonAdaptor.convertToPostAttributes(ctx, inbound); | ||
55 | - } | ||
56 | - } | ||
57 | - | ||
58 | - @Override | ||
59 | - public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { | ||
60 | - try { | ||
61 | - return protoAdaptor.convertToGetAttributes(ctx, inbound, topicBase); | ||
62 | - } catch (AdaptorException e) { | ||
63 | - log.trace("[{}] failed to process get attributes request msg: {} due to: ", ctx.getSessionId(), inbound, e); | ||
64 | - return jsonAdaptor.convertToGetAttributes(ctx, inbound, topicBase); | ||
65 | - } | ||
66 | - } | ||
67 | - | ||
68 | - @Override | ||
69 | - public TransportProtos.ToDeviceRpcResponseMsg convertToDeviceRpcResponse(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException { | ||
70 | - try { | ||
71 | - return protoAdaptor.convertToDeviceRpcResponse(ctx, mqttMsg, topicBase); | ||
72 | - } catch (AdaptorException e) { | ||
73 | - log.trace("[{}] failed to process to device rpc response msg: {} due to: ", ctx.getSessionId(), mqttMsg, e); | ||
74 | - return jsonAdaptor.convertToDeviceRpcResponse(ctx, mqttMsg, topicBase); | ||
75 | - } | ||
76 | - } | ||
77 | - | ||
78 | - @Override | ||
79 | - public TransportProtos.ToServerRpcRequestMsg convertToServerRpcRequest(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException { | ||
80 | - try { | ||
81 | - return protoAdaptor.convertToServerRpcRequest(ctx, mqttMsg, topicBase); | ||
82 | - } catch (AdaptorException e) { | ||
83 | - log.trace("[{}] failed to process to server rpc request msg: {} due to: ", ctx.getSessionId(), mqttMsg, e); | ||
84 | - return jsonAdaptor.convertToServerRpcRequest(ctx, mqttMsg, topicBase); | ||
85 | - } | ||
86 | - } | ||
87 | - | ||
88 | - @Override | ||
89 | - public TransportProtos.ClaimDeviceMsg convertToClaimDevice(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
90 | - try { | ||
91 | - return protoAdaptor.convertToClaimDevice(ctx, inbound); | ||
92 | - } catch (AdaptorException e) { | ||
93 | - log.trace("[{}] failed to process claim device request msg: {} due to: ", ctx.getSessionId(), inbound, e); | ||
94 | - return jsonAdaptor.convertToClaimDevice(ctx, inbound); | ||
95 | - } | ||
96 | - } | ||
97 | - | ||
98 | - @Override | ||
99 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException { | ||
100 | - log.warn("[{}] invoked not implemented adaptor method! GetAttributeResponseMsg: {} TopicBase: {}", ctx.getSessionId(), responseMsg, topicBase); | ||
101 | - return Optional.empty(); | ||
102 | - } | ||
103 | - | ||
104 | - @Override | ||
105 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { | ||
106 | - return protoAdaptor.convertToGatewayPublish(ctx, deviceName, responseMsg); | ||
107 | - } | ||
108 | - | ||
109 | - @Override | ||
110 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.AttributeUpdateNotificationMsg notificationMsg, String topic) throws AdaptorException { | ||
111 | - log.warn("[{}] invoked not implemented adaptor method! AttributeUpdateNotificationMsg: {} Topic: {}", ctx.getSessionId(), notificationMsg, topic); | ||
112 | - return Optional.empty(); | ||
113 | - } | ||
114 | - | ||
115 | - @Override | ||
116 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.AttributeUpdateNotificationMsg notificationMsg) throws AdaptorException { | ||
117 | - return protoAdaptor.convertToGatewayPublish(ctx, deviceName, notificationMsg); | ||
118 | - } | ||
119 | - | ||
120 | - @Override | ||
121 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ToDeviceRpcRequestMsg rpcRequest, String topicBase) throws AdaptorException { | ||
122 | - log.warn("[{}] invoked not implemented adaptor method! ToDeviceRpcRequestMsg: {} TopicBase: {}", ctx.getSessionId(), rpcRequest, topicBase); | ||
123 | - return Optional.empty(); | ||
124 | - } | ||
125 | - | ||
126 | - @Override | ||
127 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) throws AdaptorException { | ||
128 | - return protoAdaptor.convertToGatewayPublish(ctx, deviceName, rpcRequest); | ||
129 | - } | ||
130 | - | ||
131 | - @Override | ||
132 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ToServerRpcResponseMsg rpcResponse, String topicBase) throws AdaptorException { | ||
133 | - log.warn("[{}] invoked not implemented adaptor method! ToServerRpcResponseMsg: {} TopicBase: {}", ctx.getSessionId(), rpcResponse, topicBase); | ||
134 | - return Optional.empty(); | ||
135 | - } | ||
136 | - | ||
137 | - @Override | ||
138 | - public TransportProtos.ProvisionDeviceRequestMsg convertToProvisionRequestMsg(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
139 | - log.warn("[{}] invoked not implemented adaptor method! MqttPublishMessage: {}", ctx.getSessionId(), inbound); | ||
140 | - return null; | ||
141 | - } | ||
142 | - | ||
143 | - @Override | ||
144 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ProvisionDeviceResponseMsg provisionResponse) throws AdaptorException { | ||
145 | - log.warn("[{}] invoked not implemented adaptor method! ProvisionDeviceResponseMsg: {}", ctx.getSessionId(), provisionResponse); | ||
146 | - return Optional.empty(); | ||
147 | - } | ||
148 | - | ||
149 | - @Override | ||
150 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, byte[] firmwareChunk, String requestId, int chunk, OtaPackageType firmwareType) throws AdaptorException { | ||
151 | - return protoAdaptor.convertToPublish(ctx, firmwareChunk, requestId, chunk, firmwareType); | ||
152 | - } | ||
153 | -} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/adaptors/JsonTcpAdaptor.java
@@ -33,7 +33,7 @@ import org.thingsboard.server.common.data.ota.OtaPackageType; | @@ -33,7 +33,7 @@ import org.thingsboard.server.common.data.ota.OtaPackageType; | ||
33 | import org.thingsboard.server.common.transport.adaptor.AdaptorException; | 33 | import org.thingsboard.server.common.transport.adaptor.AdaptorException; |
34 | import org.thingsboard.server.common.transport.adaptor.JsonConverter; | 34 | import org.thingsboard.server.common.transport.adaptor.JsonConverter; |
35 | import org.thingsboard.server.gen.transport.TransportProtos; | 35 | import org.thingsboard.server.gen.transport.TransportProtos; |
36 | -import org.thingsboard.server.transport.tcp.session.MqttDeviceAwareSessionContext; | 36 | +import org.thingsboard.server.transport.tcp.session.DeviceSessionCtx; |
37 | 37 | ||
38 | import java.nio.charset.Charset; | 38 | import java.nio.charset.Charset; |
39 | import java.nio.charset.StandardCharsets; | 39 | import java.nio.charset.StandardCharsets; |
@@ -56,7 +56,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -56,7 +56,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
56 | protected static final Charset UTF8 = StandardCharsets.UTF_8; | 56 | protected static final Charset UTF8 = StandardCharsets.UTF_8; |
57 | 57 | ||
58 | @Override | 58 | @Override |
59 | - public TransportProtos.PostTelemetryMsg convertToPostTelemetry(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | 59 | + public TransportProtos.PostTelemetryMsg convertToPostTelemetry(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException { |
60 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); | 60 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); |
61 | try { | 61 | try { |
62 | return JsonConverter.convertToTelemetryProto(new JsonParser().parse(payload)); | 62 | return JsonConverter.convertToTelemetryProto(new JsonParser().parse(payload)); |
@@ -67,7 +67,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -67,7 +67,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
67 | } | 67 | } |
68 | 68 | ||
69 | @Override | 69 | @Override |
70 | - public TransportProtos.PostAttributeMsg convertToPostAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | 70 | + public TransportProtos.PostAttributeMsg convertToPostAttributes(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException { |
71 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); | 71 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); |
72 | try { | 72 | try { |
73 | return JsonConverter.convertToAttributesProto(new JsonParser().parse(payload)); | 73 | return JsonConverter.convertToAttributesProto(new JsonParser().parse(payload)); |
@@ -78,7 +78,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -78,7 +78,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
78 | } | 78 | } |
79 | 79 | ||
80 | @Override | 80 | @Override |
81 | - public TransportProtos.ClaimDeviceMsg convertToClaimDevice(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | 81 | + public TransportProtos.ClaimDeviceMsg convertToClaimDevice(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException { |
82 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), true); | 82 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), true); |
83 | try { | 83 | try { |
84 | return JsonConverter.convertToClaimDeviceProto(ctx.getDeviceId(), payload); | 84 | return JsonConverter.convertToClaimDeviceProto(ctx.getDeviceId(), payload); |
@@ -89,7 +89,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -89,7 +89,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
89 | } | 89 | } |
90 | 90 | ||
91 | @Override | 91 | @Override |
92 | - public TransportProtos.ProvisionDeviceRequestMsg convertToProvisionRequestMsg(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | 92 | + public TransportProtos.ProvisionDeviceRequestMsg convertToProvisionRequestMsg(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException { |
93 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); | 93 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); |
94 | try { | 94 | try { |
95 | return JsonConverter.convertToProvisionRequestMsg(payload); | 95 | return JsonConverter.convertToProvisionRequestMsg(payload); |
@@ -99,63 +99,63 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -99,63 +99,63 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
99 | } | 99 | } |
100 | 100 | ||
101 | @Override | 101 | @Override |
102 | - public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { | 102 | + public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(DeviceSessionCtx ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { |
103 | return processGetAttributeRequestMsg(inbound, topicBase); | 103 | return processGetAttributeRequestMsg(inbound, topicBase); |
104 | } | 104 | } |
105 | 105 | ||
106 | @Override | 106 | @Override |
107 | - public TransportProtos.ToDeviceRpcResponseMsg convertToDeviceRpcResponse(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { | 107 | + public TransportProtos.ToDeviceRpcResponseMsg convertToDeviceRpcResponse(DeviceSessionCtx ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { |
108 | return processToDeviceRpcResponseMsg(inbound, topicBase); | 108 | return processToDeviceRpcResponseMsg(inbound, topicBase); |
109 | } | 109 | } |
110 | 110 | ||
111 | @Override | 111 | @Override |
112 | - public TransportProtos.ToServerRpcRequestMsg convertToServerRpcRequest(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { | 112 | + public TransportProtos.ToServerRpcRequestMsg convertToServerRpcRequest(DeviceSessionCtx ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { |
113 | return processToServerRpcRequestMsg(ctx, inbound, topicBase); | 113 | return processToServerRpcRequestMsg(ctx, inbound, topicBase); |
114 | } | 114 | } |
115 | 115 | ||
116 | @Override | 116 | @Override |
117 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException { | 117 | + public Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, TransportProtos.GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException { |
118 | return processConvertFromAttributeResponseMsg(ctx, responseMsg, topicBase); | 118 | return processConvertFromAttributeResponseMsg(ctx, responseMsg, topicBase); |
119 | } | 119 | } |
120 | 120 | ||
121 | @Override | 121 | @Override |
122 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { | 122 | + public Optional<MqttMessage> convertToGatewayPublish(DeviceSessionCtx ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { |
123 | return processConvertFromGatewayAttributeResponseMsg(ctx, deviceName, responseMsg); | 123 | return processConvertFromGatewayAttributeResponseMsg(ctx, deviceName, responseMsg); |
124 | } | 124 | } |
125 | 125 | ||
126 | @Override | 126 | @Override |
127 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.AttributeUpdateNotificationMsg notificationMsg, String topic) { | 127 | + public Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, TransportProtos.AttributeUpdateNotificationMsg notificationMsg, String topic) { |
128 | return Optional.of(createMqttPublishMsg(ctx, topic, JsonConverter.toJson(notificationMsg))); | 128 | return Optional.of(createMqttPublishMsg(ctx, topic, JsonConverter.toJson(notificationMsg))); |
129 | } | 129 | } |
130 | 130 | ||
131 | @Override | 131 | @Override |
132 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.AttributeUpdateNotificationMsg notificationMsg) { | 132 | + public Optional<MqttMessage> convertToGatewayPublish(DeviceSessionCtx ctx, String deviceName, TransportProtos.AttributeUpdateNotificationMsg notificationMsg) { |
133 | JsonObject result = JsonConverter.getJsonObjectForGateway(deviceName, notificationMsg); | 133 | JsonObject result = JsonConverter.getJsonObjectForGateway(deviceName, notificationMsg); |
134 | return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, result)); | 134 | return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, result)); |
135 | } | 135 | } |
136 | 136 | ||
137 | @Override | 137 | @Override |
138 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ToDeviceRpcRequestMsg rpcRequest, String topicBase) { | 138 | + public Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, TransportProtos.ToDeviceRpcRequestMsg rpcRequest, String topicBase) { |
139 | return Optional.of(createMqttPublishMsg(ctx, topicBase + rpcRequest.getRequestId(), JsonConverter.toJson(rpcRequest, false))); | 139 | return Optional.of(createMqttPublishMsg(ctx, topicBase + rpcRequest.getRequestId(), JsonConverter.toJson(rpcRequest, false))); |
140 | } | 140 | } |
141 | 141 | ||
142 | @Override | 142 | @Override |
143 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) { | 143 | + public Optional<MqttMessage> convertToGatewayPublish(DeviceSessionCtx ctx, String deviceName, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) { |
144 | return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_RPC_TOPIC, JsonConverter.toGatewayJson(deviceName, rpcRequest))); | 144 | return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_RPC_TOPIC, JsonConverter.toGatewayJson(deviceName, rpcRequest))); |
145 | } | 145 | } |
146 | 146 | ||
147 | @Override | 147 | @Override |
148 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ToServerRpcResponseMsg rpcResponse, String topicBase) { | 148 | + public Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, TransportProtos.ToServerRpcResponseMsg rpcResponse, String topicBase) { |
149 | return Optional.of(createMqttPublishMsg(ctx, topicBase + rpcResponse.getRequestId(), JsonConverter.toJson(rpcResponse))); | 149 | return Optional.of(createMqttPublishMsg(ctx, topicBase + rpcResponse.getRequestId(), JsonConverter.toJson(rpcResponse))); |
150 | } | 150 | } |
151 | 151 | ||
152 | @Override | 152 | @Override |
153 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ProvisionDeviceResponseMsg provisionResponse) { | 153 | + public Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, TransportProtos.ProvisionDeviceResponseMsg provisionResponse) { |
154 | return Optional.of(createMqttPublishMsg(ctx, MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC, JsonConverter.toJson(provisionResponse))); | 154 | return Optional.of(createMqttPublishMsg(ctx, MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC, JsonConverter.toJson(provisionResponse))); |
155 | } | 155 | } |
156 | 156 | ||
157 | @Override | 157 | @Override |
158 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, byte[] firmwareChunk, String requestId, int chunk, OtaPackageType firmwareType) { | 158 | + public Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, byte[] firmwareChunk, String requestId, int chunk, OtaPackageType firmwareType) { |
159 | return Optional.of(createMqttPublishMsg(ctx, String.format(DEVICE_SOFTWARE_FIRMWARE_RESPONSES_TOPIC_FORMAT, firmwareType.getKeyPrefix(), requestId, chunk), firmwareChunk)); | 159 | return Optional.of(createMqttPublishMsg(ctx, String.format(DEVICE_SOFTWARE_FIRMWARE_RESPONSES_TOPIC_FORMAT, firmwareType.getKeyPrefix(), requestId, chunk), firmwareChunk)); |
160 | } | 160 | } |
161 | 161 | ||
@@ -203,7 +203,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -203,7 +203,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
203 | } | 203 | } |
204 | } | 204 | } |
205 | 205 | ||
206 | - private TransportProtos.ToServerRpcRequestMsg processToServerRpcRequestMsg(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { | 206 | + private TransportProtos.ToServerRpcRequestMsg processToServerRpcRequestMsg(DeviceSessionCtx ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { |
207 | String topicName = inbound.variableHeader().topicName(); | 207 | String topicName = inbound.variableHeader().topicName(); |
208 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); | 208 | String payload = validatePayload(ctx.getSessionId(), inbound.payload(), false); |
209 | try { | 209 | try { |
@@ -215,7 +215,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -215,7 +215,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
215 | } | 215 | } |
216 | } | 216 | } |
217 | 217 | ||
218 | - private Optional<MqttMessage> processConvertFromAttributeResponseMsg(MqttDeviceAwareSessionContext ctx, TransportProtos.GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException { | 218 | + private Optional<MqttMessage> processConvertFromAttributeResponseMsg(DeviceSessionCtx ctx, TransportProtos.GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException { |
219 | if (!StringUtils.isEmpty(responseMsg.getError())) { | 219 | if (!StringUtils.isEmpty(responseMsg.getError())) { |
220 | throw new AdaptorException(responseMsg.getError()); | 220 | throw new AdaptorException(responseMsg.getError()); |
221 | } else { | 221 | } else { |
@@ -229,7 +229,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -229,7 +229,7 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
229 | } | 229 | } |
230 | } | 230 | } |
231 | 231 | ||
232 | - private Optional<MqttMessage> processConvertFromGatewayAttributeResponseMsg(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { | 232 | + private Optional<MqttMessage> processConvertFromGatewayAttributeResponseMsg(DeviceSessionCtx ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { |
233 | if (!StringUtils.isEmpty(responseMsg.getError())) { | 233 | if (!StringUtils.isEmpty(responseMsg.getError())) { |
234 | throw new AdaptorException(responseMsg.getError()); | 234 | throw new AdaptorException(responseMsg.getError()); |
235 | } else { | 235 | } else { |
@@ -238,9 +238,9 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | @@ -238,9 +238,9 @@ public class JsonTcpAdaptor implements TcpTransportAdaptor { | ||
238 | } | 238 | } |
239 | } | 239 | } |
240 | 240 | ||
241 | - protected MqttPublishMessage createMqttPublishMsg(MqttDeviceAwareSessionContext ctx, String topic, JsonElement json) { | ||
242 | - MqttFixedHeader mqttFixedHeader = | ||
243 | - new MqttFixedHeader(MqttMessageType.PUBLISH, false, ctx.getQoSForTopic(topic), false, 0); | 241 | + protected MqttPublishMessage createMqttPublishMsg(DeviceSessionCtx ctx, String topic, JsonElement json) { |
242 | + MqttFixedHeader mqttFixedHeader = null; | ||
243 | +// new MqttFixedHeader(MqttMessageType.PUBLISH, false, ctx.getQoSForTopic(topic), false, 0); | ||
244 | MqttPublishVariableHeader header = new MqttPublishVariableHeader(topic, ctx.nextMsgId()); | 244 | MqttPublishVariableHeader header = new MqttPublishVariableHeader(topic, ctx.nextMsgId()); |
245 | ByteBuf payload = ALLOCATOR.buffer(); | 245 | ByteBuf payload = ALLOCATOR.buffer(); |
246 | payload.writeBytes(json.toString().getBytes(UTF8)); | 246 | payload.writeBytes(json.toString().getBytes(UTF8)); |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/adaptors/ProtoTcpAdaptor.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp.adaptors; | ||
17 | - | ||
18 | -import com.google.gson.JsonElement; | ||
19 | -import com.google.gson.JsonParser; | ||
20 | -import com.google.protobuf.Descriptors; | ||
21 | -import com.google.protobuf.DynamicMessage; | ||
22 | -import com.google.protobuf.InvalidProtocolBufferException; | ||
23 | -import io.netty.buffer.ByteBuf; | ||
24 | -import io.netty.handler.codec.mqtt.MqttMessage; | ||
25 | -import io.netty.handler.codec.mqtt.MqttPublishMessage; | ||
26 | -import lombok.extern.slf4j.Slf4j; | ||
27 | -import org.springframework.stereotype.Component; | ||
28 | -import org.springframework.util.StringUtils; | ||
29 | -import org.thingsboard.server.common.data.device.profile.MqttTopics; | ||
30 | -import org.thingsboard.server.common.data.ota.OtaPackageType; | ||
31 | -import org.thingsboard.server.common.transport.adaptor.AdaptorException; | ||
32 | -import org.thingsboard.server.common.transport.adaptor.JsonConverter; | ||
33 | -import org.thingsboard.server.common.transport.adaptor.ProtoConverter; | ||
34 | -import org.thingsboard.server.gen.transport.TransportApiProtos; | ||
35 | -import org.thingsboard.server.gen.transport.TransportProtos; | ||
36 | -import org.thingsboard.server.transport.tcp.session.DeviceSessionCtx; | ||
37 | -import org.thingsboard.server.transport.tcp.session.MqttDeviceAwareSessionContext; | ||
38 | - | ||
39 | -import java.util.Optional; | ||
40 | - | ||
41 | -import static org.thingsboard.server.common.data.device.profile.MqttTopics.DEVICE_SOFTWARE_FIRMWARE_RESPONSES_TOPIC_FORMAT; | ||
42 | - | ||
43 | -@Component | ||
44 | -@Slf4j | ||
45 | -public class ProtoTcpAdaptor implements TcpTransportAdaptor { | ||
46 | - | ||
47 | - @Override | ||
48 | - public TransportProtos.PostTelemetryMsg convertToPostTelemetry(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
49 | - DeviceSessionCtx deviceSessionCtx = (DeviceSessionCtx) ctx; | ||
50 | - byte[] bytes = toBytes(inbound.payload()); | ||
51 | - Descriptors.Descriptor telemetryDynamicMsgDescriptor = ProtoConverter.validateDescriptor(deviceSessionCtx.getTelemetryDynamicMsgDescriptor()); | ||
52 | - try { | ||
53 | - return JsonConverter.convertToTelemetryProto(new JsonParser().parse(ProtoConverter.dynamicMsgToJson(bytes, telemetryDynamicMsgDescriptor))); | ||
54 | - } catch (Exception e) { | ||
55 | - log.debug("Failed to decode post telemetry request", e); | ||
56 | - throw new AdaptorException(e); | ||
57 | - } | ||
58 | - } | ||
59 | - | ||
60 | - @Override | ||
61 | - public TransportProtos.PostAttributeMsg convertToPostAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
62 | - DeviceSessionCtx deviceSessionCtx = (DeviceSessionCtx) ctx; | ||
63 | - byte[] bytes = toBytes(inbound.payload()); | ||
64 | - Descriptors.Descriptor attributesDynamicMessageDescriptor = ProtoConverter.validateDescriptor(deviceSessionCtx.getAttributesDynamicMessageDescriptor()); | ||
65 | - try { | ||
66 | - return JsonConverter.convertToAttributesProto(new JsonParser().parse(ProtoConverter.dynamicMsgToJson(bytes, attributesDynamicMessageDescriptor))); | ||
67 | - } catch (Exception e) { | ||
68 | - log.debug("Failed to decode post attributes request", e); | ||
69 | - throw new AdaptorException(e); | ||
70 | - } | ||
71 | - } | ||
72 | - | ||
73 | - @Override | ||
74 | - public TransportProtos.ClaimDeviceMsg convertToClaimDevice(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException { | ||
75 | - byte[] bytes = toBytes(inbound.payload()); | ||
76 | - try { | ||
77 | - return ProtoConverter.convertToClaimDeviceProto(ctx.getDeviceId(), bytes); | ||
78 | - } catch (InvalidProtocolBufferException e) { | ||
79 | - log.debug("Failed to decode claim device request", e); | ||
80 | - throw new AdaptorException(e); | ||
81 | - } | ||
82 | - } | ||
83 | - | ||
84 | - @Override | ||
85 | - public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException { | ||
86 | - byte[] bytes = toBytes(inbound.payload()); | ||
87 | - String topicName = inbound.variableHeader().topicName(); | ||
88 | - try { | ||
89 | - int requestId = getRequestId(topicName, topicBase); | ||
90 | - return ProtoConverter.convertToGetAttributeRequestMessage(bytes, requestId); | ||
91 | - } catch (InvalidProtocolBufferException e) { | ||
92 | - log.debug("Failed to decode get attributes request", e); | ||
93 | - throw new AdaptorException(e); | ||
94 | - } | ||
95 | - } | ||
96 | - | ||
97 | - @Override | ||
98 | - public TransportProtos.ToDeviceRpcResponseMsg convertToDeviceRpcResponse(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException { | ||
99 | - DeviceSessionCtx deviceSessionCtx = (DeviceSessionCtx) ctx; | ||
100 | - String topicName = mqttMsg.variableHeader().topicName(); | ||
101 | - byte[] bytes = toBytes(mqttMsg.payload()); | ||
102 | - Descriptors.Descriptor rpcResponseDynamicMessageDescriptor = ProtoConverter.validateDescriptor(deviceSessionCtx.getRpcResponseDynamicMessageDescriptor()); | ||
103 | - try { | ||
104 | - int requestId = getRequestId(topicName, topicBase); | ||
105 | - JsonElement response = new JsonParser().parse(ProtoConverter.dynamicMsgToJson(bytes, rpcResponseDynamicMessageDescriptor)); | ||
106 | - return TransportProtos.ToDeviceRpcResponseMsg.newBuilder().setRequestId(requestId).setPayload(response.toString()).build(); | ||
107 | - } catch (Exception e) { | ||
108 | - log.debug("Failed to decode rpc response", e); | ||
109 | - throw new AdaptorException(e); | ||
110 | - } | ||
111 | - } | ||
112 | - | ||
113 | - @Override | ||
114 | - public TransportProtos.ToServerRpcRequestMsg convertToServerRpcRequest(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException { | ||
115 | - byte[] bytes = toBytes(mqttMsg.payload()); | ||
116 | - String topicName = mqttMsg.variableHeader().topicName(); | ||
117 | - try { | ||
118 | - int requestId = getRequestId(topicName, topicBase); | ||
119 | - return ProtoConverter.convertToServerRpcRequest(bytes, requestId); | ||
120 | - } catch (InvalidProtocolBufferException e) { | ||
121 | - log.debug("Failed to decode to server rpc request", e); | ||
122 | - throw new AdaptorException(e); | ||
123 | - } | ||
124 | - } | ||
125 | - | ||
126 | - @Override | ||
127 | - public TransportProtos.ProvisionDeviceRequestMsg convertToProvisionRequestMsg(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg) throws AdaptorException { | ||
128 | - byte[] bytes = toBytes(mqttMsg.payload()); | ||
129 | - try { | ||
130 | - return ProtoConverter.convertToProvisionRequestMsg(bytes); | ||
131 | - } catch (InvalidProtocolBufferException ex) { | ||
132 | - log.debug("Failed to decode provision request", ex); | ||
133 | - throw new AdaptorException(ex); | ||
134 | - } | ||
135 | - } | ||
136 | - | ||
137 | - @Override | ||
138 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException { | ||
139 | - if (!StringUtils.isEmpty(responseMsg.getError())) { | ||
140 | - throw new AdaptorException(responseMsg.getError()); | ||
141 | - } else { | ||
142 | - int requestId = responseMsg.getRequestId(); | ||
143 | - if (requestId >= 0) { | ||
144 | - return Optional.of(createMqttPublishMsg(ctx, topicBase + requestId, responseMsg.toByteArray())); | ||
145 | - } | ||
146 | - return Optional.empty(); | ||
147 | - } | ||
148 | - } | ||
149 | - | ||
150 | - @Override | ||
151 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ToDeviceRpcRequestMsg rpcRequest, String topicBase) throws AdaptorException { | ||
152 | - DeviceSessionCtx deviceSessionCtx = (DeviceSessionCtx) ctx; | ||
153 | - DynamicMessage.Builder rpcRequestDynamicMessageBuilder = deviceSessionCtx.getRpcRequestDynamicMessageBuilder(); | ||
154 | - if (rpcRequestDynamicMessageBuilder == null) { | ||
155 | - throw new AdaptorException("Failed to get rpcRequestDynamicMessageBuilder!"); | ||
156 | - } else { | ||
157 | - return Optional.of(createMqttPublishMsg(ctx, topicBase + rpcRequest.getRequestId(), ProtoConverter.convertToRpcRequest(rpcRequest, rpcRequestDynamicMessageBuilder))); | ||
158 | - } | ||
159 | - } | ||
160 | - | ||
161 | - @Override | ||
162 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ToServerRpcResponseMsg rpcResponse, String topicBase) { | ||
163 | - return Optional.of(createMqttPublishMsg(ctx, topicBase + rpcResponse.getRequestId(), rpcResponse.toByteArray())); | ||
164 | - } | ||
165 | - | ||
166 | - @Override | ||
167 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.AttributeUpdateNotificationMsg notificationMsg, String topic) { | ||
168 | - return Optional.of(createMqttPublishMsg(ctx, topic, notificationMsg.toByteArray())); | ||
169 | - } | ||
170 | - | ||
171 | - @Override | ||
172 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, TransportProtos.ProvisionDeviceResponseMsg provisionResponse) { | ||
173 | - return Optional.of(createMqttPublishMsg(ctx, MqttTopics.DEVICE_PROVISION_RESPONSE_TOPIC, provisionResponse.toByteArray())); | ||
174 | - } | ||
175 | - | ||
176 | - @Override | ||
177 | - public Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, byte[] firmwareChunk, String requestId, int chunk, OtaPackageType firmwareType) throws AdaptorException { | ||
178 | - return Optional.of(createMqttPublishMsg(ctx, String.format(DEVICE_SOFTWARE_FIRMWARE_RESPONSES_TOPIC_FORMAT, firmwareType.getKeyPrefix(), requestId, chunk), firmwareChunk)); | ||
179 | - } | ||
180 | - | ||
181 | - @Override | ||
182 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.GetAttributeResponseMsg responseMsg) throws AdaptorException { | ||
183 | - if (!StringUtils.isEmpty(responseMsg.getError())) { | ||
184 | - throw new AdaptorException(responseMsg.getError()); | ||
185 | - } else { | ||
186 | - TransportApiProtos.GatewayAttributeResponseMsg.Builder responseMsgBuilder = TransportApiProtos.GatewayAttributeResponseMsg.newBuilder(); | ||
187 | - responseMsgBuilder.setDeviceName(deviceName); | ||
188 | - responseMsgBuilder.setResponseMsg(responseMsg); | ||
189 | - byte[] payloadBytes = responseMsgBuilder.build().toByteArray(); | ||
190 | - return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_RESPONSE_TOPIC, payloadBytes)); | ||
191 | - } | ||
192 | - } | ||
193 | - | ||
194 | - @Override | ||
195 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.AttributeUpdateNotificationMsg notificationMsg) { | ||
196 | - TransportApiProtos.GatewayAttributeUpdateNotificationMsg.Builder builder = TransportApiProtos.GatewayAttributeUpdateNotificationMsg.newBuilder(); | ||
197 | - builder.setDeviceName(deviceName); | ||
198 | - builder.setNotificationMsg(notificationMsg); | ||
199 | - byte[] payloadBytes = builder.build().toByteArray(); | ||
200 | - return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_ATTRIBUTES_TOPIC, payloadBytes)); | ||
201 | - } | ||
202 | - | ||
203 | - @Override | ||
204 | - public Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, TransportProtos.ToDeviceRpcRequestMsg rpcRequest) { | ||
205 | - TransportApiProtos.GatewayDeviceRpcRequestMsg.Builder builder = TransportApiProtos.GatewayDeviceRpcRequestMsg.newBuilder(); | ||
206 | - builder.setDeviceName(deviceName); | ||
207 | - builder.setRpcRequestMsg(rpcRequest); | ||
208 | - byte[] payloadBytes = builder.build().toByteArray(); | ||
209 | - return Optional.of(createMqttPublishMsg(ctx, MqttTopics.GATEWAY_RPC_TOPIC, payloadBytes)); | ||
210 | - } | ||
211 | - | ||
212 | - public static byte[] toBytes(ByteBuf inbound) { | ||
213 | - byte[] bytes = new byte[inbound.readableBytes()]; | ||
214 | - int readerIndex = inbound.readerIndex(); | ||
215 | - inbound.getBytes(readerIndex, bytes); | ||
216 | - return bytes; | ||
217 | - } | ||
218 | - | ||
219 | - private int getRequestId(String topicName, String topic) { | ||
220 | - return Integer.parseInt(topicName.substring(topic.length())); | ||
221 | - } | ||
222 | -} |
@@ -37,7 +37,7 @@ import org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcRequestMs | @@ -37,7 +37,7 @@ import org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcRequestMs | ||
37 | import org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcResponseMsg; | 37 | import org.thingsboard.server.gen.transport.TransportProtos.ToDeviceRpcResponseMsg; |
38 | import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcRequestMsg; | 38 | import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcRequestMsg; |
39 | import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcResponseMsg; | 39 | import org.thingsboard.server.gen.transport.TransportProtos.ToServerRpcResponseMsg; |
40 | -import org.thingsboard.server.transport.tcp.session.MqttDeviceAwareSessionContext; | 40 | +import org.thingsboard.server.transport.tcp.session.DeviceSessionCtx; |
41 | 41 | ||
42 | import java.util.Optional; | 42 | import java.util.Optional; |
43 | 43 | ||
@@ -48,41 +48,41 @@ public interface TcpTransportAdaptor { | @@ -48,41 +48,41 @@ public interface TcpTransportAdaptor { | ||
48 | 48 | ||
49 | ByteBufAllocator ALLOCATOR = new UnpooledByteBufAllocator(false); | 49 | ByteBufAllocator ALLOCATOR = new UnpooledByteBufAllocator(false); |
50 | 50 | ||
51 | - PostTelemetryMsg convertToPostTelemetry(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException; | 51 | + PostTelemetryMsg convertToPostTelemetry(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException; |
52 | 52 | ||
53 | - PostAttributeMsg convertToPostAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException; | 53 | + PostAttributeMsg convertToPostAttributes(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException; |
54 | 54 | ||
55 | - GetAttributeRequestMsg convertToGetAttributes(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException; | 55 | + GetAttributeRequestMsg convertToGetAttributes(DeviceSessionCtx ctx, MqttPublishMessage inbound, String topicBase) throws AdaptorException; |
56 | 56 | ||
57 | - ToDeviceRpcResponseMsg convertToDeviceRpcResponse(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException; | 57 | + ToDeviceRpcResponseMsg convertToDeviceRpcResponse(DeviceSessionCtx ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException; |
58 | 58 | ||
59 | - ToServerRpcRequestMsg convertToServerRpcRequest(MqttDeviceAwareSessionContext ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException; | 59 | + ToServerRpcRequestMsg convertToServerRpcRequest(DeviceSessionCtx ctx, MqttPublishMessage mqttMsg, String topicBase) throws AdaptorException; |
60 | 60 | ||
61 | - ClaimDeviceMsg convertToClaimDevice(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException; | 61 | + ClaimDeviceMsg convertToClaimDevice(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException; |
62 | 62 | ||
63 | - Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException; | 63 | + Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, GetAttributeResponseMsg responseMsg, String topicBase) throws AdaptorException; |
64 | 64 | ||
65 | - Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, GetAttributeResponseMsg responseMsg) throws AdaptorException; | 65 | + Optional<MqttMessage> convertToGatewayPublish(DeviceSessionCtx ctx, String deviceName, GetAttributeResponseMsg responseMsg) throws AdaptorException; |
66 | 66 | ||
67 | - Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, AttributeUpdateNotificationMsg notificationMsg, String topic) throws AdaptorException; | 67 | + Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, AttributeUpdateNotificationMsg notificationMsg, String topic) throws AdaptorException; |
68 | 68 | ||
69 | - Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, AttributeUpdateNotificationMsg notificationMsg) throws AdaptorException; | 69 | + Optional<MqttMessage> convertToGatewayPublish(DeviceSessionCtx ctx, String deviceName, AttributeUpdateNotificationMsg notificationMsg) throws AdaptorException; |
70 | 70 | ||
71 | - Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, ToDeviceRpcRequestMsg rpcRequest, String topicBase) throws AdaptorException; | 71 | + Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, ToDeviceRpcRequestMsg rpcRequest, String topicBase) throws AdaptorException; |
72 | 72 | ||
73 | - Optional<MqttMessage> convertToGatewayPublish(MqttDeviceAwareSessionContext ctx, String deviceName, ToDeviceRpcRequestMsg rpcRequest) throws AdaptorException; | 73 | + Optional<MqttMessage> convertToGatewayPublish(DeviceSessionCtx ctx, String deviceName, ToDeviceRpcRequestMsg rpcRequest) throws AdaptorException; |
74 | 74 | ||
75 | - Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, ToServerRpcResponseMsg rpcResponse, String topicBase) throws AdaptorException; | 75 | + Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, ToServerRpcResponseMsg rpcResponse, String topicBase) throws AdaptorException; |
76 | 76 | ||
77 | - ProvisionDeviceRequestMsg convertToProvisionRequestMsg(MqttDeviceAwareSessionContext ctx, MqttPublishMessage inbound) throws AdaptorException; | 77 | + ProvisionDeviceRequestMsg convertToProvisionRequestMsg(DeviceSessionCtx ctx, MqttPublishMessage inbound) throws AdaptorException; |
78 | 78 | ||
79 | - Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, ProvisionDeviceResponseMsg provisionResponse) throws AdaptorException; | 79 | + Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, ProvisionDeviceResponseMsg provisionResponse) throws AdaptorException; |
80 | 80 | ||
81 | - Optional<MqttMessage> convertToPublish(MqttDeviceAwareSessionContext ctx, byte[] firmwareChunk, String requestId, int chunk, OtaPackageType firmwareType) throws AdaptorException; | 81 | + Optional<MqttMessage> convertToPublish(DeviceSessionCtx ctx, byte[] firmwareChunk, String requestId, int chunk, OtaPackageType firmwareType) throws AdaptorException; |
82 | 82 | ||
83 | - default MqttPublishMessage createMqttPublishMsg(MqttDeviceAwareSessionContext ctx, String topic, byte[] payloadInBytes) { | ||
84 | - MqttFixedHeader mqttFixedHeader = | ||
85 | - new MqttFixedHeader(MqttMessageType.PUBLISH, false, ctx.getQoSForTopic(topic), false, 0); | 83 | + default MqttPublishMessage createMqttPublishMsg(DeviceSessionCtx ctx, String topic, byte[] payloadInBytes) { |
84 | + MqttFixedHeader mqttFixedHeader =null; | ||
85 | +// new MqttFixedHeader(MqttMessageType.PUBLISH, false, ctx.getQoSForTopic(topic), false, 0); | ||
86 | MqttPublishVariableHeader header = new MqttPublishVariableHeader(topic, ctx.nextMsgId()); | 86 | MqttPublishVariableHeader header = new MqttPublishVariableHeader(topic, ctx.nextMsgId()); |
87 | ByteBuf payload = ALLOCATOR.buffer(); | 87 | ByteBuf payload = ALLOCATOR.buffer(); |
88 | payload.writeBytes(payloadInBytes); | 88 | payload.writeBytes(payloadInBytes); |
1 | /** | 1 | /** |
2 | * Copyright © 2016-2022 The Thingsboard Authors | 2 | * Copyright © 2016-2022 The Thingsboard Authors |
3 | - * | 3 | + * <p> |
4 | * Licensed under the Apache License, Version 2.0 (the "License"); | 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
5 | * you may not use this file except in compliance with the License. | 5 | * you may not use this file except in compliance with the License. |
6 | * You may obtain a copy of the License at | 6 | * You may obtain a copy of the License at |
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | 7 | + * <p> |
8 | + * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | + * <p> | ||
10 | * Unless required by applicable law or agreed to in writing, software | 10 | * Unless required by applicable law or agreed to in writing, software |
11 | * distributed under the License is distributed on an "AS IS" BASIS, | 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
@@ -15,34 +15,23 @@ | @@ -15,34 +15,23 @@ | ||
15 | */ | 15 | */ |
16 | package org.thingsboard.server.transport.tcp.session; | 16 | package org.thingsboard.server.transport.tcp.session; |
17 | 17 | ||
18 | -import com.google.protobuf.Descriptors; | ||
19 | -import com.google.protobuf.DynamicMessage; | ||
20 | import io.netty.channel.ChannelHandlerContext; | 18 | import io.netty.channel.ChannelHandlerContext; |
21 | -import io.netty.handler.codec.mqtt.MqttMessage; | ||
22 | import io.netty.util.ReferenceCountUtil; | 19 | import io.netty.util.ReferenceCountUtil; |
23 | import lombok.Getter; | 20 | import lombok.Getter; |
24 | import lombok.Setter; | 21 | import lombok.Setter; |
25 | import lombok.extern.slf4j.Slf4j; | 22 | import lombok.extern.slf4j.Slf4j; |
26 | import org.thingsboard.server.common.data.DeviceProfile; | 23 | import org.thingsboard.server.common.data.DeviceProfile; |
27 | -import org.thingsboard.server.common.data.DeviceTransportType; | ||
28 | -import org.thingsboard.server.common.data.TransportPayloadType; | ||
29 | import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; | 24 | import org.thingsboard.server.common.data.device.profile.DeviceProfileTransportConfiguration; |
30 | -import org.thingsboard.server.common.data.device.profile.MqttDeviceProfileTransportConfiguration; | ||
31 | -import org.thingsboard.server.common.data.device.profile.ProtoTransportPayloadConfiguration; | ||
32 | -import org.thingsboard.server.common.data.device.profile.TransportPayloadTypeConfiguration; | 25 | +import org.thingsboard.server.common.data.device.profile.TcpDeviceProfileTransportConfiguration; |
26 | +import org.thingsboard.server.common.data.yunteng.enums.TcpDataTypeEnum; | ||
27 | +import org.thingsboard.server.common.transport.session.DeviceAwareSessionContext; | ||
33 | import org.thingsboard.server.gen.transport.TransportProtos; | 28 | import org.thingsboard.server.gen.transport.TransportProtos; |
34 | import org.thingsboard.server.transport.tcp.TcpTransportContext; | 29 | import org.thingsboard.server.transport.tcp.TcpTransportContext; |
35 | -import org.thingsboard.server.transport.tcp.TopicType; | ||
36 | -import org.thingsboard.server.transport.tcp.adaptors.BackwardCompatibilityAdaptor; | ||
37 | import org.thingsboard.server.transport.tcp.adaptors.TcpTransportAdaptor; | 30 | import org.thingsboard.server.transport.tcp.adaptors.TcpTransportAdaptor; |
38 | -import org.thingsboard.server.transport.tcp.util.TcpTopicFilter; | ||
39 | -import org.thingsboard.server.transport.tcp.util.MqttTopicFilterFactory; | 31 | +import org.thingsboard.server.transport.tcp.util.ByteUtils; |
40 | 32 | ||
41 | -import java.util.Collection; | ||
42 | -import java.util.Collections; | ||
43 | import java.util.UUID; | 33 | import java.util.UUID; |
44 | import java.util.concurrent.ConcurrentLinkedQueue; | 34 | import java.util.concurrent.ConcurrentLinkedQueue; |
45 | -import java.util.concurrent.ConcurrentMap; | ||
46 | import java.util.concurrent.atomic.AtomicInteger; | 35 | import java.util.concurrent.atomic.AtomicInteger; |
47 | import java.util.concurrent.locks.Lock; | 36 | import java.util.concurrent.locks.Lock; |
48 | import java.util.concurrent.locks.ReentrantLock; | 37 | import java.util.concurrent.locks.ReentrantLock; |
@@ -52,7 +41,7 @@ import java.util.function.Consumer; | @@ -52,7 +41,7 @@ import java.util.function.Consumer; | ||
52 | * @author Andrew Shvayka | 41 | * @author Andrew Shvayka |
53 | */ | 42 | */ |
54 | @Slf4j | 43 | @Slf4j |
55 | -public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | 44 | +public class DeviceSessionCtx extends DeviceAwareSessionContext { |
56 | 45 | ||
57 | @Getter | 46 | @Getter |
58 | @Setter | 47 | @Setter |
@@ -63,7 +52,7 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | @@ -63,7 +52,7 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | ||
63 | 52 | ||
64 | private final AtomicInteger msgIdSeq = new AtomicInteger(0); | 53 | private final AtomicInteger msgIdSeq = new AtomicInteger(0); |
65 | 54 | ||
66 | - private final ConcurrentLinkedQueue<MqttMessage> msgQueue = new ConcurrentLinkedQueue<>(); | 55 | + private final ConcurrentLinkedQueue<TCPMessage> msgQueue = new ConcurrentLinkedQueue<>(); |
67 | 56 | ||
68 | @Getter | 57 | @Getter |
69 | private final Lock msgQueueProcessorLock = new ReentrantLock(); | 58 | private final Lock msgQueueProcessorLock = new ReentrantLock(); |
@@ -74,62 +63,36 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | @@ -74,62 +63,36 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | ||
74 | @Setter | 63 | @Setter |
75 | private boolean provisionOnly = false; | 64 | private boolean provisionOnly = false; |
76 | 65 | ||
77 | - private volatile TcpTopicFilter telemetryTopicFilter = MqttTopicFilterFactory.getDefaultTelemetryFilter(); | ||
78 | - private volatile TcpTopicFilter attributesTopicFilter = MqttTopicFilterFactory.getDefaultAttributesFilter(); | ||
79 | - private volatile TransportPayloadType payloadType = TransportPayloadType.JSON; | ||
80 | - private volatile Descriptors.Descriptor attributesDynamicMessageDescriptor; | ||
81 | - private volatile Descriptors.Descriptor telemetryDynamicMessageDescriptor; | ||
82 | - private volatile Descriptors.Descriptor rpcResponseDynamicMessageDescriptor; | ||
83 | - private volatile DynamicMessage.Builder rpcRequestDynamicMessageBuilder; | 66 | + // private volatile TcpTopicFilter telemetryTopicFilter = MqttTopicFilterFactory.getDefaultTelemetryFilter(); |
67 | +// private volatile TcpTopicFilter attributesTopicFilter = MqttTopicFilterFactory.getDefaultAttributesFilter(); | ||
68 | + @Getter | ||
69 | + private volatile TcpDataTypeEnum payloadType = TcpDataTypeEnum.HEX; | ||
70 | + @Getter | ||
71 | + private volatile byte[] pingText ; | ||
72 | + // private volatile Descriptors.Descriptor attributesDynamicMessageDescriptor; | ||
73 | +// private volatile Descriptors.Descriptor telemetryDynamicMessageDescriptor; | ||
74 | +// private volatile Descriptors.Descriptor rpcResponseDynamicMessageDescriptor; | ||
75 | +// private volatile DynamicMessage.Builder rpcRequestDynamicMessageBuilder; | ||
84 | private volatile TcpTransportAdaptor adaptor; | 76 | private volatile TcpTransportAdaptor adaptor; |
85 | - private volatile boolean jsonPayloadFormatCompatibilityEnabled; | ||
86 | - private volatile boolean useJsonPayloadFormatForDefaultDownlinkTopics; | ||
87 | 77 | ||
88 | - @Getter | ||
89 | - @Setter | ||
90 | - private TransportPayloadType provisionPayloadType = payloadType; | ||
91 | 78 | ||
92 | - public DeviceSessionCtx(UUID sessionId, ConcurrentMap<MqttTopicMatcher, Integer> mqttQoSMap, TcpTransportContext context) { | ||
93 | - super(sessionId, mqttQoSMap); | 79 | + public DeviceSessionCtx(UUID sessionId, TcpTransportContext context) { |
80 | + super(sessionId); | ||
94 | this.context = context; | 81 | this.context = context; |
95 | - this.adaptor = context.getJsonMqttAdaptor(); | 82 | + this.adaptor = context.getJsonTcpAdaptor(); |
96 | } | 83 | } |
97 | 84 | ||
98 | public int nextMsgId() { | 85 | public int nextMsgId() { |
99 | return msgIdSeq.incrementAndGet(); | 86 | return msgIdSeq.incrementAndGet(); |
100 | } | 87 | } |
101 | 88 | ||
102 | - public boolean isDeviceTelemetryTopic(String topicName) { | ||
103 | - return telemetryTopicFilter.filter(topicName); | ||
104 | - } | ||
105 | - | ||
106 | - public boolean isDeviceAttributesTopic(String topicName) { | ||
107 | - return attributesTopicFilter.filter(topicName); | ||
108 | - } | ||
109 | 89 | ||
110 | public TcpTransportAdaptor getPayloadAdaptor() { | 90 | public TcpTransportAdaptor getPayloadAdaptor() { |
111 | return adaptor; | 91 | return adaptor; |
112 | } | 92 | } |
113 | 93 | ||
114 | - public boolean isJsonPayloadType() { | ||
115 | - return payloadType.equals(TransportPayloadType.JSON); | ||
116 | - } | ||
117 | - | ||
118 | - public Descriptors.Descriptor getTelemetryDynamicMsgDescriptor() { | ||
119 | - return telemetryDynamicMessageDescriptor; | ||
120 | - } | ||
121 | 94 | ||
122 | - public Descriptors.Descriptor getAttributesDynamicMessageDescriptor() { | ||
123 | - return attributesDynamicMessageDescriptor; | ||
124 | - } | ||
125 | 95 | ||
126 | - public Descriptors.Descriptor getRpcResponseDynamicMessageDescriptor() { | ||
127 | - return rpcResponseDynamicMessageDescriptor; | ||
128 | - } | ||
129 | - | ||
130 | - public DynamicMessage.Builder getRpcRequestDynamicMessageBuilder() { | ||
131 | - return rpcRequestDynamicMessageBuilder; | ||
132 | - } | ||
133 | 96 | ||
134 | @Override | 97 | @Override |
135 | public void setDeviceProfile(DeviceProfile deviceProfile) { | 98 | public void setDeviceProfile(DeviceProfile deviceProfile) { |
@@ -145,76 +108,37 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | @@ -145,76 +108,37 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | ||
145 | 108 | ||
146 | private void updateDeviceSessionConfiguration(DeviceProfile deviceProfile) { | 109 | private void updateDeviceSessionConfiguration(DeviceProfile deviceProfile) { |
147 | DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); | 110 | DeviceProfileTransportConfiguration transportConfiguration = deviceProfile.getProfileData().getTransportConfiguration(); |
148 | - if (transportConfiguration.getType().equals(DeviceTransportType.MQTT) && | ||
149 | - transportConfiguration instanceof MqttDeviceProfileTransportConfiguration) { | ||
150 | - MqttDeviceProfileTransportConfiguration mqttConfig = (MqttDeviceProfileTransportConfiguration) transportConfiguration; | ||
151 | - TransportPayloadTypeConfiguration transportPayloadTypeConfiguration = mqttConfig.getTransportPayloadTypeConfiguration(); | ||
152 | - payloadType = transportPayloadTypeConfiguration.getTransportPayloadType(); | ||
153 | - telemetryTopicFilter = MqttTopicFilterFactory.toFilter(mqttConfig.getDeviceTelemetryTopic()); | ||
154 | - attributesTopicFilter = MqttTopicFilterFactory.toFilter(mqttConfig.getDeviceAttributesTopic()); | ||
155 | - if (TransportPayloadType.PROTOBUF.equals(payloadType)) { | ||
156 | - ProtoTransportPayloadConfiguration protoTransportPayloadConfig = (ProtoTransportPayloadConfiguration) transportPayloadTypeConfiguration; | ||
157 | - updateDynamicMessageDescriptors(protoTransportPayloadConfig); | ||
158 | - jsonPayloadFormatCompatibilityEnabled = protoTransportPayloadConfig.isEnableCompatibilityWithJsonPayloadFormat(); | ||
159 | - useJsonPayloadFormatForDefaultDownlinkTopics = jsonPayloadFormatCompatibilityEnabled && protoTransportPayloadConfig.isUseJsonPayloadFormatForDefaultDownlinkTopics(); | ||
160 | - } | 111 | + |
112 | + TcpDeviceProfileTransportConfiguration tcpConfiguration = (TcpDeviceProfileTransportConfiguration) transportConfiguration; | ||
113 | + payloadType = tcpConfiguration.getDataFormat(); | ||
114 | + if (TcpDataTypeEnum.ASCII.equals(payloadType)) { | ||
115 | + payloadType = TcpDataTypeEnum.ASCII; | ||
161 | } else { | 116 | } else { |
162 | - telemetryTopicFilter = MqttTopicFilterFactory.getDefaultTelemetryFilter(); | ||
163 | - attributesTopicFilter = MqttTopicFilterFactory.getDefaultAttributesFilter(); | ||
164 | - payloadType = TransportPayloadType.JSON; | 117 | + payloadType = TcpDataTypeEnum.HEX; |
165 | } | 118 | } |
166 | - updateAdaptor(); | ||
167 | - } | 119 | + this.pingText = ByteUtils.getBytes(tcpConfiguration.getPingText(),ByteUtils.UTF_8); |
168 | 120 | ||
169 | - private void updateDynamicMessageDescriptors(ProtoTransportPayloadConfiguration protoTransportPayloadConfig) { | ||
170 | - telemetryDynamicMessageDescriptor = protoTransportPayloadConfig.getTelemetryDynamicMessageDescriptor(protoTransportPayloadConfig.getDeviceTelemetryProtoSchema()); | ||
171 | - attributesDynamicMessageDescriptor = protoTransportPayloadConfig.getAttributesDynamicMessageDescriptor(protoTransportPayloadConfig.getDeviceAttributesProtoSchema()); | ||
172 | - rpcResponseDynamicMessageDescriptor = protoTransportPayloadConfig.getRpcResponseDynamicMessageDescriptor(protoTransportPayloadConfig.getDeviceRpcResponseProtoSchema()); | ||
173 | - rpcRequestDynamicMessageBuilder = protoTransportPayloadConfig.getRpcRequestDynamicMessageBuilder(protoTransportPayloadConfig.getDeviceRpcRequestProtoSchema()); | ||
174 | } | 121 | } |
175 | 122 | ||
176 | - public TcpTransportAdaptor getAdaptor(TopicType topicType) { | ||
177 | - switch (topicType) { | ||
178 | - case V2: | ||
179 | - return getDefaultAdaptor(); | ||
180 | - case V2_JSON: | ||
181 | - return context.getJsonMqttAdaptor(); | ||
182 | - case V2_PROTO: | ||
183 | - return context.getProtoMqttAdaptor(); | ||
184 | - default: | ||
185 | - return useJsonPayloadFormatForDefaultDownlinkTopics ? context.getJsonMqttAdaptor() : getDefaultAdaptor(); | ||
186 | - } | ||
187 | - } | ||
188 | 123 | ||
189 | - private TcpTransportAdaptor getDefaultAdaptor() { | ||
190 | - return isJsonPayloadType() ? context.getJsonMqttAdaptor() : context.getProtoMqttAdaptor(); | 124 | + public TcpTransportAdaptor getAdaptor() { |
125 | + return context.getJsonTcpAdaptor(); | ||
191 | } | 126 | } |
192 | 127 | ||
193 | - private void updateAdaptor() { | ||
194 | - if (isJsonPayloadType()) { | ||
195 | - adaptor = context.getJsonMqttAdaptor(); | ||
196 | - jsonPayloadFormatCompatibilityEnabled = false; | ||
197 | - useJsonPayloadFormatForDefaultDownlinkTopics = false; | ||
198 | - } else { | ||
199 | - if (jsonPayloadFormatCompatibilityEnabled) { | ||
200 | - adaptor = new BackwardCompatibilityAdaptor(context.getProtoMqttAdaptor(), context.getJsonMqttAdaptor()); | ||
201 | - } else { | ||
202 | - adaptor = context.getProtoMqttAdaptor(); | ||
203 | - } | ||
204 | - } | ||
205 | - } | ||
206 | 128 | ||
207 | - public void addToQueue(MqttMessage msg) { | 129 | + |
130 | + | ||
131 | + public void addToQueue(TCPMessage msg) { | ||
208 | msgQueueSize.incrementAndGet(); | 132 | msgQueueSize.incrementAndGet(); |
209 | ReferenceCountUtil.retain(msg); | 133 | ReferenceCountUtil.retain(msg); |
210 | msgQueue.add(msg); | 134 | msgQueue.add(msg); |
211 | } | 135 | } |
212 | 136 | ||
213 | - public void tryProcessQueuedMsgs(Consumer<MqttMessage> msgProcessor) { | 137 | + public void tryProcessQueuedMsgs(Consumer<TCPMessage> msgProcessor) { |
214 | while (!msgQueue.isEmpty()) { | 138 | while (!msgQueue.isEmpty()) { |
215 | if (msgQueueProcessorLock.tryLock()) { | 139 | if (msgQueueProcessorLock.tryLock()) { |
216 | try { | 140 | try { |
217 | - MqttMessage msg; | 141 | + TCPMessage msg; |
218 | while ((msg = msgQueue.poll()) != null) { | 142 | while ((msg = msgQueue.poll()) != null) { |
219 | try { | 143 | try { |
220 | msgQueueSize.decrementAndGet(); | 144 | msgQueueSize.decrementAndGet(); |
@@ -244,8 +168,5 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | @@ -244,8 +168,5 @@ public class DeviceSessionCtx extends MqttDeviceAwareSessionContext { | ||
244 | } | 168 | } |
245 | } | 169 | } |
246 | 170 | ||
247 | - public Collection<MqttMessage> getMsgQueueSnapshot(){ | ||
248 | - return Collections.unmodifiableCollection(msgQueue); | ||
249 | - } | ||
250 | 171 | ||
251 | } | 172 | } |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/session/GatewayDeviceSessionCtx.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp.session; | ||
17 | - | ||
18 | -import io.netty.channel.ChannelFuture; | ||
19 | -import io.netty.handler.codec.mqtt.MqttMessage; | ||
20 | -import lombok.extern.slf4j.Slf4j; | ||
21 | -import org.thingsboard.server.common.data.DeviceProfile; | ||
22 | -import org.thingsboard.server.common.data.id.DeviceId; | ||
23 | -import org.thingsboard.server.common.data.rpc.RpcStatus; | ||
24 | -import org.thingsboard.server.common.transport.SessionMsgListener; | ||
25 | -import org.thingsboard.server.common.transport.TransportService; | ||
26 | -import org.thingsboard.server.common.transport.TransportServiceCallback; | ||
27 | -import org.thingsboard.server.common.transport.auth.TransportDeviceInfo; | ||
28 | -import org.thingsboard.server.gen.transport.TransportProtos; | ||
29 | -import org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto; | ||
30 | - | ||
31 | -import java.util.UUID; | ||
32 | -import java.util.concurrent.ConcurrentMap; | ||
33 | - | ||
34 | -/** | ||
35 | - * Created by ashvayka on 19.01.17. | ||
36 | - */ | ||
37 | -@Slf4j | ||
38 | -public class GatewayDeviceSessionCtx extends MqttDeviceAwareSessionContext implements SessionMsgListener { | ||
39 | - | ||
40 | - private final GatewaySessionHandler parent; | ||
41 | - private final TransportService transportService; | ||
42 | - | ||
43 | - public GatewayDeviceSessionCtx(GatewaySessionHandler parent, TransportDeviceInfo deviceInfo, | ||
44 | - DeviceProfile deviceProfile, ConcurrentMap<MqttTopicMatcher, Integer> mqttQoSMap, | ||
45 | - TransportService transportService) { | ||
46 | - super(UUID.randomUUID(), mqttQoSMap); | ||
47 | - this.parent = parent; | ||
48 | - setSessionInfo(SessionInfoProto.newBuilder() | ||
49 | - .setNodeId(parent.getNodeId()) | ||
50 | - .setSessionIdMSB(sessionId.getMostSignificantBits()) | ||
51 | - .setSessionIdLSB(sessionId.getLeastSignificantBits()) | ||
52 | - .setDeviceIdMSB(deviceInfo.getDeviceId().getId().getMostSignificantBits()) | ||
53 | - .setDeviceIdLSB(deviceInfo.getDeviceId().getId().getLeastSignificantBits()) | ||
54 | - .setTenantIdMSB(deviceInfo.getTenantId().getId().getMostSignificantBits()) | ||
55 | - .setTenantIdLSB(deviceInfo.getTenantId().getId().getLeastSignificantBits()) | ||
56 | - .setCustomerIdMSB(deviceInfo.getCustomerId().getId().getMostSignificantBits()) | ||
57 | - .setCustomerIdLSB(deviceInfo.getCustomerId().getId().getLeastSignificantBits()) | ||
58 | - .setDeviceName(deviceInfo.getDeviceName()) | ||
59 | - .setDeviceType(deviceInfo.getDeviceType()) | ||
60 | - .setGwSessionIdMSB(parent.getSessionId().getMostSignificantBits()) | ||
61 | - .setGwSessionIdLSB(parent.getSessionId().getLeastSignificantBits()) | ||
62 | - .setDeviceProfileIdMSB(deviceInfo.getDeviceProfileId().getId().getMostSignificantBits()) | ||
63 | - .setDeviceProfileIdLSB(deviceInfo.getDeviceProfileId().getId().getLeastSignificantBits()) | ||
64 | - .build()); | ||
65 | - setDeviceInfo(deviceInfo); | ||
66 | - setConnected(true); | ||
67 | - setDeviceProfile(deviceProfile); | ||
68 | - this.transportService = transportService; | ||
69 | - } | ||
70 | - | ||
71 | - @Override | ||
72 | - public UUID getSessionId() { | ||
73 | - return sessionId; | ||
74 | - } | ||
75 | - | ||
76 | - @Override | ||
77 | - public int nextMsgId() { | ||
78 | - return parent.nextMsgId(); | ||
79 | - } | ||
80 | - | ||
81 | - @Override | ||
82 | - public void onGetAttributesResponse(TransportProtos.GetAttributeResponseMsg response) { | ||
83 | - try { | ||
84 | - parent.getPayloadAdaptor().convertToGatewayPublish(this, getDeviceInfo().getDeviceName(), response).ifPresent(parent::writeAndFlush); | ||
85 | - } catch (Exception e) { | ||
86 | - log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
87 | - } | ||
88 | - } | ||
89 | - | ||
90 | - @Override | ||
91 | - public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg notification) { | ||
92 | - log.trace("[{}] Received attributes update notification to device", sessionId); | ||
93 | - try { | ||
94 | - parent.getPayloadAdaptor().convertToGatewayPublish(this, getDeviceInfo().getDeviceName(), notification).ifPresent(parent::writeAndFlush); | ||
95 | - } catch (Exception e) { | ||
96 | - log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
97 | - } | ||
98 | - } | ||
99 | - | ||
100 | - @Override | ||
101 | - public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg request) { | ||
102 | - log.trace("[{}] Received RPC command to device", sessionId); | ||
103 | - try { | ||
104 | - parent.getPayloadAdaptor().convertToGatewayPublish(this, getDeviceInfo().getDeviceName(), request).ifPresent( | ||
105 | - payload -> { | ||
106 | - ChannelFuture channelFuture = parent.writeAndFlush(payload); | ||
107 | - if (request.getPersisted()) { | ||
108 | - channelFuture.addListener(result -> { | ||
109 | - if (result.cause() == null) { | ||
110 | - if (!isAckExpected(payload)) { | ||
111 | - transportService.process(getSessionInfo(), request, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); | ||
112 | - } else if (request.getPersisted()) { | ||
113 | - transportService.process(getSessionInfo(), request, RpcStatus.SENT, TransportServiceCallback.EMPTY); | ||
114 | - | ||
115 | - } | ||
116 | - } | ||
117 | - }); | ||
118 | - } | ||
119 | - } | ||
120 | - ); | ||
121 | - } catch (Exception e) { | ||
122 | - transportService.process(getSessionInfo(), | ||
123 | - TransportProtos.ToDeviceRpcResponseMsg.newBuilder() | ||
124 | - .setRequestId(request.getRequestId()).setError("Failed to convert device RPC command to MQTT msg").build(), TransportServiceCallback.EMPTY); | ||
125 | - log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); | ||
126 | - } | ||
127 | - } | ||
128 | - | ||
129 | - @Override | ||
130 | - public void onRemoteSessionCloseCommand(UUID sessionId, TransportProtos.SessionCloseNotificationProto sessionCloseNotification) { | ||
131 | - log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage()); | ||
132 | - parent.deregisterSession(getDeviceInfo().getDeviceName()); | ||
133 | - } | ||
134 | - | ||
135 | - @Override | ||
136 | - public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg toServerResponse) { | ||
137 | - // This feature is not supported in the TB IoT Gateway yet. | ||
138 | - } | ||
139 | - | ||
140 | - @Override | ||
141 | - public void onDeviceDeleted(DeviceId deviceId) { | ||
142 | - parent.onDeviceDeleted(this.getSessionInfo().getDeviceName()); | ||
143 | - } | ||
144 | - | ||
145 | - private boolean isAckExpected(MqttMessage message) { | ||
146 | - return message.fixedHeader().qosLevel().value() > 0; | ||
147 | - } | ||
148 | - | ||
149 | -} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/session/GatewaySessionHandler.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp.session; | ||
17 | - | ||
18 | - | ||
19 | -import com.google.common.util.concurrent.FutureCallback; | ||
20 | -import com.google.common.util.concurrent.Futures; | ||
21 | -import com.google.common.util.concurrent.ListenableFuture; | ||
22 | -import com.google.common.util.concurrent.SettableFuture; | ||
23 | -import com.google.gson.JsonArray; | ||
24 | -import com.google.gson.JsonElement; | ||
25 | -import com.google.gson.JsonNull; | ||
26 | -import com.google.gson.JsonObject; | ||
27 | -import com.google.gson.JsonSyntaxException; | ||
28 | -import com.google.protobuf.InvalidProtocolBufferException; | ||
29 | -import com.google.protobuf.ProtocolStringList; | ||
30 | -import io.netty.buffer.ByteBuf; | ||
31 | -import io.netty.channel.ChannelFuture; | ||
32 | -import io.netty.channel.ChannelHandlerContext; | ||
33 | -import io.netty.handler.codec.mqtt.MqttMessage; | ||
34 | -import io.netty.handler.codec.mqtt.MqttPublishMessage; | ||
35 | -import lombok.extern.slf4j.Slf4j; | ||
36 | -import org.springframework.util.CollectionUtils; | ||
37 | -import org.springframework.util.ConcurrentReferenceHashMap; | ||
38 | -import org.springframework.util.StringUtils; | ||
39 | -import org.thingsboard.server.common.data.id.DeviceId; | ||
40 | -import org.thingsboard.server.common.transport.TransportService; | ||
41 | -import org.thingsboard.server.common.transport.TransportServiceCallback; | ||
42 | -import org.thingsboard.server.common.transport.adaptor.AdaptorException; | ||
43 | -import org.thingsboard.server.common.transport.adaptor.JsonConverter; | ||
44 | -import org.thingsboard.server.common.transport.adaptor.ProtoConverter; | ||
45 | -import org.thingsboard.server.common.transport.auth.GetOrCreateDeviceFromGatewayResponse; | ||
46 | -import org.thingsboard.server.common.transport.auth.TransportDeviceInfo; | ||
47 | -import org.thingsboard.server.gen.transport.TransportApiProtos; | ||
48 | -import org.thingsboard.server.gen.transport.TransportProtos; | ||
49 | -import org.thingsboard.server.gen.transport.TransportProtos.GetOrCreateDeviceFromGatewayRequestMsg; | ||
50 | -import org.thingsboard.server.gen.transport.TransportProtos.SessionInfoProto; | ||
51 | -import org.thingsboard.server.transport.tcp.TcpTransportContext; | ||
52 | -import org.thingsboard.server.transport.tcp.TcpTransportHandler; | ||
53 | -import org.thingsboard.server.transport.tcp.adaptors.JsonTcpAdaptor; | ||
54 | -import org.thingsboard.server.transport.tcp.adaptors.TcpTransportAdaptor; | ||
55 | -import org.thingsboard.server.transport.tcp.adaptors.ProtoTcpAdaptor; | ||
56 | - | ||
57 | -import javax.annotation.Nullable; | ||
58 | -import java.util.Collections; | ||
59 | -import java.util.HashSet; | ||
60 | -import java.util.List; | ||
61 | -import java.util.Map; | ||
62 | -import java.util.Set; | ||
63 | -import java.util.UUID; | ||
64 | -import java.util.concurrent.ConcurrentHashMap; | ||
65 | -import java.util.concurrent.ConcurrentMap; | ||
66 | -import java.util.concurrent.locks.Lock; | ||
67 | -import java.util.concurrent.locks.ReentrantLock; | ||
68 | - | ||
69 | -import static org.springframework.util.ConcurrentReferenceHashMap.ReferenceType; | ||
70 | -import static org.thingsboard.server.common.transport.service.DefaultTransportService.SESSION_EVENT_MSG_CLOSED; | ||
71 | -import static org.thingsboard.server.common.transport.service.DefaultTransportService.SESSION_EVENT_MSG_OPEN; | ||
72 | -import static org.thingsboard.server.common.transport.service.DefaultTransportService.SUBSCRIBE_TO_ATTRIBUTE_UPDATES_ASYNC_MSG; | ||
73 | -import static org.thingsboard.server.common.transport.service.DefaultTransportService.SUBSCRIBE_TO_RPC_ASYNC_MSG; | ||
74 | - | ||
75 | -/** | ||
76 | - * Created by ashvayka on 19.01.17. | ||
77 | - */ | ||
78 | -@Slf4j | ||
79 | -public class GatewaySessionHandler { | ||
80 | - | ||
81 | - private static final String DEFAULT_DEVICE_TYPE = "default"; | ||
82 | - private static final String CAN_T_PARSE_VALUE = "Can't parse value: "; | ||
83 | - private static final String DEVICE_PROPERTY = "device"; | ||
84 | - | ||
85 | - private final TcpTransportContext context; | ||
86 | - private final TransportService transportService; | ||
87 | - private final TransportDeviceInfo gateway; | ||
88 | - private final UUID sessionId; | ||
89 | - private final ConcurrentMap<String, Lock> deviceCreationLockMap; | ||
90 | - private final ConcurrentMap<String, GatewayDeviceSessionCtx> devices; | ||
91 | - private final ConcurrentMap<String, ListenableFuture<GatewayDeviceSessionCtx>> deviceFutures; | ||
92 | - private final ConcurrentMap<MqttTopicMatcher, Integer> mqttQoSMap; | ||
93 | - private final ChannelHandlerContext channel; | ||
94 | - private final DeviceSessionCtx deviceSessionCtx; | ||
95 | - | ||
96 | - public GatewaySessionHandler(DeviceSessionCtx deviceSessionCtx, UUID sessionId) { | ||
97 | - this.context = deviceSessionCtx.getContext(); | ||
98 | - this.transportService = context.getTransportService(); | ||
99 | - this.deviceSessionCtx = deviceSessionCtx; | ||
100 | - this.gateway = deviceSessionCtx.getDeviceInfo(); | ||
101 | - this.sessionId = sessionId; | ||
102 | - this.devices = new ConcurrentHashMap<>(); | ||
103 | - this.deviceFutures = new ConcurrentHashMap<>(); | ||
104 | - this.deviceCreationLockMap = createWeakMap(); | ||
105 | - this.mqttQoSMap = deviceSessionCtx.getMqttQoSMap(); | ||
106 | - this.channel = deviceSessionCtx.getChannel(); | ||
107 | - } | ||
108 | - | ||
109 | - ConcurrentReferenceHashMap<String, Lock> createWeakMap() { | ||
110 | - return new ConcurrentReferenceHashMap<>(16, ReferenceType.WEAK); | ||
111 | - } | ||
112 | - | ||
113 | - public void onDeviceConnect(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
114 | - if (isJsonPayloadType()) { | ||
115 | - onDeviceConnectJson(mqttMsg); | ||
116 | - } else { | ||
117 | - onDeviceConnectProto(mqttMsg); | ||
118 | - } | ||
119 | - } | ||
120 | - | ||
121 | - public void onDeviceDisconnect(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
122 | - if (isJsonPayloadType()) { | ||
123 | - onDeviceDisconnectJson(mqttMsg); | ||
124 | - } else { | ||
125 | - onDeviceDisconnectProto(mqttMsg); | ||
126 | - } | ||
127 | - } | ||
128 | - | ||
129 | - public void onDeviceTelemetry(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
130 | - int msgId = getMsgId(mqttMsg); | ||
131 | - ByteBuf payload = mqttMsg.payload(); | ||
132 | - if (isJsonPayloadType()) { | ||
133 | - onDeviceTelemetryJson(msgId, payload); | ||
134 | - } else { | ||
135 | - onDeviceTelemetryProto(msgId, payload); | ||
136 | - } | ||
137 | - } | ||
138 | - | ||
139 | - public void onDeviceClaim(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
140 | - int msgId = getMsgId(mqttMsg); | ||
141 | - ByteBuf payload = mqttMsg.payload(); | ||
142 | - if (isJsonPayloadType()) { | ||
143 | - onDeviceClaimJson(msgId, payload); | ||
144 | - } else { | ||
145 | - onDeviceClaimProto(msgId, payload); | ||
146 | - } | ||
147 | - } | ||
148 | - | ||
149 | - public void onDeviceAttributes(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
150 | - int msgId = getMsgId(mqttMsg); | ||
151 | - ByteBuf payload = mqttMsg.payload(); | ||
152 | - if (isJsonPayloadType()) { | ||
153 | - onDeviceAttributesJson(msgId, payload); | ||
154 | - } else { | ||
155 | - onDeviceAttributesProto(msgId, payload); | ||
156 | - } | ||
157 | - } | ||
158 | - | ||
159 | - public void onDeviceAttributesRequest(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
160 | - if (isJsonPayloadType()) { | ||
161 | - onDeviceAttributesRequestJson(mqttMsg); | ||
162 | - } else { | ||
163 | - onDeviceAttributesRequestProto(mqttMsg); | ||
164 | - } | ||
165 | - } | ||
166 | - | ||
167 | - public void onDeviceRpcResponse(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
168 | - int msgId = getMsgId(mqttMsg); | ||
169 | - ByteBuf payload = mqttMsg.payload(); | ||
170 | - if (isJsonPayloadType()) { | ||
171 | - onDeviceRpcResponseJson(msgId, payload); | ||
172 | - } else { | ||
173 | - onDeviceRpcResponseProto(msgId, payload); | ||
174 | - } | ||
175 | - } | ||
176 | - | ||
177 | - public void onGatewayDisconnect() { | ||
178 | - devices.forEach(this::deregisterSession); | ||
179 | - } | ||
180 | - | ||
181 | - public void onDeviceDeleted(String deviceName) { | ||
182 | - deregisterSession(deviceName); | ||
183 | - } | ||
184 | - | ||
185 | - public String getNodeId() { | ||
186 | - return context.getNodeId(); | ||
187 | - } | ||
188 | - | ||
189 | - public UUID getSessionId() { | ||
190 | - return sessionId; | ||
191 | - } | ||
192 | - | ||
193 | - public TcpTransportAdaptor getPayloadAdaptor() { | ||
194 | - return deviceSessionCtx.getPayloadAdaptor(); | ||
195 | - } | ||
196 | - | ||
197 | - void deregisterSession(String deviceName) { | ||
198 | - GatewayDeviceSessionCtx deviceSessionCtx = devices.remove(deviceName); | ||
199 | - if (deviceSessionCtx != null) { | ||
200 | - deregisterSession(deviceName, deviceSessionCtx); | ||
201 | - } else { | ||
202 | - log.debug("[{}] Device [{}] was already removed from the gateway session", sessionId, deviceName); | ||
203 | - } | ||
204 | - } | ||
205 | - | ||
206 | - ChannelFuture writeAndFlush(MqttMessage mqttMessage) { | ||
207 | - return channel.writeAndFlush(mqttMessage); | ||
208 | - } | ||
209 | - | ||
210 | - int nextMsgId() { | ||
211 | - return deviceSessionCtx.nextMsgId(); | ||
212 | - } | ||
213 | - | ||
214 | - private boolean isJsonPayloadType() { | ||
215 | - return deviceSessionCtx.isJsonPayloadType(); | ||
216 | - } | ||
217 | - | ||
218 | - private void processOnConnect(MqttPublishMessage msg, String deviceName, String deviceType) { | ||
219 | - log.trace("[{}] onDeviceConnect: {}", sessionId, deviceName); | ||
220 | - Futures.addCallback(onDeviceConnect(deviceName, deviceType), new FutureCallback<GatewayDeviceSessionCtx>() { | ||
221 | - @Override | ||
222 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx result) { | ||
223 | - ack(msg); | ||
224 | - log.trace("[{}] onDeviceConnectOk: {}", sessionId, deviceName); | ||
225 | - } | ||
226 | - | ||
227 | - @Override | ||
228 | - public void onFailure(Throwable t) { | ||
229 | - log.warn("[{}] Failed to process device connect command: {}", sessionId, deviceName, t); | ||
230 | - | ||
231 | - } | ||
232 | - }, context.getExecutor()); | ||
233 | - } | ||
234 | - | ||
235 | - private ListenableFuture<GatewayDeviceSessionCtx> onDeviceConnect(String deviceName, String deviceType) { | ||
236 | - GatewayDeviceSessionCtx result = devices.get(deviceName); | ||
237 | - if (result == null) { | ||
238 | - Lock deviceCreationLock = deviceCreationLockMap.computeIfAbsent(deviceName, s -> new ReentrantLock()); | ||
239 | - deviceCreationLock.lock(); | ||
240 | - try { | ||
241 | - result = devices.get(deviceName); | ||
242 | - if (result == null) { | ||
243 | - return getDeviceCreationFuture(deviceName, deviceType); | ||
244 | - } else { | ||
245 | - return Futures.immediateFuture(result); | ||
246 | - } | ||
247 | - } finally { | ||
248 | - deviceCreationLock.unlock(); | ||
249 | - } | ||
250 | - } else { | ||
251 | - return Futures.immediateFuture(result); | ||
252 | - } | ||
253 | - } | ||
254 | - | ||
255 | - private ListenableFuture<GatewayDeviceSessionCtx> getDeviceCreationFuture(String deviceName, String deviceType) { | ||
256 | - final SettableFuture<GatewayDeviceSessionCtx> futureToSet = SettableFuture.create(); | ||
257 | - ListenableFuture<GatewayDeviceSessionCtx> future = deviceFutures.putIfAbsent(deviceName, futureToSet); | ||
258 | - if (future != null) { | ||
259 | - return future; | ||
260 | - } | ||
261 | - try { | ||
262 | - transportService.process(GetOrCreateDeviceFromGatewayRequestMsg.newBuilder() | ||
263 | - .setDeviceName(deviceName) | ||
264 | - .setDeviceType(deviceType) | ||
265 | - .setGatewayIdMSB(gateway.getDeviceId().getId().getMostSignificantBits()) | ||
266 | - .setGatewayIdLSB(gateway.getDeviceId().getId().getLeastSignificantBits()).build(), | ||
267 | - new TransportServiceCallback<GetOrCreateDeviceFromGatewayResponse>() { | ||
268 | - @Override | ||
269 | - public void onSuccess(GetOrCreateDeviceFromGatewayResponse msg) { | ||
270 | - GatewayDeviceSessionCtx deviceSessionCtx = new GatewayDeviceSessionCtx(GatewaySessionHandler.this, msg.getDeviceInfo(), msg.getDeviceProfile(), mqttQoSMap, transportService); | ||
271 | - if (devices.putIfAbsent(deviceName, deviceSessionCtx) == null) { | ||
272 | - log.trace("[{}] First got or created device [{}], type [{}] for the gateway session", sessionId, deviceName, deviceType); | ||
273 | - SessionInfoProto deviceSessionInfo = deviceSessionCtx.getSessionInfo(); | ||
274 | - transportService.registerAsyncSession(deviceSessionInfo, deviceSessionCtx); | ||
275 | - transportService.process(TransportProtos.TransportToDeviceActorMsg.newBuilder() | ||
276 | - .setSessionInfo(deviceSessionInfo) | ||
277 | - .setSessionEvent(SESSION_EVENT_MSG_OPEN) | ||
278 | - .setSubscribeToAttributes(SUBSCRIBE_TO_ATTRIBUTE_UPDATES_ASYNC_MSG) | ||
279 | - .setSubscribeToRPC(SUBSCRIBE_TO_RPC_ASYNC_MSG) | ||
280 | - .build(), null); | ||
281 | - } | ||
282 | - futureToSet.set(devices.get(deviceName)); | ||
283 | - deviceFutures.remove(deviceName); | ||
284 | - } | ||
285 | - | ||
286 | - @Override | ||
287 | - public void onError(Throwable e) { | ||
288 | - log.warn("[{}] Failed to process device connect command: {}", sessionId, deviceName, e); | ||
289 | - futureToSet.setException(e); | ||
290 | - deviceFutures.remove(deviceName); | ||
291 | - } | ||
292 | - }); | ||
293 | - return futureToSet; | ||
294 | - } catch (Throwable e) { | ||
295 | - deviceFutures.remove(deviceName); | ||
296 | - throw e; | ||
297 | - } | ||
298 | - } | ||
299 | - | ||
300 | - private int getMsgId(MqttPublishMessage mqttMsg) { | ||
301 | - return mqttMsg.variableHeader().packetId(); | ||
302 | - } | ||
303 | - | ||
304 | - private void onDeviceConnectJson(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
305 | - JsonElement json = getJson(mqttMsg); | ||
306 | - String deviceName = checkDeviceName(getDeviceName(json)); | ||
307 | - String deviceType = getDeviceType(json); | ||
308 | - processOnConnect(mqttMsg, deviceName, deviceType); | ||
309 | - } | ||
310 | - | ||
311 | - private void onDeviceConnectProto(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
312 | - try { | ||
313 | - TransportApiProtos.ConnectMsg connectProto = TransportApiProtos.ConnectMsg.parseFrom(getBytes(mqttMsg.payload())); | ||
314 | - String deviceName = checkDeviceName(connectProto.getDeviceName()); | ||
315 | - String deviceType = StringUtils.isEmpty(connectProto.getDeviceType()) ? DEFAULT_DEVICE_TYPE : connectProto.getDeviceType(); | ||
316 | - processOnConnect(mqttMsg, deviceName, deviceType); | ||
317 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
318 | - throw new AdaptorException(e); | ||
319 | - } | ||
320 | - } | ||
321 | - | ||
322 | - private void onDeviceDisconnectJson(MqttPublishMessage msg) throws AdaptorException { | ||
323 | - String deviceName = checkDeviceName(getDeviceName(getJson(msg))); | ||
324 | - processOnDisconnect(msg, deviceName); | ||
325 | - } | ||
326 | - | ||
327 | - private void onDeviceDisconnectProto(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
328 | - try { | ||
329 | - TransportApiProtos.DisconnectMsg connectProto = TransportApiProtos.DisconnectMsg.parseFrom(getBytes(mqttMsg.payload())); | ||
330 | - String deviceName = checkDeviceName(connectProto.getDeviceName()); | ||
331 | - processOnDisconnect(mqttMsg, deviceName); | ||
332 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
333 | - throw new AdaptorException(e); | ||
334 | - } | ||
335 | - } | ||
336 | - | ||
337 | - private void processOnDisconnect(MqttPublishMessage msg, String deviceName) { | ||
338 | - deregisterSession(deviceName); | ||
339 | - ack(msg); | ||
340 | - } | ||
341 | - | ||
342 | - private void onDeviceTelemetryJson(int msgId, ByteBuf payload) throws AdaptorException { | ||
343 | - JsonElement json = JsonTcpAdaptor.validateJsonPayload(sessionId, payload); | ||
344 | - if (json.isJsonObject()) { | ||
345 | - JsonObject jsonObj = json.getAsJsonObject(); | ||
346 | - for (Map.Entry<String, JsonElement> deviceEntry : jsonObj.entrySet()) { | ||
347 | - String deviceName = deviceEntry.getKey(); | ||
348 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
349 | - new FutureCallback<>() { | ||
350 | - @Override | ||
351 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
352 | - if (!deviceEntry.getValue().isJsonArray()) { | ||
353 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
354 | - } | ||
355 | - try { | ||
356 | - TransportProtos.PostTelemetryMsg postTelemetryMsg = JsonConverter.convertToTelemetryProto(deviceEntry.getValue().getAsJsonArray()); | ||
357 | - processPostTelemetryMsg(deviceCtx, postTelemetryMsg, deviceName, msgId); | ||
358 | - } catch (Throwable e) { | ||
359 | - log.warn("[{}][{}] Failed to convert telemetry: {}", gateway.getDeviceId(), deviceName, deviceEntry.getValue(), e); | ||
360 | - channel.close(); | ||
361 | - } | ||
362 | - } | ||
363 | - | ||
364 | - @Override | ||
365 | - public void onFailure(Throwable t) { | ||
366 | - log.debug("[{}] Failed to process device telemetry command: {}", sessionId, deviceName, t); | ||
367 | - } | ||
368 | - }, context.getExecutor()); | ||
369 | - } | ||
370 | - } else { | ||
371 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
372 | - } | ||
373 | - } | ||
374 | - | ||
375 | - private void onDeviceTelemetryProto(int msgId, ByteBuf payload) throws AdaptorException { | ||
376 | - try { | ||
377 | - TransportApiProtos.GatewayTelemetryMsg telemetryMsgProto = TransportApiProtos.GatewayTelemetryMsg.parseFrom(getBytes(payload)); | ||
378 | - List<TransportApiProtos.TelemetryMsg> deviceMsgList = telemetryMsgProto.getMsgList(); | ||
379 | - if (!CollectionUtils.isEmpty(deviceMsgList)) { | ||
380 | - deviceMsgList.forEach(telemetryMsg -> { | ||
381 | - String deviceName = checkDeviceName(telemetryMsg.getDeviceName()); | ||
382 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
383 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
384 | - @Override | ||
385 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
386 | - TransportProtos.PostTelemetryMsg msg = telemetryMsg.getMsg(); | ||
387 | - try { | ||
388 | - TransportProtos.PostTelemetryMsg postTelemetryMsg = ProtoConverter.validatePostTelemetryMsg(msg.toByteArray()); | ||
389 | - processPostTelemetryMsg(deviceCtx, postTelemetryMsg, deviceName, msgId); | ||
390 | - } catch (Throwable e) { | ||
391 | - log.warn("[{}][{}] Failed to convert telemetry: {}", gateway.getDeviceId(), deviceName, msg, e); | ||
392 | - channel.close(); | ||
393 | - } | ||
394 | - } | ||
395 | - | ||
396 | - @Override | ||
397 | - public void onFailure(Throwable t) { | ||
398 | - log.debug("[{}] Failed to process device telemetry command: {}", sessionId, deviceName, t); | ||
399 | - } | ||
400 | - }, context.getExecutor()); | ||
401 | - }); | ||
402 | - } else { | ||
403 | - log.debug("[{}] Devices telemetry messages is empty for: [{}]", sessionId, gateway.getDeviceId()); | ||
404 | - throw new IllegalArgumentException("[" + sessionId + "] Devices telemetry messages is empty for [" + gateway.getDeviceId() + "]"); | ||
405 | - } | ||
406 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
407 | - throw new AdaptorException(e); | ||
408 | - } | ||
409 | - } | ||
410 | - | ||
411 | - private void processPostTelemetryMsg(GatewayDeviceSessionCtx deviceCtx, TransportProtos.PostTelemetryMsg postTelemetryMsg, String deviceName, int msgId) { | ||
412 | - transportService.process(deviceCtx.getSessionInfo(), postTelemetryMsg, getPubAckCallback(channel, deviceName, msgId, postTelemetryMsg)); | ||
413 | - } | ||
414 | - | ||
415 | - private void onDeviceClaimJson(int msgId, ByteBuf payload) throws AdaptorException { | ||
416 | - JsonElement json = JsonTcpAdaptor.validateJsonPayload(sessionId, payload); | ||
417 | - if (json.isJsonObject()) { | ||
418 | - JsonObject jsonObj = json.getAsJsonObject(); | ||
419 | - for (Map.Entry<String, JsonElement> deviceEntry : jsonObj.entrySet()) { | ||
420 | - String deviceName = deviceEntry.getKey(); | ||
421 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
422 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
423 | - @Override | ||
424 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
425 | - if (!deviceEntry.getValue().isJsonObject()) { | ||
426 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
427 | - } | ||
428 | - try { | ||
429 | - DeviceId deviceId = deviceCtx.getDeviceId(); | ||
430 | - TransportProtos.ClaimDeviceMsg claimDeviceMsg = JsonConverter.convertToClaimDeviceProto(deviceId, deviceEntry.getValue()); | ||
431 | - processClaimDeviceMsg(deviceCtx, claimDeviceMsg, deviceName, msgId); | ||
432 | - } catch (Throwable e) { | ||
433 | - log.warn("[{}][{}] Failed to convert claim message: {}", gateway.getDeviceId(), deviceName, deviceEntry.getValue(), e); | ||
434 | - } | ||
435 | - } | ||
436 | - | ||
437 | - @Override | ||
438 | - public void onFailure(Throwable t) { | ||
439 | - log.debug("[{}] Failed to process device claiming command: {}", sessionId, deviceName, t); | ||
440 | - } | ||
441 | - }, context.getExecutor()); | ||
442 | - } | ||
443 | - } else { | ||
444 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
445 | - } | ||
446 | - } | ||
447 | - | ||
448 | - private void onDeviceClaimProto(int msgId, ByteBuf payload) throws AdaptorException { | ||
449 | - try { | ||
450 | - TransportApiProtos.GatewayClaimMsg claimMsgProto = TransportApiProtos.GatewayClaimMsg.parseFrom(getBytes(payload)); | ||
451 | - List<TransportApiProtos.ClaimDeviceMsg> claimMsgList = claimMsgProto.getMsgList(); | ||
452 | - if (!CollectionUtils.isEmpty(claimMsgList)) { | ||
453 | - claimMsgList.forEach(claimDeviceMsg -> { | ||
454 | - String deviceName = checkDeviceName(claimDeviceMsg.getDeviceName()); | ||
455 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
456 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
457 | - @Override | ||
458 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
459 | - TransportApiProtos.ClaimDevice claimRequest = claimDeviceMsg.getClaimRequest(); | ||
460 | - if (claimRequest == null) { | ||
461 | - throw new IllegalArgumentException("Claim request for device: " + deviceName + " is null!"); | ||
462 | - } | ||
463 | - try { | ||
464 | - DeviceId deviceId = deviceCtx.getDeviceId(); | ||
465 | - TransportProtos.ClaimDeviceMsg claimDeviceMsg = ProtoConverter.convertToClaimDeviceProto(deviceId, claimRequest.toByteArray()); | ||
466 | - processClaimDeviceMsg(deviceCtx, claimDeviceMsg, deviceName, msgId); | ||
467 | - } catch (Throwable e) { | ||
468 | - log.warn("[{}][{}] Failed to convert claim message: {}", gateway.getDeviceId(), deviceName, claimRequest, e); | ||
469 | - } | ||
470 | - } | ||
471 | - | ||
472 | - @Override | ||
473 | - public void onFailure(Throwable t) { | ||
474 | - log.debug("[{}] Failed to process device claiming command: {}", sessionId, deviceName, t); | ||
475 | - } | ||
476 | - }, context.getExecutor()); | ||
477 | - }); | ||
478 | - } else { | ||
479 | - log.debug("[{}] Devices claim messages is empty for: [{}]", sessionId, gateway.getDeviceId()); | ||
480 | - throw new IllegalArgumentException("[" + sessionId + "] Devices claim messages is empty for [" + gateway.getDeviceId() + "]"); | ||
481 | - } | ||
482 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
483 | - throw new AdaptorException(e); | ||
484 | - } | ||
485 | - } | ||
486 | - | ||
487 | - private void processClaimDeviceMsg(GatewayDeviceSessionCtx deviceCtx, TransportProtos.ClaimDeviceMsg claimDeviceMsg, String deviceName, int msgId) { | ||
488 | - transportService.process(deviceCtx.getSessionInfo(), claimDeviceMsg, getPubAckCallback(channel, deviceName, msgId, claimDeviceMsg)); | ||
489 | - } | ||
490 | - | ||
491 | - private void onDeviceAttributesJson(int msgId, ByteBuf payload) throws AdaptorException { | ||
492 | - JsonElement json = JsonTcpAdaptor.validateJsonPayload(sessionId, payload); | ||
493 | - if (json.isJsonObject()) { | ||
494 | - JsonObject jsonObj = json.getAsJsonObject(); | ||
495 | - for (Map.Entry<String, JsonElement> deviceEntry : jsonObj.entrySet()) { | ||
496 | - String deviceName = deviceEntry.getKey(); | ||
497 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
498 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
499 | - @Override | ||
500 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
501 | - if (!deviceEntry.getValue().isJsonObject()) { | ||
502 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
503 | - } | ||
504 | - TransportProtos.PostAttributeMsg postAttributeMsg = JsonConverter.convertToAttributesProto(deviceEntry.getValue().getAsJsonObject()); | ||
505 | - processPostAttributesMsg(deviceCtx, postAttributeMsg, deviceName, msgId); | ||
506 | - } | ||
507 | - | ||
508 | - @Override | ||
509 | - public void onFailure(Throwable t) { | ||
510 | - log.debug("[{}] Failed to process device attributes command: {}", sessionId, deviceName, t); | ||
511 | - } | ||
512 | - }, context.getExecutor()); | ||
513 | - } | ||
514 | - } else { | ||
515 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
516 | - } | ||
517 | - } | ||
518 | - | ||
519 | - private void onDeviceAttributesProto(int msgId, ByteBuf payload) throws AdaptorException { | ||
520 | - try { | ||
521 | - TransportApiProtos.GatewayAttributesMsg attributesMsgProto = TransportApiProtos.GatewayAttributesMsg.parseFrom(getBytes(payload)); | ||
522 | - List<TransportApiProtos.AttributesMsg> attributesMsgList = attributesMsgProto.getMsgList(); | ||
523 | - if (!CollectionUtils.isEmpty(attributesMsgList)) { | ||
524 | - attributesMsgList.forEach(attributesMsg -> { | ||
525 | - String deviceName = checkDeviceName(attributesMsg.getDeviceName()); | ||
526 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
527 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
528 | - @Override | ||
529 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
530 | - TransportProtos.PostAttributeMsg kvListProto = attributesMsg.getMsg(); | ||
531 | - if (kvListProto == null) { | ||
532 | - throw new IllegalArgumentException("Attributes List for device: " + deviceName + " is empty!"); | ||
533 | - } | ||
534 | - try { | ||
535 | - TransportProtos.PostAttributeMsg postAttributeMsg = ProtoConverter.validatePostAttributeMsg(kvListProto.toByteArray()); | ||
536 | - processPostAttributesMsg(deviceCtx, postAttributeMsg, deviceName, msgId); | ||
537 | - } catch (Throwable e) { | ||
538 | - log.warn("[{}][{}] Failed to process device attributes command: {}", gateway.getDeviceId(), deviceName, kvListProto, e); | ||
539 | - } | ||
540 | - } | ||
541 | - | ||
542 | - @Override | ||
543 | - public void onFailure(Throwable t) { | ||
544 | - log.debug("[{}] Failed to process device attributes command: {}", sessionId, deviceName, t); | ||
545 | - } | ||
546 | - }, context.getExecutor()); | ||
547 | - }); | ||
548 | - } else { | ||
549 | - log.debug("[{}] Devices attributes keys list is empty for: [{}]", sessionId, gateway.getDeviceId()); | ||
550 | - throw new IllegalArgumentException("[" + sessionId + "] Devices attributes keys list is empty for [" + gateway.getDeviceId() + "]"); | ||
551 | - } | ||
552 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
553 | - throw new AdaptorException(e); | ||
554 | - } | ||
555 | - } | ||
556 | - | ||
557 | - private void processPostAttributesMsg(GatewayDeviceSessionCtx deviceCtx, TransportProtos.PostAttributeMsg postAttributeMsg, String deviceName, int msgId) { | ||
558 | - transportService.process(deviceCtx.getSessionInfo(), postAttributeMsg, getPubAckCallback(channel, deviceName, msgId, postAttributeMsg)); | ||
559 | - } | ||
560 | - | ||
561 | - private void onDeviceAttributesRequestJson(MqttPublishMessage msg) throws AdaptorException { | ||
562 | - JsonElement json = JsonTcpAdaptor.validateJsonPayload(sessionId, msg.payload()); | ||
563 | - if (json.isJsonObject()) { | ||
564 | - JsonObject jsonObj = json.getAsJsonObject(); | ||
565 | - int requestId = jsonObj.get("id").getAsInt(); | ||
566 | - String deviceName = jsonObj.get(DEVICE_PROPERTY).getAsString(); | ||
567 | - boolean clientScope = jsonObj.get("client").getAsBoolean(); | ||
568 | - Set<String> keys; | ||
569 | - if (jsonObj.has("key")) { | ||
570 | - keys = Collections.singleton(jsonObj.get("key").getAsString()); | ||
571 | - } else { | ||
572 | - JsonArray keysArray = jsonObj.get("keys").getAsJsonArray(); | ||
573 | - keys = new HashSet<>(); | ||
574 | - for (JsonElement keyObj : keysArray) { | ||
575 | - keys.add(keyObj.getAsString()); | ||
576 | - } | ||
577 | - } | ||
578 | - TransportProtos.GetAttributeRequestMsg requestMsg = toGetAttributeRequestMsg(requestId, clientScope, keys); | ||
579 | - processGetAttributeRequestMessage(msg, deviceName, requestMsg); | ||
580 | - } else { | ||
581 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
582 | - } | ||
583 | - } | ||
584 | - | ||
585 | - private void onDeviceAttributesRequestProto(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
586 | - try { | ||
587 | - TransportApiProtos.GatewayAttributesRequestMsg gatewayAttributesRequestMsg = TransportApiProtos.GatewayAttributesRequestMsg.parseFrom(getBytes(mqttMsg.payload())); | ||
588 | - String deviceName = checkDeviceName(gatewayAttributesRequestMsg.getDeviceName()); | ||
589 | - int requestId = gatewayAttributesRequestMsg.getId(); | ||
590 | - boolean clientScope = gatewayAttributesRequestMsg.getClient(); | ||
591 | - ProtocolStringList keysList = gatewayAttributesRequestMsg.getKeysList(); | ||
592 | - Set<String> keys = new HashSet<>(keysList); | ||
593 | - TransportProtos.GetAttributeRequestMsg requestMsg = toGetAttributeRequestMsg(requestId, clientScope, keys); | ||
594 | - processGetAttributeRequestMessage(mqttMsg, deviceName, requestMsg); | ||
595 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
596 | - throw new AdaptorException(e); | ||
597 | - } | ||
598 | - } | ||
599 | - | ||
600 | - private void onDeviceRpcResponseJson(int msgId, ByteBuf payload) throws AdaptorException { | ||
601 | - JsonElement json = JsonTcpAdaptor.validateJsonPayload(sessionId, payload); | ||
602 | - if (json.isJsonObject()) { | ||
603 | - JsonObject jsonObj = json.getAsJsonObject(); | ||
604 | - String deviceName = jsonObj.get(DEVICE_PROPERTY).getAsString(); | ||
605 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
606 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
607 | - @Override | ||
608 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
609 | - Integer requestId = jsonObj.get("id").getAsInt(); | ||
610 | - String data = jsonObj.get("data").toString(); | ||
611 | - TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = TransportProtos.ToDeviceRpcResponseMsg.newBuilder() | ||
612 | - .setRequestId(requestId).setPayload(data).build(); | ||
613 | - processRpcResponseMsg(deviceCtx, rpcResponseMsg, deviceName, msgId); | ||
614 | - } | ||
615 | - | ||
616 | - @Override | ||
617 | - public void onFailure(Throwable t) { | ||
618 | - log.debug("[{}] Failed to process device Rpc response command: {}", sessionId, deviceName, t); | ||
619 | - } | ||
620 | - }, context.getExecutor()); | ||
621 | - } else { | ||
622 | - throw new JsonSyntaxException(CAN_T_PARSE_VALUE + json); | ||
623 | - } | ||
624 | - } | ||
625 | - | ||
626 | - private void onDeviceRpcResponseProto(int msgId, ByteBuf payload) throws AdaptorException { | ||
627 | - try { | ||
628 | - TransportApiProtos.GatewayRpcResponseMsg gatewayRpcResponseMsg = TransportApiProtos.GatewayRpcResponseMsg.parseFrom(getBytes(payload)); | ||
629 | - String deviceName = checkDeviceName(gatewayRpcResponseMsg.getDeviceName()); | ||
630 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
631 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
632 | - @Override | ||
633 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
634 | - Integer requestId = gatewayRpcResponseMsg.getId(); | ||
635 | - String data = gatewayRpcResponseMsg.getData(); | ||
636 | - TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg = TransportProtos.ToDeviceRpcResponseMsg.newBuilder() | ||
637 | - .setRequestId(requestId).setPayload(data).build(); | ||
638 | - processRpcResponseMsg(deviceCtx, rpcResponseMsg, deviceName, msgId); | ||
639 | - } | ||
640 | - | ||
641 | - @Override | ||
642 | - public void onFailure(Throwable t) { | ||
643 | - log.debug("[{}] Failed to process device Rpc response command: {}", sessionId, deviceName, t); | ||
644 | - } | ||
645 | - }, context.getExecutor()); | ||
646 | - } catch (RuntimeException | InvalidProtocolBufferException e) { | ||
647 | - throw new AdaptorException(e); | ||
648 | - } | ||
649 | - } | ||
650 | - | ||
651 | - private void processRpcResponseMsg(GatewayDeviceSessionCtx deviceCtx, TransportProtos.ToDeviceRpcResponseMsg rpcResponseMsg, String deviceName, int msgId) { | ||
652 | - transportService.process(deviceCtx.getSessionInfo(), rpcResponseMsg, getPubAckCallback(channel, deviceName, msgId, rpcResponseMsg)); | ||
653 | - } | ||
654 | - | ||
655 | - private void processGetAttributeRequestMessage(MqttPublishMessage mqttMsg, String deviceName, TransportProtos.GetAttributeRequestMsg requestMsg) { | ||
656 | - int msgId = getMsgId(mqttMsg); | ||
657 | - Futures.addCallback(checkDeviceConnected(deviceName), | ||
658 | - new FutureCallback<GatewayDeviceSessionCtx>() { | ||
659 | - @Override | ||
660 | - public void onSuccess(@Nullable GatewayDeviceSessionCtx deviceCtx) { | ||
661 | - transportService.process(deviceCtx.getSessionInfo(), requestMsg, getPubAckCallback(channel, deviceName, msgId, requestMsg)); | ||
662 | - } | ||
663 | - | ||
664 | - @Override | ||
665 | - public void onFailure(Throwable t) { | ||
666 | - ack(mqttMsg); | ||
667 | - log.debug("[{}] Failed to process device attributes request command: {}", sessionId, deviceName, t); | ||
668 | - } | ||
669 | - }, context.getExecutor()); | ||
670 | - } | ||
671 | - | ||
672 | - private TransportProtos.GetAttributeRequestMsg toGetAttributeRequestMsg(int requestId, boolean clientScope, Set<String> keys) { | ||
673 | - TransportProtos.GetAttributeRequestMsg.Builder result = TransportProtos.GetAttributeRequestMsg.newBuilder(); | ||
674 | - result.setRequestId(requestId); | ||
675 | - | ||
676 | - if (clientScope) { | ||
677 | - result.addAllClientAttributeNames(keys); | ||
678 | - } else { | ||
679 | - result.addAllSharedAttributeNames(keys); | ||
680 | - } | ||
681 | - return result.build(); | ||
682 | - } | ||
683 | - | ||
684 | - private ListenableFuture<GatewayDeviceSessionCtx> checkDeviceConnected(String deviceName) { | ||
685 | - GatewayDeviceSessionCtx ctx = devices.get(deviceName); | ||
686 | - if (ctx == null) { | ||
687 | - log.debug("[{}] Missing device [{}] for the gateway session", sessionId, deviceName); | ||
688 | - return onDeviceConnect(deviceName, DEFAULT_DEVICE_TYPE); | ||
689 | - } else { | ||
690 | - return Futures.immediateFuture(ctx); | ||
691 | - } | ||
692 | - } | ||
693 | - | ||
694 | - private String checkDeviceName(String deviceName) { | ||
695 | - if (StringUtils.isEmpty(deviceName)) { | ||
696 | - throw new RuntimeException("Device name is empty!"); | ||
697 | - } else { | ||
698 | - return deviceName; | ||
699 | - } | ||
700 | - } | ||
701 | - | ||
702 | - private String getDeviceName(JsonElement json) { | ||
703 | - return json.getAsJsonObject().get(DEVICE_PROPERTY).getAsString(); | ||
704 | - } | ||
705 | - | ||
706 | - private String getDeviceType(JsonElement json) { | ||
707 | - JsonElement type = json.getAsJsonObject().get("type"); | ||
708 | - return type == null || type instanceof JsonNull ? DEFAULT_DEVICE_TYPE : type.getAsString(); | ||
709 | - } | ||
710 | - | ||
711 | - private JsonElement getJson(MqttPublishMessage mqttMsg) throws AdaptorException { | ||
712 | - return JsonTcpAdaptor.validateJsonPayload(sessionId, mqttMsg.payload()); | ||
713 | - } | ||
714 | - | ||
715 | - private byte[] getBytes(ByteBuf payload) { | ||
716 | - return ProtoTcpAdaptor.toBytes(payload); | ||
717 | - } | ||
718 | - | ||
719 | - private void ack(MqttPublishMessage msg) { | ||
720 | - int msgId = getMsgId(msg); | ||
721 | - if (msgId > 0) { | ||
722 | - writeAndFlush(TcpTransportHandler.createMqttPubAckMsg(msgId)); | ||
723 | - } | ||
724 | - } | ||
725 | - | ||
726 | - private void deregisterSession(String deviceName, GatewayDeviceSessionCtx deviceSessionCtx) { | ||
727 | - transportService.deregisterSession(deviceSessionCtx.getSessionInfo()); | ||
728 | - transportService.process(deviceSessionCtx.getSessionInfo(), SESSION_EVENT_MSG_CLOSED, null); | ||
729 | - log.debug("[{}] Removed device [{}] from the gateway session", sessionId, deviceName); | ||
730 | - } | ||
731 | - | ||
732 | - private <T> TransportServiceCallback<Void> getPubAckCallback(final ChannelHandlerContext ctx, final String deviceName, final int msgId, final T msg) { | ||
733 | - return new TransportServiceCallback<Void>() { | ||
734 | - @Override | ||
735 | - public void onSuccess(Void dummy) { | ||
736 | - log.trace("[{}][{}] Published msg: {}", sessionId, deviceName, msg); | ||
737 | - if (msgId > 0) { | ||
738 | - ctx.writeAndFlush(TcpTransportHandler.createMqttPubAckMsg(msgId)); | ||
739 | - } | ||
740 | - } | ||
741 | - | ||
742 | - @Override | ||
743 | - public void onError(Throwable e) { | ||
744 | - log.trace("[{}] Failed to publish msg: {} for device: {}", sessionId, msg, deviceName, e); | ||
745 | - ctx.close(); | ||
746 | - } | ||
747 | - }; | ||
748 | - } | ||
749 | -} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/session/MqttDeviceAwareSessionContext.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp.session; | ||
17 | - | ||
18 | -import io.netty.handler.codec.mqtt.MqttQoS; | ||
19 | -import org.thingsboard.server.common.transport.session.DeviceAwareSessionContext; | ||
20 | - | ||
21 | -import java.util.List; | ||
22 | -import java.util.Map; | ||
23 | -import java.util.UUID; | ||
24 | -import java.util.concurrent.ConcurrentMap; | ||
25 | -import java.util.stream.Collectors; | ||
26 | - | ||
27 | -/** | ||
28 | - * Created by ashvayka on 30.08.18. | ||
29 | - */ | ||
30 | -public abstract class MqttDeviceAwareSessionContext extends DeviceAwareSessionContext { | ||
31 | - | ||
32 | - private final ConcurrentMap<MqttTopicMatcher, Integer> mqttQoSMap; | ||
33 | - | ||
34 | - public MqttDeviceAwareSessionContext(UUID sessionId, ConcurrentMap<MqttTopicMatcher, Integer> mqttQoSMap) { | ||
35 | - super(sessionId); | ||
36 | - this.mqttQoSMap = mqttQoSMap; | ||
37 | - } | ||
38 | - | ||
39 | - public ConcurrentMap<MqttTopicMatcher, Integer> getMqttQoSMap() { | ||
40 | - return mqttQoSMap; | ||
41 | - } | ||
42 | - | ||
43 | - public MqttQoS getQoSForTopic(String topic) { | ||
44 | - List<Integer> qosList = mqttQoSMap.entrySet() | ||
45 | - .stream() | ||
46 | - .filter(entry -> entry.getKey().matches(topic)) | ||
47 | - .map(Map.Entry::getValue) | ||
48 | - .collect(Collectors.toList()); | ||
49 | - if (!qosList.isEmpty()) { | ||
50 | - return MqttQoS.valueOf(qosList.get(0)); | ||
51 | - } else { | ||
52 | - return MqttQoS.AT_LEAST_ONCE; | ||
53 | - } | ||
54 | - } | ||
55 | -} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/session/MqttTopicMatcher.java
deleted
100644 → 0
1 | -/** | ||
2 | - * Copyright © 2016-2022 The Thingsboard Authors | ||
3 | - * | ||
4 | - * Licensed under the Apache License, Version 2.0 (the "License"); | ||
5 | - * you may not use this file except in compliance with the License. | ||
6 | - * You may obtain a copy of the License at | ||
7 | - * | ||
8 | - * http://www.apache.org/licenses/LICENSE-2.0 | ||
9 | - * | ||
10 | - * Unless required by applicable law or agreed to in writing, software | ||
11 | - * distributed under the License is distributed on an "AS IS" BASIS, | ||
12 | - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
13 | - * See the License for the specific language governing permissions and | ||
14 | - * limitations under the License. | ||
15 | - */ | ||
16 | -package org.thingsboard.server.transport.tcp.session; | ||
17 | - | ||
18 | -import java.util.regex.Pattern; | ||
19 | - | ||
20 | -public class MqttTopicMatcher { | ||
21 | - | ||
22 | - private final String topic; | ||
23 | - private final Pattern topicRegex; | ||
24 | - | ||
25 | - public MqttTopicMatcher(String topic) { | ||
26 | - if(topic == null){ | ||
27 | - throw new NullPointerException("topic"); | ||
28 | - } | ||
29 | - this.topic = topic; | ||
30 | - this.topicRegex = Pattern.compile(topic.replace("+", "[^/]+").replace("#", ".+") + "$"); | ||
31 | - } | ||
32 | - | ||
33 | - public String getTopic() { | ||
34 | - return topic; | ||
35 | - } | ||
36 | - | ||
37 | - public boolean matches(String topic){ | ||
38 | - return this.topicRegex.matcher(topic).matches(); | ||
39 | - } | ||
40 | - | ||
41 | - @Override | ||
42 | - public boolean equals(Object o) { | ||
43 | - if (this == o) return true; | ||
44 | - if (o == null || getClass() != o.getClass()) return false; | ||
45 | - | ||
46 | - MqttTopicMatcher that = (MqttTopicMatcher) o; | ||
47 | - | ||
48 | - return topic.equals(that.topic); | ||
49 | - } | ||
50 | - | ||
51 | - @Override | ||
52 | - public int hashCode() { | ||
53 | - return topic.hashCode(); | ||
54 | - } | ||
55 | -} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/session/TCPMessage.java
0 → 100644
1 | +package org.thingsboard.server.transport.tcp.session; | ||
2 | + | ||
3 | +import io.netty.handler.codec.mqtt.MqttMessageType; | ||
4 | +import lombok.Data; | ||
5 | +import lombok.NoArgsConstructor; | ||
6 | +import lombok.ToString; | ||
7 | + | ||
8 | +import java.io.Serializable; | ||
9 | + | ||
10 | +@Data | ||
11 | +public class TCPMessage implements Serializable { | ||
12 | + private String requestId; | ||
13 | + private MqttMessageType messageType; | ||
14 | + | ||
15 | + private byte[] message; | ||
16 | + private boolean hex; | ||
17 | + | ||
18 | + private String deviceId; | ||
19 | + | ||
20 | + /** | ||
21 | + * TCP 消息 | ||
22 | + * @param sn 设备sn | ||
23 | + * @param message 消息体 | ||
24 | + * @param hex 是否是16进制 | ||
25 | + */ | ||
26 | + public TCPMessage(MqttMessageType messageType, String deviceId, byte[] message, boolean hex){ | ||
27 | + this.messageType = messageType; | ||
28 | + this.deviceId = deviceId; | ||
29 | + this.message = message; | ||
30 | + this.hex = hex; | ||
31 | + } | ||
32 | + | ||
33 | + public TCPMessage(MqttMessageType messageType, byte[] message){ | ||
34 | + this.messageType = messageType; | ||
35 | + this.message = message; | ||
36 | + } | ||
37 | +} |
common/transport/tcp/src/main/java/org/thingsboard/server/transport/tcp/util/ByteUtils.java
0 → 100644
1 | +package org.thingsboard.server.transport.tcp.util; | ||
2 | + | ||
3 | +import io.netty.buffer.ByteBuf; | ||
4 | +import org.apache.commons.lang3.ArrayUtils; | ||
5 | + | ||
6 | +import java.io.*; | ||
7 | +import java.nio.charset.Charset; | ||
8 | + | ||
9 | +/** | ||
10 | + * @Description :数据类型转换工具类 | ||
11 | + * 二进制的最高位是符号位,0表示正,1表示负。 | ||
12 | + * 负数采用二进制的补码表示,10进制转为二进制得到的是源码,将源码按位取反得到的是反码,反码加1得到补码 | ||
13 | + * | ||
14 | + * | ||
15 | + * *¥¥¥【基本数据类型】¥¥¥¥¥¥¥¥¥¥¥¥ | ||
16 | + 1/8:boolean【1 位】 | ||
17 | + 3/8:byte 【1个字节,8 位】 | ||
18 | + 3/8:short 【2个字节,16位】 | ||
19 | + 4/8:int 【4个字节,32位】 | ||
20 | + 5/8:long 【8个字节,64位】 | ||
21 | + 6/8:float 【4个字节,32位】 | ||
22 | + 7/8:double 【8个字节,64位】 | ||
23 | + 8/8:chart 【2个字节,16位】 | ||
24 | + * | ||
25 | + * | ||
26 | + * | ||
27 | + * *¥¥¥【位运算】¥¥¥¥¥¥¥¥¥¥¥¥ | ||
28 | + 左移【<< n】:向左移动,左边高位舍弃,右边的低位补0,例如:2左移3位,结果为16 | ||
29 | + 右移【>>n】:向右移动,右边的舍弃掉,左边补的值取决于原来最高位,原来是1就补1,原来是0就补0 | ||
30 | + 无符号右移【>>>n】向右移动,右边的舍弃掉,左边补0。 | ||
31 | + * | ||
32 | + * | ||
33 | + * | ||
34 | + * 1.其它地方抛出异常,交由控制层统一处理 | ||
35 | + * 2.服务层注意持久化的事务管理 | ||
36 | + * @Author: junlianglee | ||
37 | + * @Date Created in 2019/12/11. | ||
38 | + * @Modified by Administrator on 2019/12/11. | ||
39 | + */ | ||
40 | +public class ByteUtils { | ||
41 | + public static final char[] ascii = "0123456789ABCDEF".toCharArray(); | ||
42 | + private static char[] HEX_VOCABLE = {'0', '1', '2', '3', '4', '5', '6', '7', | ||
43 | + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; | ||
44 | + | ||
45 | + public static final String UTF_8 = "UTF-8"; | ||
46 | + /** | ||
47 | + * 将short整型数值转换为字节数组 | ||
48 | + * | ||
49 | + * @param data | ||
50 | + * @return | ||
51 | + */ | ||
52 | + public static byte[] getBytes(short data) { | ||
53 | + byte[] bytes = new byte[2]; | ||
54 | + bytes[0] = (byte) ((data & 0xff00) >> 8);//1个十六进制位匹配4个二进制位 | ||
55 | + bytes[1] = (byte) (data & 0xff); | ||
56 | + return bytes; | ||
57 | + } | ||
58 | + | ||
59 | + /** | ||
60 | + * 将字符转换为字节数组 | ||
61 | + * | ||
62 | + * @param data | ||
63 | + * @return | ||
64 | + */ | ||
65 | + public static byte[] getBytes(char data) { | ||
66 | + byte[] bytes = new byte[2]; | ||
67 | + bytes[0] = (byte) (data >> 8); | ||
68 | + bytes[1] = (byte) (data); | ||
69 | + return bytes; | ||
70 | + } | ||
71 | + | ||
72 | + /** | ||
73 | + * 将布尔值转换为字节数组 | ||
74 | + * | ||
75 | + * @param data | ||
76 | + * @return | ||
77 | + */ | ||
78 | + public static byte[] getBytes(boolean data) { | ||
79 | + byte[] bytes = new byte[1]; | ||
80 | + bytes[0] = (byte) (data ? 1 : 0); | ||
81 | + return bytes; | ||
82 | + } | ||
83 | + | ||
84 | + /** | ||
85 | + * 将整型数值转换为字节数组 | ||
86 | + * | ||
87 | + * @param data | ||
88 | + * @return | ||
89 | + */ | ||
90 | + public static byte[] getBytes(int data) { | ||
91 | + byte[] bytes = new byte[4]; | ||
92 | + bytes[0] = (byte) ((data & 0xff000000) >> 24); | ||
93 | + bytes[1] = (byte) ((data & 0xff0000) >> 16); | ||
94 | + bytes[2] = (byte) ((data & 0xff00) >> 8); | ||
95 | + bytes[3] = (byte) (data & 0xff); | ||
96 | + return bytes; | ||
97 | + } | ||
98 | + | ||
99 | + /** | ||
100 | + * 将long整型数值转换为字节数组 | ||
101 | + * | ||
102 | + * @param data | ||
103 | + * @return | ||
104 | + */ | ||
105 | + public static byte[] getBytes(long data) { | ||
106 | + byte[] bytes = new byte[8]; | ||
107 | + bytes[0] = (byte) ((data >> 56) & 0xff); | ||
108 | + bytes[1] = (byte) ((data >> 48) & 0xff); | ||
109 | + bytes[2] = (byte) ((data >> 40) & 0xff); | ||
110 | + bytes[3] = (byte) ((data >> 32) & 0xff); | ||
111 | + bytes[4] = (byte) ((data >> 24) & 0xff); | ||
112 | + bytes[5] = (byte) ((data >> 16) & 0xff); | ||
113 | + bytes[6] = (byte) ((data >> 8) & 0xff); | ||
114 | + bytes[7] = (byte) (data & 0xff); | ||
115 | + return bytes; | ||
116 | + } | ||
117 | + | ||
118 | + /** | ||
119 | + * 将float型数值转换为字节数组 | ||
120 | + * | ||
121 | + * @param data | ||
122 | + * @return | ||
123 | + */ | ||
124 | + public static byte[] getBytes(float data) { | ||
125 | + int intBits = Float.floatToIntBits(data); | ||
126 | + return getBytes(intBits); | ||
127 | + } | ||
128 | + | ||
129 | + /** | ||
130 | + * 将double型数值转换为字节数组 | ||
131 | + * | ||
132 | + * @param data | ||
133 | + * @return | ||
134 | + */ | ||
135 | + public static byte[] getBytes(double data) { | ||
136 | + long intBits = Double.doubleToLongBits(data); | ||
137 | + return getBytes(intBits); | ||
138 | + } | ||
139 | + | ||
140 | + /** | ||
141 | + * 将字符串按照charsetName编码格式的字节数组 | ||
142 | + * | ||
143 | + * @param data | ||
144 | + * 字符串 | ||
145 | + * @param charsetName | ||
146 | + * 编码格式 | ||
147 | + * @return | ||
148 | + */ | ||
149 | + public static byte[] getBytes(String data, String charsetName) { | ||
150 | + Charset charset = Charset.forName(charsetName); | ||
151 | + return data.getBytes(charset); | ||
152 | + } | ||
153 | + | ||
154 | + | ||
155 | + | ||
156 | + | ||
157 | + | ||
158 | + /** | ||
159 | + * 将字节数组前8字节转换为long整型数值 | ||
160 | + * | ||
161 | + * @param bytes | ||
162 | + * @return | ||
163 | + */ | ||
164 | + public static long getLong(byte[] bytes) { | ||
165 | + return (0xff00000000000000L & ((long) bytes[0] << 56) | ||
166 | + | (0xff000000000000L & ((long) bytes[1] << 48)) | ||
167 | + | (0xff0000000000L & ((long) bytes[2] << 40)) | ||
168 | + | (0xff00000000L & ((long) bytes[3] << 32)) | ||
169 | + | (0xff000000L & ((long) bytes[4] << 24)) | ||
170 | + | (0xff0000L & ((long) bytes[5] << 16)) | ||
171 | + | (0xff00L & ((long) bytes[6] << 8)) | ||
172 | + | (0xffL & (long) bytes[7])); | ||
173 | + } | ||
174 | + | ||
175 | + | ||
176 | + | ||
177 | + /** | ||
178 | + * 将charsetName编码格式的字节数组转换为字符串 | ||
179 | + * | ||
180 | + * @param bytes | ||
181 | + * @param charsetName | ||
182 | + * @return | ||
183 | + */ | ||
184 | + public static String getString(byte[] bytes, String charsetName) { | ||
185 | + return new String(bytes, Charset.forName(charsetName)); | ||
186 | + } | ||
187 | + | ||
188 | + | ||
189 | + public static byte[] hexStr2Bytes(String hexString) { | ||
190 | + if (hexString == null || hexString.equals("")) { | ||
191 | + return null; | ||
192 | + } | ||
193 | + // toUpperCase将字符串中的所有字符转换为大写 | ||
194 | + hexString = hexString.toUpperCase(); | ||
195 | + int length = hexString.length() / 2;// 2个16进制字符表示一个字节,所以字节数组长度是字符串长度除以2 | ||
196 | + // toCharArray将此字符串转换为一个新的字符数组。 | ||
197 | + char[] hexChars = hexString.toCharArray(); | ||
198 | + byte[] d = new byte[length]; | ||
199 | + for (int i = 0; i < length; i++) { | ||
200 | + int pos = i * 2; | ||
201 | + d[i] = (byte) (charToByte(hexChars[pos]) << 4 | ||
202 | + | charToByte(hexChars[pos + 1])); | ||
203 | + } | ||
204 | + return d; | ||
205 | + } | ||
206 | + | ||
207 | + // charToByte返回在指定字符的第一个发生的字符串中的索引,即返回匹配字符 | ||
208 | + private static byte charToByte(char c) { | ||
209 | + return (byte) "0123456789ABCDEF".indexOf(c); | ||
210 | + } | ||
211 | + /** | ||
212 | + * 将16进制字符串转换为字节数组 | ||
213 | + * | ||
214 | + * @param hex | ||
215 | + * @return | ||
216 | + */ | ||
217 | + public static byte[] hexToBytes(String hex) { | ||
218 | + if (hex.length() % 2 != 0) | ||
219 | + throw new IllegalArgumentException( | ||
220 | + "input string should be any multiple of 2!"); | ||
221 | + hex.toUpperCase(); | ||
222 | + | ||
223 | + byte[] byteBuffer = new byte[hex.length() / 2]; | ||
224 | + | ||
225 | + byte padding = 0x00; | ||
226 | + boolean paddingTurning = false; | ||
227 | + for (int i = 0; i < hex.length(); i++) { | ||
228 | + if (paddingTurning) { | ||
229 | + char c = hex.charAt(i); | ||
230 | + int index = indexOf(hex, c); | ||
231 | + padding = (byte) ((padding << 4) | index); | ||
232 | + byteBuffer[i / 2] = padding; | ||
233 | + padding = 0x00; | ||
234 | + paddingTurning = false; | ||
235 | + } else { | ||
236 | + char c = hex.charAt(i); | ||
237 | + int index = indexOf(hex, c); | ||
238 | + padding = (byte) (padding | index); | ||
239 | + paddingTurning = true; | ||
240 | + } | ||
241 | + | ||
242 | + } | ||
243 | + return byteBuffer; | ||
244 | + } | ||
245 | + | ||
246 | + private static int indexOf(String input, char c) { | ||
247 | + int index = ArrayUtils.indexOf(HEX_VOCABLE, c); | ||
248 | + | ||
249 | + if (index < 0) { | ||
250 | + throw new IllegalArgumentException("err input:" + input); | ||
251 | + } | ||
252 | + return index; | ||
253 | + | ||
254 | + } | ||
255 | + /** | ||
256 | + * 字节数组转16进制字符串 | ||
257 | + * | ||
258 | + * @param bs | ||
259 | + * @return | ||
260 | + */ | ||
261 | + public static String bytesToHex(byte[] bs) { | ||
262 | + StringBuilder sb = new StringBuilder(); | ||
263 | + for (byte b : bs) { | ||
264 | + int high = (b >> 4) & 0x0f; | ||
265 | + int low = b & 0x0f; | ||
266 | + sb.append(HEX_VOCABLE[high]); | ||
267 | + sb.append(HEX_VOCABLE[low]); | ||
268 | + } | ||
269 | + return sb.toString(); | ||
270 | + } | ||
271 | + | ||
272 | + /** | ||
273 | + * 字节数组取前len个字节转16进制字符串 | ||
274 | + * | ||
275 | + * @param bs | ||
276 | + * @param len | ||
277 | + * @return | ||
278 | + */ | ||
279 | + public static String bytesToHex(byte[] bs, int len) { | ||
280 | + StringBuilder sb = new StringBuilder(); | ||
281 | + for (int i = 0; i < len; i++) { | ||
282 | + byte b = bs[i]; | ||
283 | + int high = (b >> 4) & 0x0f; | ||
284 | + int low = b & 0x0f; | ||
285 | + sb.append(HEX_VOCABLE[high]); | ||
286 | + sb.append(HEX_VOCABLE[low]); | ||
287 | + } | ||
288 | + return sb.toString(); | ||
289 | + } | ||
290 | + /** | ||
291 | + * 字节数组偏移offset长度之后的取len个字节转16进制字符串 | ||
292 | + * | ||
293 | + * @param bs | ||
294 | + * @param offset | ||
295 | + * @param len | ||
296 | + * @return | ||
297 | + */ | ||
298 | + public static String bytesToHex(byte[] bs, int offset, int len) { | ||
299 | + StringBuilder sb = new StringBuilder(); | ||
300 | + for (int i = 0; i < len; i++) { | ||
301 | + byte b = bs[offset + i]; | ||
302 | + int high = (b >> 4) & 0x0f; | ||
303 | + int low = b & 0x0f; | ||
304 | + sb.append(HEX_VOCABLE[high]); | ||
305 | + sb.append(HEX_VOCABLE[low]); | ||
306 | + } | ||
307 | + return sb.toString(); | ||
308 | + } | ||
309 | + /** | ||
310 | + * 字节数组转16进制字符串 | ||
311 | + * | ||
312 | + * @param bs | ||
313 | + * @return | ||
314 | + */ | ||
315 | + public static String byteToHex(byte bs) { | ||
316 | + StringBuilder sb = new StringBuilder(); | ||
317 | + int high = (bs >> 4) & 0x0f; | ||
318 | + int low = bs & 0x0f; | ||
319 | + sb.append(HEX_VOCABLE[high]); | ||
320 | + sb.append(HEX_VOCABLE[low]); | ||
321 | + return sb.toString(); | ||
322 | + } | ||
323 | + /** | ||
324 | + * 将字节数组取反 | ||
325 | + * | ||
326 | + * @param src | ||
327 | + * @return | ||
328 | + */ | ||
329 | + public static String negate(byte[] src) { | ||
330 | + if (src == null || src.length == 0) { | ||
331 | + return null; | ||
332 | + } | ||
333 | + byte[] temp = new byte[2 * src.length]; | ||
334 | + for (int i = 0; i < src.length; i++) { | ||
335 | + byte tmp = (byte) (0xFF ^ src[i]); | ||
336 | + temp[i * 2] = (byte) ((tmp >> 4) & 0x0f); | ||
337 | + temp[i * 2 + 1] = (byte) (tmp & 0x0f); | ||
338 | + } | ||
339 | + StringBuffer res = new StringBuffer(); | ||
340 | + for (int i = 0; i < temp.length; i++) { | ||
341 | + res.append(ascii[temp[i]]); | ||
342 | + } | ||
343 | + return res.toString(); | ||
344 | + } | ||
345 | + | ||
346 | + | ||
347 | + | ||
348 | + /** | ||
349 | + * 数组合并 | ||
350 | + * @param before | ||
351 | + * @param end | ||
352 | + * @return | ||
353 | + */ | ||
354 | + public static byte[] merge(byte[]before,byte[]end){ | ||
355 | + byte[] result= new byte[before.length+end.length]; | ||
356 | + System.arraycopy(before,0,result,0,before.length); | ||
357 | + System.arraycopy(end,0,result,before.length,end.length); | ||
358 | + return result; | ||
359 | + } | ||
360 | + | ||
361 | + public static byte[] subBytes(byte[]before,Integer start,Integer length){ | ||
362 | + byte[] result= new byte[length]; | ||
363 | + System.arraycopy(before,start,result,0,length); | ||
364 | + return result; | ||
365 | + } | ||
366 | + | ||
367 | + /** | ||
368 | + * 比较字节数组是否相同 | ||
369 | + * | ||
370 | + * @param a | ||
371 | + * @param b | ||
372 | + * @return | ||
373 | + */ | ||
374 | + public static boolean compareBytes(byte[] a, byte[] b) { | ||
375 | + if (a == null || a.length == 0 || b == null || b.length == 0 | ||
376 | + || a.length != b.length) { | ||
377 | + return false; | ||
378 | + } | ||
379 | + if (a.length == b.length) { | ||
380 | + for (int i = 0; i < a.length; i++) { | ||
381 | + if (a[i] != b[i]) { | ||
382 | + return false; | ||
383 | + } | ||
384 | + } | ||
385 | + } else { | ||
386 | + return false; | ||
387 | + } | ||
388 | + return true; | ||
389 | + } | ||
390 | + /** | ||
391 | + * 只比对指定长度byte | ||
392 | + * | ||
393 | + * @param a | ||
394 | + * @param b | ||
395 | + * @param len | ||
396 | + * @return | ||
397 | + */ | ||
398 | + public static boolean compareBytes(byte[] a, byte[] b, int len) { | ||
399 | + if (a == null || a.length == 0 || b == null || b.length == 0 | ||
400 | + || a.length < len || b.length < len) { | ||
401 | + return false; | ||
402 | + } | ||
403 | + for (int i = 0; i < len; i++) { | ||
404 | + if (a[i] != b[i]) { | ||
405 | + return false; | ||
406 | + } | ||
407 | + } | ||
408 | + return true; | ||
409 | + } | ||
410 | + | ||
411 | + /** | ||
412 | + * 将字节数组转换为二进制字符串 | ||
413 | + * | ||
414 | + * @param items | ||
415 | + * @return | ||
416 | + */ | ||
417 | + public static String bytesToBinaryString(byte[] items) { | ||
418 | + if (items == null || items.length == 0) { | ||
419 | + return null; | ||
420 | + } | ||
421 | + StringBuffer buf = new StringBuffer(); | ||
422 | + for (byte item : items) { | ||
423 | + buf.append(byteToBinaryString(item)); | ||
424 | + } | ||
425 | + return buf.toString(); | ||
426 | + } | ||
427 | + | ||
428 | + /** | ||
429 | + * 将字节转换为二进制字符串 | ||
430 | + * | ||
431 | + * @param item | ||
432 | + * @return | ||
433 | + */ | ||
434 | + public static String byteToBinaryString(byte item) { | ||
435 | + byte a = item; | ||
436 | + StringBuffer buf = new StringBuffer(); | ||
437 | + for (int i = 0; i < 8; i++) { | ||
438 | + buf.insert(0, a % 2); | ||
439 | + a = (byte) (a >> 1); | ||
440 | + } | ||
441 | + return buf.toString(); | ||
442 | + } | ||
443 | + | ||
444 | + /** | ||
445 | + * 对数组a,b进行异或运算 | ||
446 | + * | ||
447 | + * @param a | ||
448 | + * @param b | ||
449 | + * @return | ||
450 | + */ | ||
451 | + public static byte[] xor(byte[] a, byte[] b) { | ||
452 | + if (a == null || a.length == 0 || b == null || b.length == 0 | ||
453 | + || a.length != b.length) { | ||
454 | + return null; | ||
455 | + } | ||
456 | + byte[] result = new byte[a.length]; | ||
457 | + for (int i = 0; i < a.length; i++) { | ||
458 | + result[i] = (byte) (a[i] ^ b[i]); | ||
459 | + } | ||
460 | + return result; | ||
461 | + } | ||
462 | + | ||
463 | + /** | ||
464 | + * 对数组a,b进行异或运算 运算长度len | ||
465 | + * | ||
466 | + * @param a | ||
467 | + * @param b | ||
468 | + * @param len | ||
469 | + * @return | ||
470 | + */ | ||
471 | + public static byte[] xor(byte[] a, byte[] b, int len) { | ||
472 | + if (a == null || a.length == 0 || b == null || b.length == 0) { | ||
473 | + return null; | ||
474 | + } | ||
475 | + if (a.length < len || b.length < len) { | ||
476 | + return null; | ||
477 | + } | ||
478 | + byte[] result = new byte[len]; | ||
479 | + for (int i = 0; i < len; i++) { | ||
480 | + result[i] = (byte) (a[i] ^ b[i]); | ||
481 | + } | ||
482 | + return result; | ||
483 | + } | ||
484 | + /** | ||
485 | + * 将short整型数值转换为字节数组 | ||
486 | + * | ||
487 | + * @param num | ||
488 | + * @return | ||
489 | + */ | ||
490 | + public static byte[] shortToBytes(int num) { | ||
491 | + byte[] temp = new byte[2]; | ||
492 | + for (int i = 0; i < 2; i++) { | ||
493 | + temp[i] = (byte) ((num >>> (8 - i * 8)) & 0xFF); | ||
494 | + } | ||
495 | + return temp; | ||
496 | + } | ||
497 | + | ||
498 | + /** | ||
499 | + * 将字节数组转为整型 | ||
500 | + * | ||
501 | + * @param arr | ||
502 | + * @return | ||
503 | + */ | ||
504 | + public static int bytesToShort(byte[] arr) { | ||
505 | + int mask = 0xFF; | ||
506 | + int temp = 0; | ||
507 | + int result = 0; | ||
508 | + for (int i = 0; i < 2; i++) { | ||
509 | + result <<= 8; | ||
510 | + temp = arr[i] & mask; | ||
511 | + result |= temp; | ||
512 | + } | ||
513 | + return result; | ||
514 | + } | ||
515 | + | ||
516 | + /** | ||
517 | + * 将整型数值转换为指定长度的字节数组 | ||
518 | + * | ||
519 | + * @param num | ||
520 | + * @return | ||
521 | + */ | ||
522 | + public static byte[] intToBytes(int num) { | ||
523 | + byte[] temp = new byte[4]; | ||
524 | + for (int i = 0; i < 4; i++) { | ||
525 | + temp[i] = (byte) ((num >>> (24 - i * 8)) & 0xFF); | ||
526 | + } | ||
527 | + return temp; | ||
528 | + } | ||
529 | + | ||
530 | + /** | ||
531 | + * 将整型数值转换为指定长度的字节数组 | ||
532 | + * | ||
533 | + * @param src | ||
534 | + * @param len | ||
535 | + * @return | ||
536 | + */ | ||
537 | + public static byte[] intToBytes(int src, int len) { | ||
538 | + if (len < 1 || len > 4) { | ||
539 | + return null; | ||
540 | + } | ||
541 | + byte[] temp = new byte[len]; | ||
542 | + for (int i = 0; i < len; i++) { | ||
543 | + temp[len - 1 - i] = (byte) ((src >>> (8 * i)) & 0xFF); | ||
544 | + } | ||
545 | + return temp; | ||
546 | + } | ||
547 | + | ||
548 | + /** | ||
549 | + * 将字节数组转换为整型数值 | ||
550 | + * | ||
551 | + * @param arr | ||
552 | + * @return | ||
553 | + */ | ||
554 | + public static int bytesToInt(byte[] arr) { | ||
555 | + int mask = 0xFF; | ||
556 | + int temp = 0; | ||
557 | + int result = 0; | ||
558 | + for (int i = 0; i < 4; i++) { | ||
559 | + result <<= 8; | ||
560 | + temp = arr[i] & mask; | ||
561 | + result |= temp; | ||
562 | + } | ||
563 | + return result; | ||
564 | + } | ||
565 | + | ||
566 | + /** | ||
567 | + * 将long整型数值转换为字节数组 | ||
568 | + * | ||
569 | + * @param num | ||
570 | + * @return | ||
571 | + */ | ||
572 | + public static byte[] longToBytes(long num) { | ||
573 | + byte[] temp = new byte[8]; | ||
574 | + for (int i = 0; i < 8; i++) { | ||
575 | + temp[i] = (byte) ((num >>> (56 - i * 8)) & 0xFF); | ||
576 | + } | ||
577 | + return temp; | ||
578 | + } | ||
579 | + | ||
580 | + /** | ||
581 | + * 将字节数组转换为long整型数值 | ||
582 | + * | ||
583 | + * @param arr | ||
584 | + * @return | ||
585 | + */ | ||
586 | + public static long bytesToLong(byte[] arr) { | ||
587 | + int mask = 0xFF; | ||
588 | + int temp = 0; | ||
589 | + long result = 0; | ||
590 | + int len = Math.min(8, arr.length); | ||
591 | + for (int i = 0; i < len; i++) { | ||
592 | + result <<= 8; | ||
593 | + temp = arr[i] & mask; | ||
594 | + result |= temp; | ||
595 | + } | ||
596 | + return result; | ||
597 | + } | ||
598 | + | ||
599 | + /** | ||
600 | + * 将16进制字符转换为字节 | ||
601 | + * | ||
602 | + * @param c | ||
603 | + * @return | ||
604 | + */ | ||
605 | + public static byte toByte(char c) { | ||
606 | + byte b = (byte) "0123456789ABCDEF".indexOf(c); | ||
607 | + return b; | ||
608 | + } | ||
609 | + | ||
610 | + /** | ||
611 | + * 功能描述:把两个字节的字节数组转化为整型数据,高位补零,例如:<br/> | ||
612 | + * 有字节数组byte[] data = new byte[]{1,2};转换后int数据的字节分布如下:<br/> | ||
613 | + * 00000000 00000000 00000001 00000010,函数返回258 | ||
614 | + * | ||
615 | + * @param lenData | ||
616 | + * 需要进行转换的字节数组 | ||
617 | + * @return 字节数组所表示整型值的大小 | ||
618 | + */ | ||
619 | + public static int bytesToIntWhereByteLengthEquals2(byte lenData[]) { | ||
620 | + if (lenData.length != 2) { | ||
621 | + return -1; | ||
622 | + } | ||
623 | + byte fill[] = new byte[]{0, 0}; | ||
624 | + byte real[] = new byte[4]; | ||
625 | + System.arraycopy(fill, 0, real, 0, 2); | ||
626 | + System.arraycopy(lenData, 0, real, 2, 2); | ||
627 | + int len = byteToInt(real); | ||
628 | + return len; | ||
629 | + | ||
630 | + } | ||
631 | + | ||
632 | + /** | ||
633 | + * 功能描述:将byte数组转化为int类型的数据 | ||
634 | + * | ||
635 | + * @param byteVal | ||
636 | + * 需要转化的字节数组 | ||
637 | + * @return 字节数组所表示的整型数据 | ||
638 | + */ | ||
639 | + public static int byteToInt(byte[] byteVal) { | ||
640 | + int result = 0; | ||
641 | + for (int i = 0; i < byteVal.length; i++) { | ||
642 | + int tmpVal = (byteVal[i] << (8 * (3 - i))); | ||
643 | + switch (i) { | ||
644 | + case 0 : | ||
645 | + tmpVal = tmpVal & 0xFF000000; | ||
646 | + break; | ||
647 | + case 1 : | ||
648 | + tmpVal = tmpVal & 0x00FF0000; | ||
649 | + break; | ||
650 | + case 2 : | ||
651 | + tmpVal = tmpVal & 0x0000FF00; | ||
652 | + break; | ||
653 | + case 3 : | ||
654 | + tmpVal = tmpVal & 0x000000FF; | ||
655 | + break; | ||
656 | + } | ||
657 | + | ||
658 | + result = result | tmpVal; | ||
659 | + } | ||
660 | + return result; | ||
661 | + } | ||
662 | + public static byte CheckXORSum(byte[] bData) { | ||
663 | + byte sum = 0x00; | ||
664 | + for (int i = 0; i < bData.length; i++) { | ||
665 | + sum ^= bData[i]; | ||
666 | + } | ||
667 | + return sum; | ||
668 | + } | ||
669 | + /** | ||
670 | + * 从offset开始 将后续长度为len的byte字节转为int | ||
671 | + * | ||
672 | + * @param data | ||
673 | + * @param offset | ||
674 | + * @param len | ||
675 | + * @return | ||
676 | + */ | ||
677 | + public static int bytesToInt(byte[] data, int offset, int len) { | ||
678 | + int mask = 0xFF; | ||
679 | + int temp = 0; | ||
680 | + int result = 0; | ||
681 | + len = Math.min(len, 4); | ||
682 | + for (int i = 0; i < len; i++) { | ||
683 | + result <<= 8; | ||
684 | + temp = data[offset + i] & mask; | ||
685 | + result |= temp; | ||
686 | + } | ||
687 | + return result; | ||
688 | + } | ||
689 | + | ||
690 | + /** | ||
691 | + * byte字节数组中的字符串的长度 | ||
692 | + * | ||
693 | + * @param data | ||
694 | + * @return | ||
695 | + */ | ||
696 | + public static int getBytesStringLen(byte[] data) { | ||
697 | + int count = 0; | ||
698 | + for (byte b : data) { | ||
699 | + if (b == 0x00) | ||
700 | + break; | ||
701 | + count++; | ||
702 | + } | ||
703 | + return count; | ||
704 | + } | ||
705 | + | ||
706 | + /** | ||
707 | + * 校验和 | ||
708 | + * | ||
709 | + * @param msg | ||
710 | + * 需要计算校验和的byte数组 | ||
711 | + * @param length | ||
712 | + * 校验和位数 | ||
713 | + * @return 计算出的校验和数组 | ||
714 | + */ | ||
715 | + public static byte[] SumCheck(byte[] msg, int length) { | ||
716 | + long mSum = 0; | ||
717 | + byte[] mByte = new byte[length]; | ||
718 | + | ||
719 | + /** 逐Byte添加位数和 */ | ||
720 | + for (byte byteMsg : msg) { | ||
721 | + long mNum = ((long) byteMsg >= 0) | ||
722 | + ? (long) byteMsg | ||
723 | + : ((long) byteMsg + 256); | ||
724 | + mSum += mNum; | ||
725 | + } /** end of for (byte byteMsg : msg) */ | ||
726 | + | ||
727 | + /** 位数和转化为Byte数组 */ | ||
728 | + for (int liv_Count = 0; liv_Count < length; liv_Count++) { | ||
729 | + mByte[length - liv_Count | ||
730 | + - 1] = (byte) (mSum >> (liv_Count * 8) & 0xff); | ||
731 | + } /** end of for (int liv_Count = 0; liv_Count < length; liv_Count++) */ | ||
732 | + | ||
733 | + return mByte; | ||
734 | + } | ||
735 | + | ||
736 | + /** | ||
737 | + * 字节数据转十进制字符(补码-无符号) | ||
738 | + * | ||
739 | + * @param data | ||
740 | + * @return | ||
741 | + */ | ||
742 | + public static String getByteToStr(byte[] data) { | ||
743 | + StringBuffer str = new StringBuffer(); | ||
744 | + for (int i = 0; i < data.length; i++) { | ||
745 | + if (data[i] < 0) { | ||
746 | + int tem = data[i] + 256; | ||
747 | + str.append(tem + " "); | ||
748 | + } else { | ||
749 | + str.append(data[i] + " "); | ||
750 | + } | ||
751 | + } | ||
752 | + return str.toString(); | ||
753 | + } | ||
754 | + | ||
755 | + public static byte[] buf2Bytes(ByteBuf in) { | ||
756 | + return buf2Bytes( in, in.readableBytes()) ; | ||
757 | + } | ||
758 | + public static byte[] buf2Bytes(ByteBuf in,int readable) { | ||
759 | + byte[] dst = new byte[readable]; | ||
760 | + in.getBytes(0, dst); | ||
761 | + return dst; | ||
762 | + } | ||
763 | + | ||
764 | + public static byte[] fileBytes(String pathname) throws IOException { | ||
765 | + File filename = new File(pathname); | ||
766 | + BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename)); | ||
767 | + ByteArrayOutputStream out = new ByteArrayOutputStream(1024); | ||
768 | + byte[] temp = new byte[1024]; | ||
769 | + int size = 0; | ||
770 | + while((size = in.read(temp)) != -1){ | ||
771 | + out.write(temp, 0, size); | ||
772 | + } | ||
773 | + in.close(); | ||
774 | + out.close(); | ||
775 | + byte[] content = out.toByteArray(); | ||
776 | + return content; | ||
777 | + } | ||
778 | + /** | ||
779 | + * 单字节高低位互换 | ||
780 | + * @param src | ||
781 | + * @return | ||
782 | + */ | ||
783 | + public static int revert(int src) { | ||
784 | + int lowByte = (src & 0xFF00) >> 8; | ||
785 | + int highByte = (src & 0x00FF) << 8; | ||
786 | + return lowByte | highByte; | ||
787 | + } | ||
788 | +} |
@@ -28,9 +28,9 @@ server: | @@ -28,9 +28,9 @@ server: | ||
28 | # Zookeeper connection parameters. Used for service discovery. | 28 | # Zookeeper connection parameters. Used for service discovery. |
29 | zk: | 29 | zk: |
30 | # Enable/disable zookeeper discovery service. | 30 | # Enable/disable zookeeper discovery service. |
31 | - enabled: "${ZOOKEEPER_ENABLED:false}" | 31 | + enabled: "${ZOOKEEPER_ENABLED:true}" |
32 | # Zookeeper connect string | 32 | # Zookeeper connect string |
33 | - url: "${ZOOKEEPER_URL:localhost:2181}" | 33 | + url: "${ZOOKEEPER_URL:47.99.141.212:2181}" |
34 | # Zookeeper retry interval in milliseconds | 34 | # Zookeeper retry interval in milliseconds |
35 | retry_interval_ms: "${ZOOKEEPER_RETRY_INTERVAL_MS:3000}" | 35 | retry_interval_ms: "${ZOOKEEPER_RETRY_INTERVAL_MS:3000}" |
36 | # Zookeeper connection timeout in milliseconds | 36 | # Zookeeper connection timeout in milliseconds |
@@ -68,7 +68,7 @@ redis: | @@ -68,7 +68,7 @@ redis: | ||
68 | # db index | 68 | # db index |
69 | db: "${REDIS_DB:0}" | 69 | db: "${REDIS_DB:0}" |
70 | # db password | 70 | # db password |
71 | - password: "${REDIS_PASSWORD:}" | 71 | + password: "${REDIS_PASSWORD:redis@6379}" |
72 | # pool config | 72 | # pool config |
73 | pool_config: | 73 | pool_config: |
74 | maxTotal: "${REDIS_POOL_CONFIG_MAX_TOTAL:128}" | 74 | maxTotal: "${REDIS_POOL_CONFIG_MAX_TOTAL:128}" |
@@ -163,7 +163,7 @@ transport: | @@ -163,7 +163,7 @@ transport: | ||
163 | queue: | 163 | queue: |
164 | type: "${TB_QUEUE_TYPE:kafka}" # kafka (Apache Kafka) or aws-sqs (AWS SQS) or pubsub (PubSub) or service-bus (Azure Service Bus) or rabbitmq (RabbitMQ) | 164 | type: "${TB_QUEUE_TYPE:kafka}" # kafka (Apache Kafka) or aws-sqs (AWS SQS) or pubsub (PubSub) or service-bus (Azure Service Bus) or rabbitmq (RabbitMQ) |
165 | kafka: | 165 | kafka: |
166 | - bootstrap.servers: "${TB_KAFKA_SERVERS:localhost:9092}" | 166 | + bootstrap.servers: "${TB_KAFKA_SERVERS:47.99.141.212:9092}" |
167 | acks: "${TB_KAFKA_ACKS:all}" | 167 | acks: "${TB_KAFKA_ACKS:all}" |
168 | retries: "${TB_KAFKA_RETRIES:1}" | 168 | retries: "${TB_KAFKA_RETRIES:1}" |
169 | batch.size: "${TB_KAFKA_BATCH_SIZE:16384}" | 169 | batch.size: "${TB_KAFKA_BATCH_SIZE:16384}" |