package com.example.iot_controlhost.model.controller;

import com.example.iot_controlhost.model.Device;
import com.example.iot_controlhost.utils.log.MyLog;

import android_serialport_api.SerialPortUtil;

/**
 * 控制器
 *
 * @Author DuanKaiji
 */
public abstract class Controller extends Device {
    /**
     * 设备电源开关
     */
    protected boolean powerSupply;

    protected static SerialPortUtil serialPortUtil;

    public Controller(String name) {
        super(name);
        serialPortUtil = SerialPortUtil.getInstance(SerialPortUtil.TYPE_CONTROLLER);
    }

    /**
     * 设置开关 需要子类实现
     *
     * @param state 目标状态
     * @return 操作成功与否
     */
    public abstract boolean setPowerSupply(boolean state);

    /**
     * 执行控制器指令
     *
     * @param instruction    指令
     * @param operateContent 操作内容 用于输出日志
     * @return 操作成功与否-发送指令与接收指令相同
     */
    protected boolean executeInstructions(String instruction, String operateContent) {
        return executeInstructions(instruction, instruction, operateContent);
    }


    protected boolean executeInstructions(String instruction, String result, String operateContent) {
        if (!isAvailable()) {
            return false;
        }
        MyLog.controller("操作" + name + "：" + operateContent);
        if (result != null && result.equals(serialPortUtil.sendAndReceiveSerialData(this, instruction))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 执行不等待设备响应的指令。
     */
    protected boolean executeInstructionsNoResponse(String instruction, String operateContent) {
        if (!isAvailable()) {
            return false;
        }
        MyLog.controller("操作" + name + "：" + operateContent);
        return serialPortUtil.sendSerialDataNoResponse(this, instruction);
    }

    public boolean isPowerSupply() {
        return powerSupply;
    }

}
