package com.bonait.bnframework.modules.home.fragment.mode;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 *
 */
public class SerialManage {
    public volatile static SerialManage _instance;
    public static SerialManage GetInstance(){
        if (_instance == null)
            _instance = new SerialManage();
        return _instance;
    }

    private ScheduledExecutorService scheduledExecutor;//线程池 统一管理保证只有一个
    private ShaoMaSave shaoMaSave;//串口连接 发送 读取对象
    private Queue<String> queueMsg = new ConcurrentLinkedQueue<String>();//线程安全到队列
    private ScheduledFuture sendStrTask;//循环发送队列
    private boolean isConnect = false;//串口是否连接



    private SerialManage(){
        scheduledExecutor = Executors.newScheduledThreadPool(8);//初始化8个线程
    }

    /**
     * 获取线程池
     * @return
     */
    public ScheduledExecutorService getScheduledExecutor(){
        return scheduledExecutor;
    }

    /**
     * 串口初始化
     * @param serialInter 串口接口
     */
    public void init(SerialInter serialInter){
        if (shaoMaSave == null){
            shaoMaSave = new ShaoMaSave();
            /*starSendTask();*///暂时关闭发送任务
        }
        shaoMaSave.addSerialInter(serialInter);
    }

    /**
     * 打开串口
     */
    public void Open(String path,int baudrate,boolean isRead){
        isConnect = shaoMaSave.Open(path,baudrate,isRead);
    }

    public void Open(String path,int baudrate,int dataBits,int stopBits,int parity,boolean isRead){
        isConnect = shaoMaSave.Open(path,baudrate,dataBits,stopBits,parity,isRead);
    }

    /**
     * 发送指令
     * @param msg
     */
    public void send(String msg){
        queueMsg.offer(msg);//向队列添加指令
    }

    /**
     * 关闭串口
     */
    public void Close(){
        shaoMaSave.Close();
    }

    /**
     * 启动发送任务
     */
    private void starSendTask(){
        CancelTask();
        sendStrTask =scheduledExecutor.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                if (!isConnect) return;//串口未连接 退出
                if (shaoMaSave == null) return;//串口未初始化
                String msg = queueMsg.poll();//取出指令
                if (msg == null||"".equals(msg)) return;//无效指令 退出
                shaoMaSave.send(msg);//发送指令
            }
        },0,100, TimeUnit.MILLISECONDS);
    }

    private void CancelTask(){
        if (sendStrTask == null) return;
        sendStrTask.cancel(true);
        try {
            Thread.sleep(100);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        sendStrTask = null;
    }
}
