using BPA.Utility; using HBLConsole.Communication; using HBLConsole.Service; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using static BPA.Utility.EventBus; namespace HBLDevice.ICChip { /// /// 指令封装 /// internal class CommandHandler { private SerialPortClient commProxy; private ICChipPackage package = new ICChipPackage(); /// /// 初始化 /// internal void Init(SerialPortClient commProxy) { this.commProxy = commProxy; EventBus.GetInstance().Subscribe(TakeCupEventHandle); EventBus.GetInstance().Subscribe(MakeIceCreamEventHandle); EventBus.GetInstance().Subscribe(RotorSwitchEventHandle); } private void RotorSwitchEventHandle(IEvent @event, EventCallBackHandle callBack) { package.Cmd = IC_CMD.ROTOR; package.Value = (@event as RotorSwitchEvent).TurnOn ? (byte)IC_ROTOR.OPEN_ROTOR : (byte)IC_ROTOR.OPEN_ROTOR; commProxy.SendData(StructureToByte(package)); } private void MakeIceCreamEventHandle(IEvent @event, EventCallBackHandle callBack) { package.Cmd = IC_CMD.OPEN_SE; package.Value = (byte)(@event as MakeIceCreamEvent).SteeringEngine; commProxy.SendData(StructureToByte(package)); Thread.Sleep(3000); package.Cmd = IC_CMD.CLOSE_SE; package.Value = (byte)(@event as MakeIceCreamEvent).SteeringEngine; commProxy.SendData(StructureToByte(package)); } private void TakeCupEventHandle(IEvent @event, EventCallBackHandle callBack) { switch ((@event as TakeCupEvent).Cup) { case IC_CUP.CUP_ICECREAM: ChipStatus.GetInstance().CompletedTake_CPU_CUP_ICECREAM = false; break; case IC_CUP.CUP_COFFEE: ChipStatus.GetInstance().CompletedTake_CPU_CUP_COFFEE = false; break; } package.Cmd = IC_CMD.TAKE_CUP; package.Value = (byte)(@event as TakeCupEvent).Cup; commProxy.SendData(StructureToByte(package)); } private byte[] StructureToByte(ICChipPackage structure) { structure.Header = 0xAA; structure.Sender = IC_SENDER.CONSOLE; structure.End = 0xBB; int size = Marshal.SizeOf(typeof(ICChipPackage)); byte[] buffer = new byte[size]; IntPtr bufferIntPtr = Marshal.AllocHGlobal(size); try { Marshal.StructureToPtr(structure, bufferIntPtr, true); Marshal.Copy(bufferIntPtr, buffer, 0, size); } finally { Marshal.FreeHGlobal(bufferIntPtr); } return buffer; } } }