|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120 |
- using BPASmartClient.Helper;
- using BPASmartClient.Message;
- 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<byte> dataStorage = new DataStorage<byte>();
-
- //是否下发指令,主线程等待
- 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()
- {
- ThreadManage.GetInstance().StartLong(new Action(() =>
- {
- if (!free)
- {
- commProxy.SendData(cmdAsk);
- }
- Thread.Sleep(500);
- }), "KHKJ询问线程");
-
- ThreadManage.GetInstance().StartLong(new Action(() =>
- {
- ResolveMsg();
- }), "KHKJ解析线程");
- }
-
- private void ResolveMsg()
- {
- List<byte> temp = new List<byte>();
- //一系列解包
- while (dataStorage.GetSize() > 0)
- {
- byte item = dataStorage.GetData();
- List<byte> data = new List<byte>() { 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<byte> vs = new List<byte>() { 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}]");
- }
- }
-
-
- /// <summary>
- /// 16进制转字节数组
- /// </summary>
- /// <param name="hexstring"></param>
- /// <returns></returns>
- 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;
- }
- }
- }
|