using BPA.Helper; using BPASmartClient.SerialPort; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BPASmartClient.KHKJ { public class KHKJMachine { //通讯代理 SerialPortClient commProxy = null; //数据仓库 private DataStorage dataStorage = new DataStorage(); //是否下发指令,主线程等待 private bool free = false; //状态询问指令 private byte[] cmdAsk; public KHKJMachine() { MainLoop(); } public void Communication(string serialPort) { commProxy = new SerialPortClient(serialPort, BaudRates.BR_9600); commProxy.SetDataStorage(dataStorage); commProxy.Start(); free = true; } private void MainLoop() { TaskManage.GetInstance.StartLong(new Action(() => { if (!free) { commProxy.SendData(cmdAsk); } Thread.Sleep(500); }), "KHKJ询问线程"); TaskManage.GetInstance.StartLong(new Action(() => { ResolveMsg(); }), "KHKJ解析线程"); } private void ResolveMsg() { List temp = new List(); //一系列解包 while (dataStorage.GetSize() > 0) { byte item = dataStorage.GetData(); List data = new List() { item }; if (Encoding.ASCII.GetString(data.ToArray()) == ":") { temp.Add(item); while (dataStorage.GetSize() < 32) { Thread.Sleep(5); } while (temp.Count < 32) { temp.Add(dataStorage.GetData()); } List vs = new List() { temp[temp.Count - 4], temp[temp.Count - 3], temp[temp.Count - 2], temp[temp.Count - 1] }; string t = Encoding.ASCII.GetString(vs.ToArray()).ToLower(); var package = Encoding.ASCII.GetString(temp.ToArray()); //if (package.Contains("\\r\\n")) //{ // ProcessMsg(package); //} temp.Clear(); } continue; } Thread.Sleep(500); } public void Stop() { try { commProxy.Stop(); free = true; } catch (Exception ex) { MessageLog.GetInstance.ShowEx($"BPASmartClient.KLMCoffee 中引发错误,CoffeeMachine 类,描述:[{ex.Message}]"); } } /// /// 16进制转字节数组 /// /// /// public byte[] HexStringToByteArray( string hexstring) { var byteArray = new byte[hexstring.Length/2]; for (int i = 0; i < byteArray.Length; i++) { var x = Convert.ToInt32(hexstring.Substring(i * 2, 2), 16); byteArray[i] = (byte)x; } return byteArray; } } }