import android.util.Log
import com.gnetek.tool.socket.base.SmartIotProtocol
import com.gnetek.tool.utils.IntBytesUtils
import com.swallowsonny.convertextlibrary.toHexString
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
/**
* 接收解码方式
*/
class SmartIotDecoder: ByteToMessageDecoder() {
companion object{
private const val TAG = "SmartIotDecoder"
}
override fun decode(ctx: ChannelHandlerContext?, buffer: ByteBuf?, out: MutableList<Any>?) {
buffer?.run {
Log.e(TAG, "decode: 开始解析")
val totalLenght = readableBytes() //bytebuf的长度,默认512字节
Log.e(TAG, "decode: buffer长度=${totalLenght}" )
if(totalLenght >= SmartIotProtocol.minLen){//数据长度大于等于最小包长度
var beginReader:Int
while (true) {
//记录包头开始位置
beginReader = readerIndex()
//标记包头开始index
markReaderIndex()
//读到了协议的开始标志,结束while循环
if (readShort() == IntBytesUtils.bytes2ToShortHL(SmartIotProtocol.start)) {
break
}
// 未读到包头,略过一个字节
// 每次略过,一个字节,去读取,包头信息的开始标记
resetReaderIndex()
readByte()
// 当略过,一个字节之后,
// 数据包的长度,又变得不满足
// 此时,应该结束。等待后面的数据到达
if (readableBytes() < SmartIotProtocol.minLen) {
return
}
}
//数据包总长度-2个字节
val packageLenght = readShort()
Log.e(TAG, "decode: package长度=${packageLenght}" )
//包序号-4个字节
val sequence = ByteArray(4)
sequence[0]=readByte()
sequence[1]=readByte()
sequence[2]=readByte()
sequence[3]=readByte()
//code 命令码2个字节
val cmdCode = ByteArray(2)
cmdCode[0] = readByte()
cmdCode[1] = readByte()
Log.e(TAG, "decode: 命令码=${cmdCode.toHexString(false)}")
//数据长度
val bodyLen = totalLenght-12
Log.e(TAG, "decode: body长度=${bodyLen}" )
//读取数据
var body = byteArrayOf()
if(bodyLen>0){
body = ByteArray(bodyLen)
readBytes(body)
}
//结束标识
val end = readShort()
Log.e(TAG, "decode end: ${end}")
Log.e(TAG, "SmartIotProtocol end ${IntBytesUtils.bytes2ToShortHL(SmartIotProtocol.end)}", )
if(end == IntBytesUtils.bytes2ToShortHL(SmartIotProtocol.end)){
val iot= SmartIotProtocol(IntBytesUtils.shortToBytes2HL(packageLenght),
sequence,
cmdCode,
body)
out?.add(iot)
Log.e(TAG, "decode: 解析完成 ${body.toHexString()}")
}else{
readerIndex(beginReader)
Log.e(TAG, "decode: 还原读指针")
}
}
}
}
}
netty接收到数据进行分析包装
最新推荐文章于 2024-07-11 03:24:23 发布