package com.develop.common.food_sdk

import android.serialport.SerialPort
import android.util.Log
import com.kuyuntech.cofarcooking.device.sdk.protocol.core.BaseDecoder
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import java.util.*


class ProtocolListener(private val serialPort: SerialPort) : Runnable {

    override fun run() {
        try {
            var tmp = ByteArray(1024)
            var len = -1
            val bytes: MutableList<Byte> = ArrayList()
            while (serialPort.inputStream.read(tmp).also { len = it } != -1) {
                val cmdTmp = tmp.copyOf(len)
                tmp = ByteArray(1024)
                for (b in cmdTmp) {
                    if (b.toInt() == 0x7e) {
                        if (bytes.size == 0) {
                            bytes.add(b)
                        } else {
                            bytes.add(b)
                            try {
                                val cmd = ByteArray(bytes.size)
                                for (i in bytes.indices) {
                                    cmd[i] = bytes[i]
                                }
                                val baseDecoder = BaseDecoder(cmd)
                                Log.i("mcu2dev:", baseDecoder.escapeBytesStr())
                                CofarSDK.post2Dev(baseDecoder.baseBody)
                                bytes.clear()
                            } catch (e: Exception) {
                                e.printStackTrace()
                                Log.i("weilai-protocol", e.message!!)
                                bytes.clear()
                                bytes.add(b)
                            }
                        }
                    } else if (bytes.size != 0) {
                        bytes.add(b)
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.i("weilai-protocol", e.message!!)
        }
    }
}
