using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading.Tasks;
using BPASmartClient.Device;
using BPA.Message.Enum;
using BPA.Message;
using BPASmartClient.Helper;
using BPASmartClient.Model.咖啡机.Enum;
using BPASmartClient.Model;
using BPASmartClient.EventBus;
using static BPASmartClient.EventBus.EventBus;
using BPASmartClient.Model.PLC;
using BPASmartClient.Model.单片机;

namespace BPASmartClient.MorktJAKAJC
{
    /*
     * 冰淇淋咖啡机组合套装
     * 物料位置：
     * 1：冰淇料
     * 2：冰淇淋杯
     * 5：咖啡
     * 6：咖啡杯
     * 9: 茶
     * 10: 茶杯
     */
    public class Control_MORKJC : BaseDevice
    {
        GVL_MORKJC mORKD = new GVL_MORKJC();
        //咖啡机主控程序
        //private CoffeeMachine coffeeMachine;
        ////果汁机主控程序
        //private JuicerMachine juicerMachine;
        ////单片机主控程序
        //private ICChipMachine icchipMachine;
        //物料存放位置
        private Dictionary<string, PolymerBatching> batchings = new Dictionary<string, PolymerBatching>();
        //容器位置
        private string holderLoc;
        //主料位置
        private string mainMaterialLoc;
        //子订单ID
        private string subOrderId;

        private bool enableFunny = false;
        private DateTime lastRecvdOrder = DateTime.Now;
        private bool working = false;
        /// <summary>
        /// 果汁机做法，true:热饮，false:冷饮
        /// </summary>
        private bool GuMake = false;

        private void OrderChange(string subid, ORDER_STATUS oRDER_STATUS)
        {
            EventBus.EventBus.GetInstance().Publish(new OrderStatusChangedEvent() { Status = oRDER_STATUS, SubOrderId = subid, deviceClientType = DeviceType });
        }

