using log4net;
using log4net.Repository.Hierarchy;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Configuration;
using System.IO.Ports;
using System.Linq;
using System.Reflection.Metadata;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Markup;
using System.Reflection;
using MasaBlazorApp3.Pojo.Config;
using Microsoft.Extensions.Options;
using LinqToDB.Common;
using MasaBlazorApp3.Util;
using Microsoft.Extensions.Logging;

namespace MasaBlazorApp3.Port
{
    public class PortUtil
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(PortUtil));
        // 抽屉串口
        public SerialPort drawerSerial;
        // can总线串口
        public SerialPort canBusSerial;
        // can总线串口
        public SerialPort canBusSerialTwo;

        // 条码枪串口
        public SerialPort scanCodeSerial;

        //冰箱串口
        public SerialPort fridgeSerial;


        public bool Operate { get; set; }
        public DateTime dateTime { get; set; } = DateTime.Now;
       // //鼠标点击时间
        public DateTime mouseClickTime { get; set; }

        // 当前操作的抽屉号
        public int DrawerNo { get; set; }
        // 当前操作的库位号列表
        public int[] ColNos { get; set; } = new int[] { };
        // 当前操作查数的库位号列表
        public List<int> ColNoLst { get; set; } = new List<int>();
        // 当前操作开药盒的库位号
        public int OpenBoxColNo { get; set; } = 0;

        private readonly PortConfig _portConfig;

        public PortUtil(IOptions<PortConfig> setting)
        {
            _portConfig = setting.Value;
            try
            {
                string DrawerPortPath = _portConfig.drawerPortPath;
                logger.Info($"打开抽屉串口【{DrawerPortPath}】");
                drawerSerial = new SerialPort(DrawerPortPath, 9600, Parity.None, 8);
                //drawerSerial.Open();
                //logger.Info($"抽屉串口打开结果【{drawerSerial.IsOpen}】");
            }
            catch (Exception e)
            {
                logger.Error("抽屉串口打开错误" + e.Message);
            }

            try
            {
                string ScanCodePortPath = _portConfig.scanCodePortPath;
                logger.Info($"打开条码枪串口【{ScanCodePortPath}】");
                scanCodeSerial = new SerialPort(ScanCodePortPath, 9600, Parity.None, 8);
                scanCodeSerial.DataReceived += (object sender, System.IO.Ports.SerialDataReceivedEventArgs e) =>
                {
                    string code = scanCodeSerial.ReadExisting();

                };
                //scanCodeSerial.Open();
                //logger.Info($"条码枪串口打开结果【{scanCodeSerial.IsOpen}】");
            }
            catch (Exception e)
            {
                logger.Error("条码枪串口打开错误" + e.Message);
            }
            if (_portConfig.canBusExsit)
            {
                try
                {
                    string CanBusPortPath = _portConfig.canBusPortPath;
                    logger.Info($"打开can总线串口【{CanBusPortPath}】");
                    canBusSerial = new SerialPort(CanBusPortPath, 57600, Parity.None, 8);
                    //canBusSerial.Open();
                    //logger.Info($"can总线串口打开结果【{canBusSerial.IsOpen}】");
                }
                catch (Exception e)
                {
                    logger.Error("can总线串口打开错误" + e.Message);
                }

            }
            //打开第二个can总线串口
            if (_portConfig.canBusTwoExsit)
            {
                try
                {
                    string CanBusPortPath = _portConfig.canBusPortPathTwo;
                    logger.Info($"打开第二个can总线串口【{CanBusPortPath}】");
                    canBusSerialTwo = new SerialPort(CanBusPortPath, 57600, Parity.None, 8);
                }
                catch (Exception e)
                {
                    logger.Error("第二个can总线串口打开错误" + e.Message);
                }

            }
            if (_portConfig.fridgePortExist)
            {
                try
                {
                    string FridgePortPath = _portConfig.fridgePortPath;
                    logger.Info($"打开冰箱串口【{FridgePortPath}】");
                    fridgeSerial = new SerialPort(FridgePortPath, 9600, Parity.None, 8);
                    //fridgeSerial.Open();
                    //logger.Info($"冰箱串口打开结果【{fridgeSerial.IsOpen}】");
                }
                catch (Exception e)
                {
                    logger.Error("冰箱串口打开错误" + e.Message);
                }
            }
        }


        private byte[] GetBufferByPort(SerialPort serialPort, int length, int timeout)
        {
            int _length = 0;
            DateTime start = DateTime.Now;
            DateTime end = DateTime.Now;
            while (_length != length && end.Subtract(start).TotalMilliseconds < timeout)
            {
                _length = serialPort.BytesToRead;
                end = DateTime.Now;
                //logger.Error($"_length：{_length};length:{length}");
            }
            if (_length != length)
            {
                throw new TimeoutException($"串口【{serialPort.PortName}】交互超时");
            }
            byte[] buffer = new byte[length];
            serialPort.Read(buffer, 0, length);
            return buffer;
        }
        private Task<byte[]> GetBufferByPort(SerialPort serialPort, int length)
        {

            return Task.Run(() => GetBufferByPort(serialPort, length, 3000));
        }


        public static SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
        public void SpeakAsync(string textinfo)
        {
            speechSynthesizer.SpeakAsync(textinfo);
        }



        #region 抽屉串口操作
        // 打开抽屉
        public async Task<byte[]> OpenDrawer(int DrawerNo)
        {
            drawerSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, 0x41, (byte)DrawerNo, 0xee };
            if (_portConfig.drawerProtocol == 485)
            {
                if (_portConfig.totalDrawerCount > 8)
                {
                    if (DrawerNo % 2 == 0)
                    {
                        buffer = new byte[] { 0xaa, 0x21, (byte)(DrawerNo / 2), 0xee };
                    }
                    else
                    {
                        buffer = new byte[] { 0xaa, 0x11, (byte)(DrawerNo / 2 + DrawerNo % 2), 0xee };
                    }
                }
                else
                {
                    buffer = new byte[] { 0xaa, 0x11, (byte)DrawerNo, 0xee };
                }

            }
            logger.Info($"打开抽屉，串口数据：{Convert.ToHexString(buffer)}");
            drawerSerial.Write(buffer, 0, 4);

            return await GetBufferByPort(drawerSerial, 11);
        }

        public async Task<bool> OpenDrawerStatus(int DrawerNo)
        {
            byte[] buffer = await OpenDrawer(DrawerNo);
            int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
            //int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
            //int index = DrawerNo % 2 > 0 ? ((DrawerNo + 1) / 2) + 1 : (DrawerNo / 2) + 1;
            int index = 1;
            if (_portConfig.totalDrawerCount > 8)
            {
                index = DrawerNo % 2 > 0 ? ((DrawerNo + 1) / 2) + 1 : (DrawerNo / 2) + 1;
            }
            else
            {
                index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
            }
            return r[index] == 0;

        }


        // 查询抽屉状态
        public async Task<byte[]> CheckDrawerStatus(int DrawerNo)
        {
            drawerSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, 0x42, 0xee };
            if (_portConfig.drawerProtocol == 485)
            {
                if (_portConfig.totalDrawerCount > 8)
                {
                    //if (DrawerNo > 8)
                    //{
                    if (DrawerNo % 2 == 0)
                    {
                        buffer = new byte[] { 0xaa, 0x22, 0xee };
                    }
                    else
                    {
                        buffer = new byte[] { 0xaa, 0x12, 0xee };
                    }
                    //}
                    //else
                    //{
                    //    buffer = new byte[] { 0xaa, 0x12, 0xee };
                    //}
                }
                else
                {
                    buffer = new byte[] { 0xaa, 0x12, 0xee };
                }
            }

            logger.Info($"查询抽屉状态，串口数据：{Convert.ToHexString(buffer)}");
            drawerSerial.Write(buffer, 0, 3);

            return await GetBufferByPort(drawerSerial, 11);
        }

        public async Task<bool> CheckDrawerStatus2(int DrawerNo)
        {
            byte[] buffer = await CheckDrawerStatus(DrawerNo);
            logger.Info($"查询抽屉状态，返回：{Convert.ToHexString(buffer)}");
            int[] r = buffer.Select(it => Convert.ToInt32(it)).ToArray();
            //int index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
            int index = 1;
            if (_portConfig.totalDrawerCount > 8)
            {
                index = DrawerNo % 2 > 0 ? ((DrawerNo + 1) / 2) + 1 : (DrawerNo / 2) + 1;
            }
            else
            {
                index = DrawerNo > 8 ? DrawerNo - 7 : DrawerNo + 1;
            }
            return r[index] != 0;

        }
        #endregion

        #region can总线串口操作
        #region 耗材板操作
        // 后门状态
        public async Task<byte[]> BackDoorState()
        {

            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, (byte)(_portConfig.doorAddr), 0x02, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);

            return await GetBufferByPort(canBusSerial, 8);

        }
        // 打开电控门储物箱（有灯使能）
        public async Task<byte[]> OpenStorage()
        {
            if (_portConfig.StorageCan == 2)
            {
                canBusSerial.DiscardInBuffer();
                byte[] buffer = new byte[] { 0xaa, (byte)(_portConfig.doorAddr), 0x01, (byte)_portConfig.storageBoxAddr, 0x00, 0x00, 0x00, 0xee };
                canBusSerial.Write(buffer, 0, 8);
                return await GetBufferByPort(canBusSerial, 8);
            }
            else
            {
                canBusSerialTwo.DiscardInBuffer();
                byte[] buffer = new byte[] { 0xaa, (byte)(_portConfig.doorAddr), 0x01, (byte)_portConfig.storageBoxAddr, 0x00, 0x00, 0x00, 0xee };
                canBusSerialTwo.Write(buffer, 0, 8);
                return await GetBufferByPort(canBusSerialTwo, 8);
            }


        }
        // 关闭电控门储物箱（有灯失能）
        public void CloseStorage()
        {
            byte[] buffer = new byte[] { 0xaa, (byte)(_portConfig.doorAddr), 0x04, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 打开普通储物箱（无灯）
        public void OpenStorageBox()
        {
            byte[] buffer = new byte[] { 0xaa, (byte)(_portConfig.storageBoxAddr), 0x03, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 关闭普通储物箱（无灯）
        public void CloseStorageBox()
        {
            byte[] buffer = new byte[] { 0xaa, (byte)(_portConfig.storageBoxAddr), 0x04, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }

        private int[] CheckStorageStatus(int[] data)
        {
            int a = data[0];
            int b = data[1];
            int[] intA = Decimal2Chunks(a);
            int[] intB = Decimal2Chunks(b);
            int[] r = new int[intA.Length + intB.Length];
            Array.Copy(intA, 0, r, 0, intA.Length);
            Array.Copy(intB, 0, r, intA.Length, intB.Length);
            return r;
        }
        private int[] Decimal2Chunks(int d)
        {
            string s = Convert.ToString(d, 2);
            List<int> t = s.Split().Select(it => Convert.ToInt32(it)).Reverse().ToList();
            while (t.Count < 8)
            {
                t.Add(0);
            }
            return t.ToArray();
        }

        #endregion

        #region 单支操作
        // 以抽屉为单位获取抽屉内所有库位的药品数量
        public async Task<byte[]> CheckQuantityByDrawer(int DrawerNo)
        {
            SerialPort serialCanPort = canBusSerial;
            int channel = DrawerNo;
            if (_portConfig.totalDrawerCount > 8)
            {
                if (DrawerNo % 2 == 0)
                {
                    channel = DrawerNo / 2;
                }
                else
                {
                    serialCanPort = canBusSerialTwo;
                    channel = (DrawerNo + 1) / 2;
                }
            }


            serialCanPort.DiscardInBuffer();

            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + channel), 0x01, 0x00, 0x00, 0x00, 0x00, 0xee };

            logger.Info($"单支板发送库位数量查询【{string.Join(",", buffer)}】，调用串口{serialCanPort.PortName}");
            serialCanPort.Write(buffer, 0, 8);

            return await GetBufferByPort(serialCanPort, 13);
        }
        // 获取单个单支板药品数量
        public async Task<byte[]> CheckQuantityByCol(int DrawerNo, int colNo)
        {
            canBusSerial.DiscardInBuffer();

            var channel = Convert.ToInt32((DrawerNo * 10 + colNo).ToString(), 16);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x08, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);

            return await GetBufferByPort(canBusSerial, 8);

        }
        // 以抽屉为单位有药位置亮灯
        public void HasLightOnByDrawer(int DrawerNo)
        {
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x02, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 以抽屉为单位无药位置亮灯
        public void NoLightOnByDrawer(int DrawerNo)
        {
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x03, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 以抽屉为单位灭灯
        public void LightOffByDrawer(int DrawerNo)
        {
            SerialPort serialPort = canBusSerial;
            int channelDrawerNo = DrawerNo;
            if (_portConfig.totalDrawerCount > 8)
            {
                if (DrawerNo % 2 == 0)
                {
                    channelDrawerNo = DrawerNo / 2;
                }
                else
                {
                    serialPort = canBusSerialTwo;
                    channelDrawerNo = (DrawerNo + 1) / 2;
                }
            }
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x06, 0x00, 0x00, 0x00, 0x00, 0xee };
            serialPort.Write(buffer, 0, 8);
        }
        // 以单支板为单位有药位置亮灯
        public async Task HasLightOnByCol(int DrawerNo, int[] ColNos)
        {
            SerialPort serialPort = canBusSerial;
            int channelDrawerNo = DrawerNo;
            if (_portConfig.totalDrawerCount > 8)
            {
                if (DrawerNo % 2 == 0)
                {
                    channelDrawerNo = DrawerNo / 2;
                }
                else
                {
                    serialPort = canBusSerialTwo;
                    channelDrawerNo = (DrawerNo + 1) / 2;
                }
            }
            for (int i = 0; i < ColNos.Length; i++)
            {

                var channel = Convert.ToInt32((channelDrawerNo * 10 + ColNos[i]).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x0a, 0x00, 0x00, 0x00, 0x00, 0xee };
                serialPort.Write(buffer, 0, 8);
                logger.Info($"{serialPort}串口{DrawerNo}号{channelDrawerNo}抽屉{string.Join(',',ColNos)}库位有药位置亮灯发送指令：{Convert.ToHexString(buffer)}");
                await Task.Delay(TimeSpan.FromMilliseconds(20));
            }

        }
        // 以单支板为单位无药位置亮灯
        public async Task NoLightOnByCol(int DrawerNo, int[] ColNos)
        {
            SerialPort serialPort = canBusSerial;
            int channelDrawerNo = DrawerNo;
            if (_portConfig.totalDrawerCount > 8)
            {
                if (DrawerNo % 2 == 0)
                {
                    channelDrawerNo = DrawerNo / 2;
                }
                else
                {
                    serialPort = canBusSerialTwo;
                    channelDrawerNo = (DrawerNo + 1) / 2;
                }
            }
            for (int i = 0; i < ColNos.Length; i++)
            {
                var channel = Convert.ToInt32((channelDrawerNo * 10 + ColNos[i]).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x0b, 0x00, 0x00, 0x00, 0x00, 0xee };
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(TimeSpan.FromMilliseconds(20));
            }
        }
        // 广播灭灯
        public void AllLightOff()
        {
            byte[] buffer = new byte[] { 0xaa, 0xff, 0x07, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
            canBusSerialTwo.Write(buffer, 0, 8);
        }
        //单支板通电
        public void PowerOn()
        {
            if (_portConfig.StorageCan == 2)
            {
                canBusSerial.DiscardInBuffer();
                byte[] buffer = new byte[] { 0xaa, 0x01, 0x05, 0x07, 0x01, 0x00, 0x00, 0xee };
                canBusSerial.Write(buffer, 0, 8);
            }
            else
            {
                canBusSerialTwo.DiscardInBuffer();
                byte[] buffer = new byte[] { 0xaa, 0x01, 0x05, 0x07, 0x01, 0x00, 0x00, 0xee };
                canBusSerialTwo.Write(buffer, 0, 8);
            }
        }
        //单支板断电
        public void PowerOff()
        {
            if (_portConfig.StorageCan == 2)
            {
                canBusSerial.DiscardInBuffer();
                byte[] buffer = new byte[] { 0xaa, 0x01, 0x05, 0x07, 0x00, 0x00, 0x00, 0xee };
                canBusSerial.Write(buffer, 0, 8);
            }
            else
            {
                canBusSerialTwo.DiscardInBuffer();
                byte[] buffer = new byte[] { 0xaa, 0x01, 0x05, 0x07, 0x00, 0x00, 0x00, 0xee };
                canBusSerialTwo.Write(buffer, 0, 8);
            }

        }
        #endregion

        #region 药盒操作
        // 指定药盒指示灯开启使能开锁
        public async Task BoxLockLightOn(int DrawerNo, int[] ColNos)
        {
            for (int i = 0; i < ColNos.Length; i++)
            {

                var channel = Convert.ToInt32((DrawerNo * 10 + ColNos[i]).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x03, 0x00, 0x00, 0x00, 0x00, 0xee };
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(TimeSpan.FromMilliseconds(20));
            }
        }
        // 指定药盒指示灯开启失能开锁
        public async Task BoxLockLightOff(int DrawerNo, int[] ColNos)
        {
            for (int i = 0; i < ColNos.Length; i++)
            {
                var channel = Convert.ToInt32((DrawerNo * 10 + ColNos[i]).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x04, 0x00, 0x00, 0x00, 0x00, 0xee };
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(TimeSpan.FromMilliseconds(20));
            }
        }
        // 指定药盒状态查询
        public async Task<byte[]> BoxLockState(int DrawerNo, int ColNo)
        {
            canBusSerial.DiscardInBuffer();
            var channel = Convert.ToInt32((DrawerNo * 10 + ColNo).ToString(), 16);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x02, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);

            return await GetBufferByPort(canBusSerial, 8);

        }
        // 以抽屉为单位药盒指示灯开启使能开锁
        public async Task BoxLockLightOnByDrawer(int DrawerNo)
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x04, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 以抽屉为单位药盒指示灯开启失能开锁
        public async Task BoxLockLightOffByDrawer(int DrawerNo)
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x05, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }

        /// <summary>
        /// 开指定库位的药盒
        /// </summary>
        /// <param name="ColNo"></param>
        /// <returns></returns>
        public async Task<bool> OpenBoxByColNo(int colNo)
        {
            if (colNo > 0)
            {
                canBusSerial.DiscardInBuffer();
                int ColNo = colNo;
                int[] iNum = new int[] { 4, 2, 1 };
                var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2];
                decimal decolNO = (decimal)ColNo;
                var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)channel, 5, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
                //byte[] buffer = new byte[] { 0xaa, 0x11, 0x05,0x01, 0x00,0x00,0x00,0xee};
                logger.Info($"开药盒{DrawerNo}-{ColNo}【{Convert.ToHexString(buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
                byte[] retBuffer = await GetBufferByPort(canBusSerial, 8);
                logger.Info($"开药盒返回{ColNo}【{Convert.ToHexString(retBuffer)}】");
                int[] r = retBuffer.Select(it => Convert.ToInt32(it)).ToArray();
                if (r[4] > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }
        /// <summary>
        /// 打开药盒
        /// </summary>
        /// <param name="ColNo"></param>
        /// <returns></returns>
        public async Task OpenBox()
        {
            for (int i = 0; i < ColNos.Length; i++)
            {
                canBusSerial.DiscardInBuffer();
                int ColNo = ColNos[i];
                int[] iNum = new int[] { 4, 2, 1 };
                var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2];
                decimal decolNO = (decimal)ColNo;
                var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)channel, 5, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };
                //byte[] buffer = new byte[] { 0xaa, 0x11, 0x05,0x01, 0x00,0x00,0x00,0xee};
                logger.Info($"{Convert.ToHexString(buffer)}");
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(800);
            }

        }
        // 以抽屉为单位药盒指示灯开启使能开锁
        public async Task BoxLockLightOnByDrawer()
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x04, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 以抽屉为单位药盒指示灯开启失能开锁
        public async Task BoxLockLightOffByDrawer()
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xaa, (byte)(0xf0 + DrawerNo), 0x05, 0x00, 0x00, 0x00, 0x00, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }



        #endregion

        private string trim(string text)
        {
            //此处使用了转义字符如：\',\",\\，分别表示单引号，双引号，反斜杠
            char[] TrimChar = { ' ', '-', '\'', '\"', '\\', '(', ')', '（', '）', '①', '②' };
            return text.Trim(TrimChar);
        }

        #region 2.4寸汉显屏
        // 基础数据写入方法
        public async void WriteChannelInfo(int type, string content, int drawerNo, int colNo)
        {

            canBusSerial.DiscardInBuffer();
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            byte[] contentBuf = Encoding.GetEncoding("gb2312").GetBytes(trim(content));
            int channel = (drawerNo * 10 + colNo);
            if (contentBuf.Length % 2 != 0)
            {
                Array.Resize(ref contentBuf, contentBuf.Length + 1);
            }
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 1, (byte)type, 0, 0, 0, 0xee };
            canBusSerial.Write(buffer, 0, 8);
            await Task.Delay(20);
            buffer[4] = 1;
            for (int i = 0; i < contentBuf.Length; i += 2)
            {
                buffer[5] = contentBuf[i];
                buffer[6] = contentBuf[i + 1];
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(20);
            }
            buffer[4] = 2;
            buffer[5] = 0;
            buffer[6] = 0;
            canBusSerial.Write(buffer, 0, 8);
            await Task.Delay(20);
        }

        // 清除显示内容
        public void ClearContent(int drawerNo, int colNo)
        {
            canBusSerial.DiscardInBuffer();
            int channel = (drawerNo * 10 + colNo);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 4, 0, 0, 0, 0, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 刷新显示内容
        public void ShowContent(int drawerNo, int colNo)
        {
            canBusSerial.DiscardInBuffer();
            int channel = (drawerNo * 10 + colNo);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 2, 0, 0, 0, 0, 0xee };
            canBusSerial.Write(buffer, 0, 8);
        }
        // 取药或者加药亮灯
        public void TakeQuantity(int drawerNo, int colNo, int quantity, int stock)
        {
            canBusSerial.DiscardInBuffer();
            int channel = (drawerNo * 10 + colNo);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 6, 0, 0, 0, 0, 0xee };
            buffer[3] = (byte)(quantity >> 8);
            buffer[4] = (byte)(quantity & 0xff);
            buffer[5] = (byte)(stock >> 8);
            buffer[6] = (byte)(stock & 0xff);
            canBusSerial.Write(buffer, 0, 8);
        }
        // 写入数量
        public void WriteQuantity(int drawerNo, int colNo, int quantity)
        {
            canBusSerial.DiscardInBuffer();
            int channel = (drawerNo * 10 + colNo);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x21, 0, 0, 0, 0, 0xee };
            buffer[5] = (byte)(quantity >> 8);
            buffer[6] = (byte)(quantity & 0xff);
            canBusSerial.Write(buffer, 0, 8);
        }

        //清屏
        public void ClearContentMethod(int drawerNo, int colNo)
        {
            decimal deColNo = colNo;
            //var channel = drawerNo * 10 + Math.Ceiling(deColNo / 3);
            int[] iNum = new int[] { 3, 2, 1 };
            var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
            var bColNo = Convert.ToInt32((iNum[colNo2] + 10).ToString(), 16);
            //var index = Convert.ToInt32(((colNo % 3 == 0 ? 3 : colNo % 3)+10).ToString(),16);
            int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x09, (byte)bColNo, 0, 0, 0, 0xee };
            canBusSerial.Write(buffer, 0, 8);
            logger.Info($"清屏指令：{Convert.ToHexString(buffer)}");
        }
        //刷新内容
        public async Task ShowContentMethod(int drawerNo, int colNo)
        {
            int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
            byte[] buffer = new byte[] { 0xaa, (byte)channel, 0x0c, 0x00, 0x00, 0x00, 0x00, 0xee };
            logger.Info($"刷新内容指令：{Convert.ToHexString(buffer)}");
            canBusSerial.Write(buffer, 0, 8);
        }
        // 基础数据写入方法
        public async Task WriteChannelInfoMethod(int type, string content, int drawerNo, int colNo)
        {
            try
            {
                canBusSerial.DiscardInBuffer();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                if (content.Length > 10)
                {
                    content = content.Substring(0, 10);
                }
                byte[] contentBuf = Encoding.GetEncoding("gb2312").GetBytes(trim(content));
                int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
                int[] iNum = new int[] { 3, 2, 1 };
                var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2] + 160;
                //var index = (colNo % 3 == 0 ? 3 : colNo % 3)+160;
                if (contentBuf.Length % 2 != 0)
                {
                    Array.Resize(ref contentBuf, contentBuf.Length + 1);
                }
                byte[] buffer = new byte[] { 0xaa, (byte)channel, (byte)bColNo, (byte)type, 0, 0, 0, 0xee };


                canBusSerial.Write(buffer, 0, 8);
                logger.Info($"开始写标签指令：{Convert.ToHexString(buffer)}");
                Thread.Sleep(20);
                buffer[4] = 1;
                for (int i = 0; i < contentBuf.Length; i += 2)
                {
                    buffer[5] = contentBuf[i];
                    buffer[6] = contentBuf[i + 1];
                    canBusSerial.Write(buffer, 0, 8);
                    logger.Info($"写标签指令：{Convert.ToHexString(buffer)}");
                    Thread.Sleep(50);
                }
                buffer[4] = 2;
                buffer[5] = 0;
                buffer[6] = 0;
                canBusSerial.Write(buffer, 0, 8);
                logger.Info($"结束写标签指令：{Convert.ToHexString(buffer)}");
                Thread.Sleep(20);

            }
            catch (Exception ex)
            {
                logger.Info($"2.4寸汉显屏异常：ex:{ex.Message}");
            }
        }

        public async Task WriteQuantityMethod(int quantity, int drawerNo, int colNo)
        {
            try
            {
                logger.Info($"写数量：{drawerNo}-{colNo}：{quantity}");
                canBusSerial.DiscardInBuffer();
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                string strQuantity = quantity.ToString("X");
                if (strQuantity.Length % 2 != 0)
                {
                    strQuantity = "0" + strQuantity;
                }
                int channel = Convert.ToInt32((drawerNo * 10 + Math.Ceiling((decimal)colNo / 3)).ToString(), 16);
                int[] iNum = new int[] { 3, 2, 1 };
                var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2] + 160;
                byte[] buffer = new byte[] { 0xaa, (byte)channel, (byte)bColNo, 0xf2, 01, 0, 0, 0xee };
                if (strQuantity.Length >= 4)
                {
                    buffer[5] = Convert.ToByte(strQuantity.Substring(0, 2), 16);
                    buffer[6] = Convert.ToByte(strQuantity.Substring(2, 2), 16);
                }
                else
                {

                    buffer[6] = Convert.ToByte(strQuantity.Substring(0, 2), 16);
                }
                canBusSerial.Write(buffer, 0, 8);
                logger.Info($"写标签指令：{Convert.ToHexString(buffer)}");
            }
            catch (Exception ex)
            {
                logger.Info($"写标签数量异常：ex:{ex.Message}");
            }
        }

        #endregion

        #region 回收箱操作
        // 打开回收箱
        public async Task<byte[]> OpenRecover()
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xAA, 0x9A, 0x04, 0x00, 0x00, 0x00, 0x00, 0xEE };
            canBusSerial.Write(buffer, 0, 8);

            return await GetBufferByPort(canBusSerial, 8);
        }
        // 回收箱状态查询
        public async Task<byte[]> CheckRecoverStatus()
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xAA, 0x9A, 0x03, 0x00, 0x00, 0x00, 0x00, 0xEE };
            canBusSerial.Write(buffer, 0, 8);

            return await GetBufferByPort(canBusSerial, 8);
        }
        // 回收箱回收数量查询
        public async Task<byte[]> CheckRecoverQuantity(int ColNo)
        {
            canBusSerial.DiscardInBuffer();
            byte[] buffer = new byte[] { 0xAA, 0x9A, (byte)(ColNo > 3 ? 2 : 1), 0x00, 0x00, 0x00, 0x00, 0xEE };
            canBusSerial.Write(buffer, 0, 8);

            return await GetBufferByPort(canBusSerial, 8);
        }
        #endregion

        #region 称重操作
        // 以板子为单位获取抽屉内所有库位的药品数量
        public async Task<byte[]> CheckQuantityByAddr(int DrawerNo)
        {

            canBusSerial.DiscardInBuffer();
            var channel = Convert.ToInt32((DrawerNo * 10 + 1).ToString(), 16);
            byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x28, 0x00, 0x00, 0x00, 0x00, 0xee };
            logger.Info($"称重发送库位数量查询1【{string.Join(",", buffer)}】");
            canBusSerial.Write(buffer, 0, 8);
            byte[] result1 = await GetBufferByPort(canBusSerial, 8);


            var channel2 = Convert.ToInt32((DrawerNo * 10 + 2).ToString(), 16);
            byte[] buffer2 = new byte[] { 0xaa, (byte)(channel2), 0x28, 0x00, 0x00, 0x00, 0x00, 0xee };
            logger.Info($"称重发送库位数量查询2【{string.Join(",", buffer2)}】");
            canBusSerial.Write(buffer2, 0, 8);
            byte[] result2 = await GetBufferByPort(canBusSerial, 8);

            byte[] res = new byte[6];
            Array.Copy(result1, 3, res, 0, 3);
            Array.Copy(result2, 3, res, 3, 3);

            return res;

        }

        // 以板子为单位获取抽屉内所有库位的药品数量
        public async Task<int[]> CheckQuantityByAddr2(int DrawerNo, int[] ColNos)
        {


            int[] res = new int[6];
            for (int i = 0; i < ColNos.Length; i++)
            {
                canBusSerial.DiscardInBuffer();
                var index = ColNos[i] > 3 ? 2 : 1;
                var lock1 = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3;
                var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)lock1, 0x00, 0x00, 0x00, 0xee };

                logger.Info($"称重发送库位数量查询1【{string.Join(",", buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
                byte[] result = await GetBufferByPort(canBusSerial, 8);
                logger.Info($"称重发送库位数量查询1返回结果【{string.Join(",", result)}】");
                byte[] hl = result.Skip(3).Take(2).ToArray();
                int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                res[ColNos[i] - 1] = quantity;
            }

            return res;

        }

        // 指定药盒指示灯开启使能开锁
        public async Task BoxLockLightOn2(int DrawerNo, int[] ColNos)
        {
            for (int i = 0; i < ColNos.Length; i++)
            {
                var index = ColNos[i] > 3 ? 2 : 1;
                var lock1 = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3;
                var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x03, (byte)lock1, 0x00, 0x00, 0x00, 0xee };
                logger.Info($"称重发送药盒使能【{string.Join(",", buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(TimeSpan.FromMilliseconds(500));
            }
        }
        // 指定药盒指示灯开启失能开锁
        public async Task BoxLockLightOff2(int DrawerNo, int[] ColNos)
        {
            canBusSerial.DiscardInBuffer();
            for (int i = 0; i < ColNos.Length; i++)
            {
                var index = ColNos[i] > 3 ? 2 : 1;
                var lock1 = ColNos[i] % 3 == 0 ? 3 : ColNos[i] % 3;
                var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x04, (byte)lock1, 0x00, 0x00, 0x00, 0xee };
                logger.Info($"称重发送药盒失能【{string.Join(",", buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
                await Task.Delay(TimeSpan.FromMilliseconds(50));
            }
        }

        public async Task ClearCount(int DrawerNo, int ColNo)
        {
            try
            {
                canBusSerial.DiscardInBuffer();
                int[] iNum = new int[] { 3, 2, 1 };
                var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2];
                decimal decolNO = (decimal)ColNo;
                var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x25, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };

                logger.Info($"称重发送清空计数【{Convert.ToHexString(buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
            }
            catch (Exception ex)
            {
                logger.Info($"操作发生异常：ex:{ex.Message},方法名：ClearCount；参数：{DrawerNo}，{ColNo}");
            }
        }

        public async Task SetNumCount(int DrawerNo, int ColNo, int Quantity)
        {
            try
            {
                canBusSerial.DiscardInBuffer();
                int[] iNum = new int[] { 3, 2, 1 };
                var colNo2 = ColNo % 3 > 0 ? (ColNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2];
                decimal decolNO = (decimal)ColNo;
                var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);
                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x26, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };

                buffer[4] = (byte)(Quantity & 0xff);
                //buffer[4] = (byte)(Quantity >> 8);
                //buffer[5] = (byte)(Quantity & 0xff);


                logger.Info($"标定数量【{Convert.ToHexString(buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
            }
            catch (Exception ex)
            {
                logger.Info($"操作发生异常：ex:{ex.Message},方法名：SetNumCount；参数：{DrawerNo}，{ColNo},{Quantity}");
            }
        }

        // 以板子为单位获取抽屉内所有库位的药品数量
        public async Task<byte[]> CheckQuantityByAddr()
        {

            canBusSerial.DiscardInBuffer();
            var channel = Convert.ToInt32((DrawerNo * 10 + 1).ToString(), 16);
            byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x28, 0x00, 0x00, 0x00, 0x00, 0xee };
            logger.Info($"称重发送库位数量查询1【{Convert.ToHexString(buffer)}】");
            canBusSerial.Write(buffer, 0, 8);
            byte[] result1 = await GetBufferByPort(canBusSerial, 8);


            var channel2 = Convert.ToInt32((DrawerNo * 10 + 2).ToString(), 16);
            byte[] buffer2 = new byte[] { 0xaa, (byte)(channel2), 0x28, 0x00, 0x00, 0x00, 0x00, 0xee };
            logger.Info($"称重发送库位数量查询2【{Convert.ToHexString(buffer2)}】");
            canBusSerial.Write(buffer2, 0, 8);
            byte[] result2 = await GetBufferByPort(canBusSerial, 8);

            byte[] res = new byte[6];
            Array.Copy(result1, 3, res, 0, 3);
            Array.Copy(result2, 3, res, 3, 3);

            return res;

        }
        // 以板子为单位获取抽屉内所有库位的药品数量
        public async Task<int[]> CheckQuantityByAddrForMulti()
        {


            int[] res = new int[9];
            for (int i = 0; i < ColNoLst.Count; i++)
            {
                Thread.Sleep(200);
                canBusSerial.DiscardInBuffer();
                int colNo = ColNoLst[i];
                int[] iNum = new int[] { 3, 2, 1 };
                var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2];
                decimal decolNO = (decimal)colNo;
                var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);

                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };

                logger.Info($"称重发送库位数量查询{DrawerNo}-{ColNoLst[i]}【{Convert.ToHexString(buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
                byte[] result = await GetBufferByPort(canBusSerial, 8);
                logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
                byte[] hl = result.Skip(4).Take(2).ToArray();
                var r = Convert.ToHexString(result).Substring(8, 1);
                int quantity = 0;
                if (r == "8")
                {
                    hl[0] -= 0x80;
                    quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                    logger.Info($"获取值为负数{quantity}");
                    quantity = 0 - quantity;
                }
                else
                {
                    quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                    logger.Info($"获取值为正数{quantity}");
                }

                res[ColNoLst[i] - 1] = quantity;
            }

            return res;

        }
        //获取单个称重药合的药品数量   --查数
        public async Task<int> CheckQuantityForSingle(int colNo)
        {
            //await Task.Delay(300);
            //canBusSerial.DiscardInBuffer();
            //var index = colNo % 3 == 0 ? 3 : colNo % 3;
            //var lock1 = colNo <= 3 ? 3 : colNo >= 7 ? 1 : 2;
            //var channel = Convert.ToInt32((DrawerNo * 10 + index).ToString(), 16);


            canBusSerial.DiscardInBuffer();
            int[] iNum = new int[] { 3, 2, 1 };
            var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
            var bColNo = iNum[colNo2];
            decimal decolNO = (decimal)colNo;
            var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);

            byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };

            logger.Info($"称重发送库位数量查询{DrawerNo}-{colNo}【{Convert.ToHexString(buffer)}】");
            canBusSerial.Write(buffer, 0, 8);
            byte[] result = await GetBufferByPort(canBusSerial, 8);
            byte[] hl = result.Skip(4).Take(2).ToArray();
            var r = Convert.ToHexString(result).Substring(8, 1);
            logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");

            if (r == "8")
            {
                hl[0] -= 0x80;
                int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                logger.Info($"获取值为负数{quantity}");
                return 0 - quantity;
            }
            else
            {
                int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                logger.Info($"获取值为正数{quantity}");
                return quantity;
            }

        }
        //获取单个称重药合的药品数量---标定（标定查数与库位查数区别在于用不用忽略0x80）
        public async Task<int> CheckQuantityForBiaoDing(int colNo)
        {
            canBusSerial.DiscardInBuffer();
            int[] iNum = new int[] { 3, 2, 1 };
            var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
            var bColNo = iNum[colNo2];
            decimal decolNO = (decimal)colNo;
            var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);

            byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };

            logger.Info($"称重发送库位数量查询{DrawerNo}-{colNo}【{Convert.ToHexString(buffer)}】");
            canBusSerial.Write(buffer, 0, 8);
            byte[] result = await GetBufferByPort(canBusSerial, 8);
            logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
            byte[] hl = result.Skip(4).Take(2).ToArray();
            int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);

            return quantity;

        }
        // 以板子为单位获取抽屉内所有库位的药品数量
        public async Task<int[]> CheckQuantityByAddr2()
        {


            int[] res = new int[9];
            for (int i = 0; i < ColNos.Length; i++)
            {
                await Task.Delay(300);
                canBusSerial.DiscardInBuffer();
                int colNo = ColNos[i];
                int[] iNum = new int[] { 3, 2, 1 };
                var colNo2 = colNo % 3 > 0 ? (colNo % 3) - 1 : 2;
                var bColNo = iNum[colNo2];
                decimal decolNO = (decimal)colNo;
                var channel = Convert.ToInt32((DrawerNo * 10 + Math.Ceiling(decolNO / 3)).ToString(), 16);

                byte[] buffer = new byte[] { 0xaa, (byte)(channel), 0x27, (byte)bColNo, 0x00, 0x00, 0x00, 0xee };

                logger.Info($"称重发送库位数量查询{DrawerNo}-{ColNos[i]}【{Convert.ToHexString(buffer)}】");
                canBusSerial.Write(buffer, 0, 8);
                byte[] result = await GetBufferByPort(canBusSerial, 8);
                logger.Info($"称重发送库位数量查询返回结果【{Convert.ToHexString(result)}】");
                byte[] hl = result.Skip(4).Take(2).ToArray();
                //int quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                var r = Convert.ToHexString(result).Substring(8, 1);
                int quantity = 0;
                if (r == "8")
                {
                    hl[0] -= 0x80;
                    quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                    logger.Info($"获取值为负数{quantity}");
                    quantity = 0 - quantity;
                }
                else
                {
                    quantity = BitConverter.ToInt16(hl.Reverse().ToArray(), 0);
                    logger.Info($"获取值为正数{quantity}");
                }


                res[ColNos[i] - 1] = quantity;
            }

            return res;

        }

        #endregion  称重操作
        #endregion

        #region 冰箱
        /// <summary>
        /// 冰箱使能
        /// </summary>
        /// <returns></returns>
        public async Task FridegOpen(int iIndex)
        {
            try
            {
                fridgeSerial.DiscardInBuffer();
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] buffer = new byte[] { bAddress, 0x06, 0x10, 0xD4, 0x00, 0x01, 0x0C, 0xF2 };
                //byte[] buffer = new byte[] { 0x01, 0x06, 0x10, 0xD4, 0x00, 0x01 };
                ////获取数组CRC校验码
                //byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                ////Array.Reverse(byteDate);
                //int dataLength = buffer.Length;
                //Array.Resize(ref buffer, dataLength + byteDate.Length);
                //for (int i = 0; i < byteDate.Length; i++)
                //{
                //    buffer[dataLength + i] = byteDate[i];
                //}
                logger.Info($"冰箱使能【{Convert.ToHexString(buffer)}】");
                fridgeSerial.Write(buffer, 0, 8);
                await Task.Delay(80);
            }
            catch (Exception ex)
            {
                logger.Info($"冰箱使能发生异常：ex:{ex.Message}");
            }
        }
        /// <summary>
        /// 冰箱失能
        /// </summary>
        /// <returns></returns>
        public async Task FridgeOff(int iIndex)
        {
            try
            {
                fridgeSerial.DiscardInBuffer();
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] buffer = new byte[] { bAddress, 0x06, 0x10, 0xD4, 0x00, 0x00, 0xCD, 0x32 };
                //byte[] buffer = new byte[] { 0x01, 0x06, 0x10, 0xD4, 0x00, 0x01 };
                ////获取数组CRC校验码
                //byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                ////Array.Reverse(byteDate);
                //int dataLength = buffer.Length;
                //Array.Resize(ref buffer, dataLength + byteDate.Length);
                //for (int i = 0; i < byteDate.Length; i++)
                //{
                //    buffer[dataLength + i] = byteDate[i];
                //}
                logger.Info($"冰箱失能【{Convert.ToHexString(buffer)}】");
                fridgeSerial.Write(buffer, 0, 8);
                await Task.Delay(80);
            }
            catch (Exception ex)
            {
                logger.Info($"冰箱失能发生异常：ex:{ex.Message}");
            }
        }
        /// <summary>
        /// 冰箱报警使能
        /// </summary>
        /// <returns></returns>
        public async Task FridgeAlarmOn(int iIndex)
        {
            try
            {
                fridgeSerial.DiscardInBuffer();
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] buffer = new byte[] { bAddress, 0x06, 0x10, 0xD5, 0x00, 0x01, 0x5D, 0x32 };
                //byte[] buffer = new byte[] { 0x01, 0x06, 0x10, 0xD5, 0x00, 0x01 };
                ////获取数组CRC校验码
                //byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                ////Array.Reverse(byteDate);
                //int dataLength = buffer.Length;
                //Array.Resize(ref buffer, dataLength + byteDate.Length);
                //for (int i = 0; i < byteDate.Length; i++)
                //{
                //    buffer[dataLength + i] = byteDate[i];
                //}
                logger.Info($"冰箱报警使能【{Convert.ToHexString(buffer)}】");
                fridgeSerial.Write(buffer, 0, 8);
                await Task.Delay(80);
            }
            catch (Exception ex)
            {
                logger.Info($"冰箱报警使能发生异常：ex:{ex.Message}");
            }

        }

        /// <summary>
        /// 冰箱报警失能
        /// </summary>
        /// <returns></returns>
        public async Task FridgeAlarmOff(int iIndex)
        {
            try
            {
                fridgeSerial.DiscardInBuffer();
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] buffer = new byte[] { bAddress, 0x06, 0x10, 0xD5, 0x00, 0x00, 0x9C, 0xF2 };
                //byte[] buffer = new byte[] { 0x01, 0x06, 0x10, 0xD5, 0x00, 0x00 };
                ////获取数组CRC校验码
                //byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                ////Array.Reverse(byteDate);
                //int dataLength = buffer.Length;
                //Array.Resize(ref buffer, dataLength + byteDate.Length);
                //for (int i = 0; i < byteDate.Length; i++)
                //{
                //    buffer[dataLength + i] = byteDate[i];
                //}
                logger.Info($"冰箱报警失能【{Convert.ToHexString(buffer)}】");
                fridgeSerial.Write(buffer, 0, 8);
                await Task.Delay(80);
            }
            catch (Exception ex)
            {
                logger.Info($"冰箱报警失能发生异常：ex:{ex.Message}");
            }
        }
        /// <summary>
        /// 冰箱温度设定最小
        /// </summary>
        /// <returns></returns>
        public async Task FridgeMinSetting(float min, int iIndex)
        {
            try
            {

                int iMix = Convert.ToInt32(min * 10);
                fridgeSerial.DiscardInBuffer();
                //byte[] bufferMin = new byte[] { 0x01, 0x06, 0x10, 0xC9, 0x00, 0x15, 0x9C, 0xFB };
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] bufferMin = new byte[] { bAddress, 0x06, 0x10, 0xC9, 0x00, (byte)(iMix & 0xff) };
                //获取数组CRC校验码
                byte[] byteDate = CRC16MODBUS.CrcModBus(bufferMin);
                //Array.Reverse(byteDate);
                int dataLength = bufferMin.Length;
                Array.Resize(ref bufferMin, dataLength + byteDate.Length);
                for (int i = 0; i < byteDate.Length; i++)
                {
                    bufferMin[dataLength + i] = byteDate[i];
                }
                logger.Info($"冰箱温度设定Min:【{Convert.ToHexString(bufferMin)}】");
                fridgeSerial.Write(bufferMin, 0, 8);
            }
            catch (Exception ex)
            {
                logger.Info($"获取冰箱温度发生异常：ex:{ex.Message}");
            }
        }
        /// <summary>
        /// 冰箱温度设定最大
        /// </summary>
        /// <returns></returns>
        public async Task FridgeMaxSetting(float max, int iIndex)
        {
            try
            {
                int iMax = Convert.ToInt32(max * 10);
                fridgeSerial.DiscardInBuffer();
                //byte[] bufferMin = new byte[] { 0x01, 0x06, 0x10, 0xC9, 0x00, 0x15, 0x9C, 0xFB };
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] bufferMax = new byte[] { bAddress, 0x06, 0x10, 0xC8, 0x00, (byte)(iMax & 0xff) };
                //获取数组CRC校验码
                byte[] byteDate = CRC16MODBUS.CrcModBus(bufferMax);
                //Array.Reverse(byteDate);
                int dataLength = bufferMax.Length;
                Array.Resize(ref bufferMax, dataLength + byteDate.Length);
                for (int i = 0; i < byteDate.Length; i++)
                {
                    bufferMax[dataLength + i] = byteDate[i];
                }
                logger.Info($"冰箱温度设定Max:【{Convert.ToHexString(bufferMax)}】");
                fridgeSerial.Write(bufferMax, 0, 8);
            }
            catch (Exception ex)
            {
                logger.Info($"获取冰箱温度发生异常：ex:{ex.Message}");
            }
        }
        /// <summary>
        /// 获取冰箱温度
        /// </summary>
        /// <returns></returns>
        public async Task<float> GetFridgeTemperature(int iIndex)
        {
            float temperature = 0.0f;
            try
            {
                fridgeSerial.DiscardInBuffer();
                byte bAddress;
                if (iIndex == 1)
                {
                    bAddress = 0x01;
                }
                else
                {
                    bAddress = 0x02;
                }
                byte[] buffer = new byte[] { bAddress, 0x03, 0x10, 0x02, 0x00, 0x01, 0x21, 0x0A };
                //byte[] buffer = new byte[] { 0x01, 0x03, 0x10, 0x02, 0x00, 0x01 };

                ////获取数组CRC校验码
                //byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                ////Array.Reverse(byteDate);
                //int dataLength = buffer.Length;
                //Array.Resize(ref buffer, dataLength + byteDate.Length);
                //for (int i = 0; i < byteDate.Length; i++)
                //{
                //    buffer[dataLength + i] = byteDate[i];
                //}

                logger.Info($"获取冰箱温度【{Convert.ToHexString(buffer)}】");
                fridgeSerial.Write(buffer, 0, 8);

                byte[] retByte = await GetBufferByPort(fridgeSerial, 7);

                logger.Info($"获取冰箱温度返回【{Convert.ToHexString(retByte)}】");

                if (retByte != null && retByte.Length >= 7)
                {
                    var hight = retByte[3];
                    var low = retByte[4];
                    int iHight = Convert.ToInt32(hight << 8);
                    int iLow = Convert.ToInt32(retByte[4]);
                    temperature = Convert.ToSingle(iHight + iLow) / 10;
                }
            }
            catch (Exception ex)
            {

                logger.Info($"获取冰箱温度发生异常：ex:{ex.Message}");
            }
            return temperature;
        }
        /// <summary>
        /// 设置冰箱温度
        /// </summary>
        /// <returns></returns>
        public async Task<float> SetFridgeTemperature(float temperature, int iIndex)
        {
            int tpt = (int)temperature * 10;
            byte Temperature = (byte)(tpt & 0xff);
            try
            {
                //if (!FridgeOperate)
                {
                    fridgeSerial.DiscardInBuffer();
                    byte bAddress;
                    if (iIndex == 1)
                    {
                        bAddress = 0x01;
                    }
                    else
                    {
                        bAddress = 0x02;
                    }
                    //byte[] buffer = new byte[] { 0x01, 0x03, 0x10, 0x02, 0x00, 0x01, 0x21,0x0A };
                    byte[] buffer = new byte[] { bAddress, 0x06, 0x10, 0x02, 0x00, (byte)Temperature };

                    //获取数组CRC校验码
                    byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                    //Array.Reverse(byteDate);
                    int dataLength = buffer.Length;
                    Array.Resize(ref buffer, dataLength + byteDate.Length);
                    for (int i = 0; i < byteDate.Length; i++)
                    {
                        buffer[dataLength + i] = byteDate[i];
                    }
                    logger.Info($"设置冰箱温度【{Convert.ToHexString(buffer)}】");
                    fridgeSerial.Write(buffer, 0, 8);

                    await GetBufferByPort(fridgeSerial, 8);
                }
            }
            catch (Exception ex)
            {

                logger.Info($"获取冰箱温度发生异常：ex:{ex.Message}");
            }
            return temperature;
        }
        /// <summary>
        /// 冰箱延迟报警
        /// </summary>
        /// <returns></returns>
        public async Task FridgeDelayWarm(int iIndex)
        {
            try
            {
                //if (!FridgeOperate)
                {
                    fridgeSerial.DiscardInBuffer();
                    byte bAddress;
                    if (iIndex == 1)
                    {
                        bAddress = 0x01;
                    }
                    else
                    {
                        bAddress = 0x02;
                    }
                    byte[] buffer = new byte[] { bAddress, 0x06, 0x10, 0xCD, 0x00, 0x01, 0xDD, 0x35 };
                    //byte[] buffer = new byte[] { 0x01, 0x06, 0x10, 0xCD, 0x00, 0x01 };
                    ////获取数组CRC校验码
                    //byte[] byteDate = CRC16MODBUS.CrcModBus(buffer);
                    ////Array.Reverse(byteDate);
                    //int dataLength = buffer.Length;
                    //Array.Resize(ref buffer, dataLength + byteDate.Length);
                    //for (int i = 0; i < byteDate.Length; i++)
                    //{
                    //    buffer[dataLength + i] = byteDate[i];
                    //}
                    logger.Info($"冰箱延迟报警【{Convert.ToHexString(buffer)}】");
                    fridgeSerial.Write(buffer, 0, 8);
                }
            }
            catch (Exception ex)
            {

                logger.Info($"获取冰箱温度发生异常：ex:{ex.Message}");
            }
        }
        #endregion

    }
}
