package com.hboxs.serialport.plc.thread

import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import com.hboxs.serialport.plc.SerialPortSendQueue
import com.hboxs.serialport.plc.frame.RstCommandFrame
import com.quyunshuo.androidbaseframemvvm.base.addressenum.PlcSettingAddressEnum
import com.hboxs.serialport.plc.frame.SetCommandFrame
import com.hboxs.serialport.sbc.VboxSerialPortSendQueue
import com.hboxs.serialport.sbc.frame.VboxCommand
import com.hboxs.serialport.sbc.frame.VboxWriteCommand
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject

class ThreadSettingParam @Inject constructor(): LifecycleObserver  {

    private val TAG = "ThreadGeneralParam"
    var jobM3: Job? = null
        get() = field
    var isActiveM3: Boolean = true
        get() = field
        set(value) {
            field = value
        }

    var jobRM3: Job? = null
        get() = field
    var isActiveRM3: Boolean = true
        get() = field
        set(value) {
            field = value
        }

    /***
     * 01开机
     * 00关机
     * */
    fun startSetM3(data:String) {
        stopSetM3()
        // 启动协程
        jobM3 = CoroutineScope(Dispatchers.Main).launch {
            while (isActiveM3) {
               // SerialPortSendQueue.sendCommand(SetCommandFrame(PlcSettingAddressEnum.M3.address), 10, PlcSettingAddressEnum.M3.address)
                // 执行定时任务的操作
                VboxSerialPortSendQueue.getInstance().sendCommand(VboxWriteCommand(VboxCommand.CMD_OPENORCLOSE, "11110101${data}00"))
                Log.d("backinfo","发生开机指令")
                delay(3000) // 每隔0.3秒重复执行

            }
        }
    }
    fun stopSetM3(){
        jobM3?.cancel()
    }

    fun startRstM3() {
        stopRstM3()
        // 启动协程
        jobRM3 = CoroutineScope(Dispatchers.Main).launch {
            while (isActiveRM3) {
                SerialPortSendQueue.sendCommand(RstCommandFrame(PlcSettingAddressEnum.M3.address), 10, PlcSettingAddressEnum.RM3.address)
                // 执行定时任务的操作
                delay(300) // 每隔0.3秒重复执行
            }
        }
    }
    fun stopRstM3(){
        jobRM3?.cancel()
    }


    /**
     * 关掉线程池
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun destroy() {
        stopSetM3()
    }


}