        //private SerialPortClient commProxy;
        public void ConnectOk()
        {

        }
        ConcurrentQueue<MorkOrderPush> morkOrderPushes = new ConcurrentQueue<MorkOrderPush>();
        public void Init()
        {
            ActionManage.GetInstance.Register(new Action<object>((s) =>
            {
                if (s is DrCoffeeDrinksCode cf)
                {
                    mainMaterialLoc = ((int)cf).ToString();
                    DoCoffee();
                }
            }), "SimCoffee");

            //构建所有商品物料信息
            batchings = PolymerBatching.BuildAll();
            EventBus.EventBus.GetInstance().Subscribe<DRCoffee_CoffeEndCookEvent>(DeviceId, DRCoffee_CoffeEndCookEventHandle);

            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
            //一系列外围基础配置
            var com_Coffee = config.AppSettings.Settings["COM_Coffee"].Value;
            var baud_Coffee = config.AppSettings.Settings["BAUD_Coffee"].Value;
            //咖啡机创建
            //coffeeMachine = new CoffeeMachine(com_Coffee, (BaudRates)Enum.Parse(typeof(BaudRates), baud_Coffee));
            Main();
            ReadData();
            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                while (morkOrderPushes.Count > 0)
                {
                    while (enableFunny) { Thread.Sleep(10); }
                    DeviceProcessLogShow("当前非自嗨模式，允许开工");
                    working = true;
                    if (morkOrderPushes.TryDequeue(out MorkOrderPush order))
                    {
                        DeviceProcessLogShow($"开始制作订单[{order.SortNum}]");



                        //商品类型
                        GOODS_TYPE currentGoodsType = GOODS_TYPE.NEITHER;
                        //子订单ID
                        subOrderId = order.SuborderId;
                        //遍历物料
                        foreach (var item in order.GoodBatchings)
                        {
                            var res = Json<BatchingInfoPar>.Data.orderMaterialDelivery.BatchingInfo.FirstOrDefault(p => p.BatchingId == item.BatchingId);
                            if (res != null)
                            {
                                //获取主料和容器位置
                                switch (batchings[res.BatchingLoc].BatchingClass)
                                {
                                    case BATCHING_CLASS.HOLDER:
                                        holderLoc = res.BatchingLoc;
                                        break;
                                    case BATCHING_CLASS.MAIN_MATERIAL:
                                        // mainMaterialLoc ="1";
                                        mainMaterialLoc = res.BatchingLoc;
                                        //验证商品是咖啡还是冰淇淋
                                        if (ValidateGoodsByBatching(res.BatchingLoc) != GOODS_TYPE.NEITHER)
                                        {
                                            //获取当前物料所属商品类型
                                            currentGoodsType = ValidateGoodsByBatching(res.BatchingLoc);
                                        }
                                        break;
                                }
                            }
                        }

                        //根据商品类型执行具体制作流程
                        switch (currentGoodsType)
                        {
                            case GOODS_TYPE.COFFEE:
                                DoCoffee();
                                break;
                            case GOODS_TYPE.JUICE:
                                GuMake = order.MakeID == "2";
                                DoJuicer();
                                break;
                            case GOODS_TYPE.TEA:
                                DoTea();
                                break;
                            case GOODS_TYPE.WATER:
                                DoWater();
                                break;
                            case GOODS_TYPE.NEITHER:
                                DeviceProcessLogShow("未知的商品类型");
                                break;
                        }
                    }
                    working = false;
                    lastRecvdOrder = DateTime.Now;
                }
                Thread.Sleep(1000);
            }), "订单制作");
        }

        public void Main()
        {
            //咖啡机开启主线程
            //coffeeMachine.Start();
            //开始心跳刷新，根据咖啡机及冰淇淋机来判断
            ThreadManage.GetInstance().StartLong(new Action(() =>
            {
                //IsHealth =
                //         Write.IsConnected &&
                //         MorkCStatus.GetInstance().CanDo &&
                //         JuicerHelper.GetInstance.IsOpen &&
                //         MCUSerialHelper.GetInstance.IsOpen;
                //GeneralConfig.Healthy = true;
                Thread.Sleep(100);
            }), "MORK-IC心跳刷新");
            //ThreadManage.GetInstance().Start(new Action(() =>
            //{
            //    while (!Write.IsConnected)
            //    {
            //        Thread.Sleep(10);
            //    }
            //    //LebaiHelper.GetInstance.Scene(LebaiHelper.SENCE_欢迎);
            //}), "MORK-JC欢迎");
        }

        public void DataParse<T>(T order)
        {
            if (order is MorkOrderPush morkOrderPush)
            {
                morkOrderPushes.Enqueue(morkOrderPush);
            }
        }

        /// <summary>
        /// 验证当前是做咖啡还是做冰淇淋
        /// </summary>
        /// <param name="batchingLoc">物料位置</param>
        private GOODS_TYPE ValidateGoodsByBatching(string batchingLoc)
        {
            if (batchings.ContainsKey(batchingLoc))
                return batchings[batchingLoc].GoodsType;
            return GOODS_TYPE.NEITHER;
        }

        private AutoResetEvent are = new AutoResetEvent(false);

        private T GetStatus<T>(string key)
        {
            if (peripheralStatus.ContainsKey(key))
            {
                if (peripheralStatus[key] != null)
                {
                    return (T)(peripheralStatus[key]);
                }
            }
            return default;
        }

        private void Wait(int value)
        {
            while (!((GetStatus<int>("Get_RobotAO1") == value) && GetStatus<int>("GetProgramStatus") == 0))//判断文件是否已经执行结束 且 文件末端变量值==文件名
            {
                Thread.Sleep(5);
            }
        }
        int[] devStatusBy = new int[2] { 0, 0 };

        /// <summary>
        /// 传感器的输入信号 0:无意义 1：有信号 2：无信号 3：信号不正确
        /// </summary>
        int bSensorInput;
        /// <summary>
        /// 延迟的超时时间
        /// </summary>
        DateTime delayTimeOut;
        /// <summary>
        /// 做咖啡
        /// </summary>
        private void DoCoffee()
        {
            #region 接咖啡流程
            are.Reset();
            // OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COOKING);
            OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COOKING);
            int resultTakeCup = takeCup();
            if (resultTakeCup == 1)
            {
                DeviceProcessLogShow("咖啡杯取杯完成");
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接咖啡 }.Publish();
                // Write("JaKaProgramName",JakaModel.SENCE_接咖啡);
                Wait(int.Parse(JakaModel.SENCE_接咖啡));
                new DRCoffee_MakeCoffeeEvent() { DeviceId = DeviceId, DrinkCode = (DrCoffeeDrinksCode)int.Parse(mainMaterialLoc) }.Publish();  //接咖啡控制 //DrCoffeeDrinksCode.热水
                are.WaitOne(1000 * 180);
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放咖啡杯 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_放咖啡杯));
                int resultputCup = putCup();
                if (resultputCup == 1)
                {
                    //订单状态改变：完成
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                    OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COMPLETED_TAKE);
                }
                else
                {
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                }
            }
            else if (resultTakeCup == 2 || resultTakeCup == 3)
            {
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_初始位));
            }
            #endregion
        }
        /// <summary>
        /// 做茶
        /// </summary>
        private void DoTea()
        {
            #region 接茶流程
            OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COOKING);
            int resultTakeCup = takeCup();
            if (resultTakeCup == 1)
            {
                DeviceProcessLogShow("取茶杯完成");
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接茶 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_接茶));

                new WriteMcu() { TagName = "ServoControl", Address = "1", Value = 105 }.Publish();
                Thread.Sleep(1000);
                new WriteMcu() { TagName = "ServoControl", Address = "1", Value = 130 }.Publish();
                Thread.Sleep(1000);
                new WriteMcu() { TagName = "ServoControl", Address = "1", Value = 105 }.Publish();

                Thread.Sleep(3000);
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接茶_接水 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_接茶_接水));


                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "4" }.Publish();
                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "3" }.Publish();

                Thread.Sleep(100);
                new WriteMcu() { TagName = "OutputControl", Value = true, Address = "3" }.Publish();
                Thread.Sleep(3000);
                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "3" }.Publish();
                Thread.Sleep(100);

                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "4" }.Publish();
                Thread.Sleep(100);
                new WriteMcu() { TagName = "OutputControl", Value = true, Address = "4" }.Publish();
                Thread.Sleep(500);
                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "4" }.Publish();

                Thread.Sleep(50000);

                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放茶水杯 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_放茶水杯));
                int resultputCup = putCup();
                if (resultputCup == 1)
                {
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                    OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COMPLETED_TAKE);
                }
                else
                {
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                }
            }
            else if (resultTakeCup == 2 || resultTakeCup == 3)
            {
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_初始位));
            }
            #endregion
        }

        /// <summary>
        /// 接开水
        /// </summary>
        private void DoWater()
        {
            #region 接水流程
            OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COOKING);
            int resultTakeCup = takeCup();
            if (resultTakeCup == 1)
            {

                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接水 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_接水));

                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "4" }.Publish();


                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "3" }.Publish();
                Thread.Sleep(100);
                new WriteMcu() { TagName = "OutputControl", Value = true, Address = "3" }.Publish();
                Thread.Sleep(3000);
                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "3" }.Publish();
                Thread.Sleep(100);

                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "4" }.Publish();
                Thread.Sleep(100);
                new WriteMcu() { TagName = "OutputControl", Value = true, Address = "4" }.Publish();
                Thread.Sleep(500);
                new WriteMcu() { TagName = "OutputControl", Value = false, Address = "4" }.Publish();

                Thread.Sleep(50000);
                //添加控制接水机构程序

                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放茶水杯 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_放茶水杯));
                int resultputCup = putCup();
                if (resultputCup == 1)
                {
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                    OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COMPLETED_TAKE);
                }
                else
                {
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                }
            }
            else if (resultTakeCup == 2 || resultTakeCup == 3)
            {
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_初始位));
            }
            #endregion
        }
        /// <summary>
        /// 果汁机控制信号
        /// </summary>
        private byte JuicerNum;
        /// <summary>
        /// 做果汁
        /// </summary>
        private void DoJuicer()
        {
            #region 接果汁流程
            are.Reset();
            OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COOKING);
            int resultTakeCup = takeCup();
            if (resultTakeCup == 1)
            {
                int JuicerNum1 = int.Parse(mainMaterialLoc);
                switch (JuicerNum1)
                {
                    case 52:
                        if (GuMake)
                        {
                            JuicerNum = 0x00;
                        }
                        else
                        {
                            JuicerNum = 0x01;
                        }
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接果汁1 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_接果汁1));
                        break;
                    case 53:
                        if (GuMake)
                        {
                            JuicerNum = 0x02;
                        }
                        else
                        {
                            JuicerNum = 0x03;
                        }
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接果汁2 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_接果汁2));
                        break;
                    case 54:
                        if (GuMake)
                        {
                            JuicerNum = 0x04;
                        }
                        else
                        {
                            JuicerNum = 0x05;
                        }
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接果汁3 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_接果汁3));
                        break;
                    case 55:
                        if (GuMake)
                        {
                            JuicerNum = 0x06;
                        }
                        else
                        {
                            JuicerNum = 0x07;
                        }
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接果汁4 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_接果汁4));
                        break;
                    default:
                        JuicerNum = 0x00;
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_接果汁1 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_接果汁1));
                        break;
                }
                var devStatus = GetStatus<int[]>("GetDeviceStatus");
                var devStatus1 = Convert.ToString(devStatus[0], 2);
                var devStatus2 = devStatus[1];

                if (devStatus1.IndexOf("0") == 1 && devStatus2 == 0)
                {
                    if (sensor_Sign(1) == 1)
                    {
                        new WriteJuicer() { Value = JuicerNum }.Publish();
                    }
                    Thread.Sleep(100);
                    devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                    while (!(devStatusBy[1] == 0))
                    {
                        Thread.Sleep(100);
                        devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                        while (devStatusBy.Length != 2)
                        {
                            Thread.Sleep(100);
                            devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                        }
                    }
                    devStatusBy = GetStatus<int[]>("GetDeviceStatus");
                    Thread.Sleep(5000);
                    switch (JuicerNum1)
                    {
                        case 52:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯1 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯1));
                            break;
                        case 53:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯2 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯2));
                            break;
                        case 54:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯3 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯3));
                            break;
                        case 55:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯4 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯4));
                            break;
                        default:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯1 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯1));
                            break;
                    }
                    int resultputCup = putCup();
                    if (resultputCup == 1)
                    {
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_初始位));
                        OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COMPLETED_TAKE);
                    }
                    else
                    {
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_初始位));
                    }
                }
                else
                {
                    switch (JuicerNum1)
                    {
                        case 52:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯1 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯1));
                            break;
                        case 53:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯2 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯2));
                            break;
                        case 54:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯3 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯3));
                            break;
                        case 55:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯4 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯4));
                            break;
                        default:
                            new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放果汁杯1 }.Publish();
                            Wait(int.Parse(JakaModel.SENCE_放果汁杯1));
                            break;
                    }
                    int resultputCup = putCup();
                    if (resultputCup == 1)
                    {
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_初始位));
                        OrderChange(subOrderId, BPA.Message.Enum.ORDER_STATUS.COMPLETED_TAKE);
                    }
                    else
                    {
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_初始位));
                    }
                }
            }
            else if (resultTakeCup == 2 || resultTakeCup == 3)
            {
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_初始位));
            }
            #endregion
        }
        private int getCup_cnt;
        /// <summary>
        /// 取杯流程
        /// </summary>
        /// <returns>0:无意义，1：取杯成功 2：机构有杯子，取杯失败 3：机构没有杯子</returns>
        private int takeCup()
        {
            try
            {
                getCup_cnt = 0;//取杯次数复位
                new WriteJaka() { TagName = "Set_RobotAO1", Value = 0 }.Publish();
                Wait(0);
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_初始位));
                new WriteMcu() { TagName = "OutputControl", Address = "1", Value = true }.Publish();
                Thread.Sleep(10);
                new WriteMcu() { TagName = "OutputControl", Address = "1", Value = true }.Publish();
                new WriteJaka() { TagName = "Set_RobotAO1", Value = 0 }.Publish();
                Wait(0);
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_取杯 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_取杯));
                bSensorInput = sensor_Sign(1);
                if (bSensorInput == 2)
                {
                    Thread.Sleep(100);
                    new WriteMcu() { TagName = "OutputControl", Address = "1", Value = false }.Publish();
                    new WriteMcu() { TagName = "OutputControl", Address = "1", Value = false }.Publish();
                    Thread.Sleep(100);
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_取杯检测 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_取杯检测));
                    DeviceProcessLogShow("落杯器没有纸杯了");
                    return 3;
                }
                if (bSensorInput == 1)
                {
                    Thread.Sleep(100);
                    new WriteMcu() { TagName = "OutputControl", Address = "1", Value = false }.Publish();
                    new WriteMcu() { TagName = "OutputControl", Address = "1", Value = false }.Publish();
                    Thread.Sleep(100);
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_取杯检测 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_取杯检测));
                    bSensorInput = sensor_Sign(1);
                    /*delayTimeOut = DateTime.Now;
                    bSensorInput = sensor_Sign(1);
                    while (bSensorInput == 3)
                    {
                        Thread.Sleep(100);
                        bSensorInput = sensor_Sign(1);
                    }*/
                    while (getCup_cnt < 4 && (bSensorInput == 2 || bSensorInput == 3))
                    {
                        DeviceProcessLogShow($"第{getCup_cnt}次取杯失败");
                        Thread.Sleep(100);
                        new WriteMcu() { TagName = "OutputControl", Address = "1", Value = true }.Publish();
                        new WriteMcu() { TagName = "OutputControl", Address = "1", Value = true }.Publish();
                        Thread.Sleep(100);
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_取杯 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_取杯));
                        getCup_cnt = getCup_cnt + 1;
                        Thread.Sleep(100);
                        new WriteMcu() { TagName = "OutputControl", Address = "1", Value = false }.Publish();
                        new WriteMcu() { TagName = "OutputControl", Address = "1", Value = false }.Publish();
                        Thread.Sleep(100);
                        new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_取杯检测 }.Publish();
                        Wait(int.Parse(JakaModel.SENCE_取杯检测));
                        bSensorInput = sensor_Sign(1);
                    }
                    if (bSensorInput == 1)
                    {
                        return 1;
                    }
                    else
                    {
                        return 2;
                    }
                }
                return 1;
            }
            catch (Exception ex)
            {
                DeviceProcessLogShow(ex.ToString());
                return 0;
            }
        }
        /// <summary>
        /// 放杯
        /// </summary>
        /// <returns>0:无意义 1：执行成功 2：执行失败(传感器还有信号)</returns>
        private int putCup()
        {
            try
            {
                while (checkCup() == 2)
                {
                    Thread.Sleep(100);
                }
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放杯 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_放杯));
                new WriteMcu() { TagName = "OutputControl", Address = "1", Value = true }.Publish();
                Thread.Sleep(10);
                new WriteMcu() { TagName = "OutputControl", Address = "1", Value = true }.Publish();
                Thread.Sleep(10);
                new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_放杯检测 }.Publish();
                Wait(int.Parse(JakaModel.SENCE_放杯检测));
                bSensorInput = sensor_Sign(2);
                delayTimeOut = DateTime.Now;
                while (bSensorInput == 2)
                {
                    Thread.Sleep(100);
                    bSensorInput = sensor_Sign(2);
                    if (DateTime.Now.Subtract(delayTimeOut).TotalSeconds >= 2) return 2;
                }
                if (bSensorInput == 2)
                {
                    DeviceProcessLogShow("放杯失败传感器没有信号");
                    new WriteJaka() { TagName = "JaKaProgramName", Value = JakaModel.SENCE_初始位 }.Publish();
                    Wait(int.Parse(JakaModel.SENCE_初始位));
                    return 1;
                }
                return 1;
            }
            catch (Exception ex)
            {
                DeviceProcessLogShow(ex.ToString());
                return 0;
            }
        }
        private int cnt_Check;

        public override DeviceClientType DeviceType => throw new NotImplementedException();

        /// <summary>
        /// 检测放杯位，是否有杯子
        /// </summary>
        /// <returns>0：无意义 1：没有杯子  2：有杯子 </returns>
        private int checkCup()
        {
            try
            {
                //cnt_Check = 0;
                bSensorInput = sensor_Sign(2);
                if (bSensorInput == 2)
                {
                    DeviceProcessLogShow($"放杯位传感器没有信号:{cnt_Check}");
                    return 1;
                }
                else if (bSensorInput == 1)
                {
                    DeviceProcessLogShow($"放杯位传感器有信号:{cnt_Check}");
                    return 2;
                }
                return 2;
            }
            catch (Exception ex)
            {
                DeviceProcessLogShow(ex.ToString());
                return 0;
            }
        }

        private T McuRead<T>(string tagName, object par)
        {
            new ReadMcu() { DeviceId = DeviceId, TagName = tagName, ReadPar = par };
            if (peripheralStatus.ContainsKey(tagName))
            {
                if (peripheralStatus[tagName] != null)
                {
                    return (T)peripheralStatus[tagName];
                }
            }
            return default;
        }



        /// <summary>
        /// 传感器防抖0.2s内检测20次，
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        private int sensor_Sign(byte num)
        {
            DeviceProcessLogShow($"开始检测{num}号传感器信号");
            int cnt = 0;
            cnt_Check = 0;
            while (true)
            {
                Thread.Sleep(10);
                bSensorInput = McuRead<int>("GetInputStatus", num);
                if (bSensorInput == 1)
                {
                    cnt_Check = cnt_Check + 1;
                    cnt = cnt + 1;
                }
                else if (bSensorInput == 2)
                {
                    cnt_Check = cnt_Check - 1;
                    cnt = cnt + 1;
                }
                if (cnt >= 20)
                {
                    break;
                }

            }
            if (cnt_Check >= 0)
            {
                DeviceProcessLogShow($"{num}传感器有信号:{cnt_Check}");
                return 1;
            }
            else
            {
                DeviceProcessLogShow($"{num}传感器没有信号:{cnt_Check}");
                return 2;
            }
        }
        private void DRCoffee_CoffeEndCookEventHandle(IEvent @event, EventCallBackHandle callBack)
        {
            are.Set();
        }

        public void SimOrder<T>(T simOrder)
        {

        }

        public override void DoMain()
        {

        }

        public override void Stop()
        {

        }

        public override void ReadData()
        {

        }

        public override void MainTask()
        {

        }

        public override void ResetProgram()
        {

        }
    }
}
