package com.example.iot_controlhost.utils.mainboard;

import android.os.Build;

import com.example.iot_controlhost.MyApp;
import com.example.iot_controlhost.utils.PollingTask;
import com.example.iot_controlhost.utils.log.MyLog;
import com.ys.mcu7502.Mcu7502;
import com.ys.rkapi.MyManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @Description 亿晟API
 * @Author DuanKaiji
 * @CreateTime 2024年01月05日 14:36:37
 */
public class YSAPI extends API {
    private MyManager manager;

    @Override
    public void init() {
        manager = MyManager.getInstance(MyApp.getAppContext());
        if (-1 == Mcu7502.open()) {
            MyLog.app("亿晟——看门狗初始化失败");
            return;
        }
        String path;
        if (Build.MODEL.contains("rk312")) {
            path = "/sys/devices/misc_power_en.19/mcu";
        } else {
            path = "/sys/devices/platform/misc_power_en/mcu";
        }
        MyLog.app("亿晟——看门狗：" + path);
        if (7 == Mcu7502.enableWatchdog(path)) {
            MyLog.app("设置属性为1，表示启用看门狗");
            setValueToProp("persist.sys.watchdog", "1"); // 设置属性为1，表示启用看门狗
        }
        MyLog.app("亿晟看门狗状态：" + (Mcu7502.getWatchdogStatus() == 0 ? "未启用" : "启用"));
    }

    @Override
    public void shutDown() {
        manager.shutdown();
    }

    @Override
    public void reBoot() {
        manager.reboot();
    }

    @Override
    public void feed() {
        MyLog.app("开始持续喂狗");
        PollingTask.getInstance("FeedDog").startPollingTaskOnIOThread("Feed", 5, () -> {
            if (7 != Mcu7502.feetDog(10)) {
//                MyLog.app("亿晟喂狗失败");
            } else {
//                MyLog.app("亿晟喂狗成功");
            }
        });

    }

    private void closeDogs() {
        Mcu7502.disableWatchdog();
        Mcu7502.close();
        setValueToProp("persist.sys.watchdog", "0");
    }

    public static void setValueToProp(String key, String val) {
        Class<?> classType;
        try {
            classType = Class.forName("android.os.SystemProperties");
            Method method = classType.getDeclaredMethod("set", new Class[]{String.class, String.class});
            method.invoke(classType, new Object[]{key, val});
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
