package com.flightfeather.uav.socket.decoder
|
|
import com.flightfeather.uav.common.utils.CommonUtil
|
import com.flightfeather.uav.socket.bean.BaseMessage
|
import java.text.SimpleDateFormat
|
import java.util.*
|
|
/**
|
* @author riku
|
* Date: 2020/9/10
|
*/
|
typealias Decode<T> = (m: T, s: String) -> Unit
|
|
abstract class BaseDataDecoder<T : BaseMessage> {
|
|
companion object {
|
const val INVALID_VALUE = -1.0
|
}
|
|
private var isInit = false
|
|
private lateinit var message: T
|
|
abstract fun messageClass(): Class<T>
|
|
abstract fun getCpDecode(): List<Decode<T>>
|
|
private val decodeList = mutableListOf<Decode<T>>()
|
|
private val getHead: Decode<T> = {m, s ->
|
m.head = s.substring(0, 2)
|
}
|
|
private val getLength: Decode<T> = {m, s ->
|
m.length = s.substring(2, 6)
|
}
|
|
private val getQN: Decode<T> = {m, s ->
|
m.qn = getData(s, "QN=", ";")
|
}
|
|
private val getST: Decode<T> = {m, s ->
|
m.st = getData(s, "ST=", ";")
|
}
|
|
private val getCN: Decode<T> = {m, s ->
|
m.cn = getData(s, "CN=", ";")
|
}
|
|
private val getPW: Decode<T> = {m, s ->
|
m.pw = getData(s, "PW=", ";")
|
}
|
|
private val getMN: Decode<T> = {m, s ->
|
m.mn = getData(s, "MN=", ";")
|
}
|
|
private val getCP: Decode<T> = {m, s ->
|
m.cp = getData(s, "CP=&&", "&&")
|
}
|
|
private val getExtra:Decode<T> = {m, s ->
|
val start = s.lastIndexOf("&&")
|
val end = s.length - 4
|
m.extra = s.substring(start, end).substring(2)
|
}
|
|
|
private val getCrc: Decode<T> = {m, s ->
|
m.crc = s.substring(s.length - 4, s.length)
|
}
|
|
protected fun getData(msg: String, start: String, end: String) =
|
CommonUtil.getSubStr(msg, start, end)?.substring(start.length) ?: ""
|
|
private fun init() {
|
if (!isInit) {
|
|
decodeList.add(getHead)
|
decodeList.add(getLength)
|
decodeList.add(getQN)
|
decodeList.add(getST)
|
decodeList.add(getCN)
|
decodeList.add(getPW)
|
decodeList.add(getMN)
|
decodeList.add(getCP)
|
decodeList.add(getExtra)
|
decodeList.add(getCrc)
|
|
decodeList.addAll(this.getCpDecode())
|
|
isInit = true
|
}
|
message = this.messageClass().newInstance()
|
}
|
|
fun decode(msg: String): T {
|
init()
|
|
decodeList.forEach {
|
try {
|
it.invoke(message, msg)
|
} catch (e: Exception) {
|
println("${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}: 命令无法获取[${it.javaClass.name}]")
|
}
|
}
|
return message
|
}
|
}
|