package com.develop.common.food_sdk

import android.serialport.SerialPort
import android.util.Log
import com.kuyuntech.cofarcooking.device.sdk.eventbus.event.Dev2McuDataEvent
import com.kuyuntech.cofarcooking.device.sdk.eventbus.listener.Dev2McuEventListener
import com.kuyuntech.cofarcooking.device.sdk.eventbus.listener.Mcu2DevEventListener
import com.kuyuntech.cofarcooking.device.sdk.util.core.CofarSDK
import com.kuyuntech.cofarcooking.device.sdk.util.core.Converter
import java.io.File
import java.io.IOException

object SerialPortUtils {

    private var thread: Thread? = null

    fun init() {
        val serialPortPath = "/dev/ttyS1"
        val baudRate = 9600
        val dataBits = 8
        val parity = 0
        val stopBits = 1
        val flags = 0
        try {
            SerialPort.setSuPath("/system/xbin/su")
            val serialPort =
                SerialPort(File(serialPortPath), baudRate, dataBits, parity, stopBits, flags)
            val dev2McuEventListener = Dev2McuEventListener { event: Dev2McuDataEvent ->
                Log.i("dev2mcu:", event.data)
                val data = Converter.hexStringToBytes(event.data)
                try {
                    serialPort.outputStream.write(data)
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
            CofarSDK.register(dev2McuEventListener)
            CofarSDK.register(Mcu2DevEventListener())
            val protocolListener = ProtocolListener(serialPort)
            thread = Thread(protocolListener)
            thread?.start()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun destroy() {
        thread?.interrupt()
        thread = null
    }


}