ComAgent.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO.Ports;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using System.Linq;
  9. using System.Collections.Concurrent;
  10. using System.Runtime.InteropServices;
  11. using WpfTest1.SmallDialogs.Debug;
  12. using WpfTest1.ComAgent.Debug;
  13. namespace WpfTest1.ComAgent
  14. {
  15. public interface ComAgentListener
  16. {
  17. void comAgentReceiveData(byte[] data);
  18. void comAgentConnected();
  19. void comAgentDisconnected(Exception e);
  20. }
  21. public struct TreatmentStep
  22. {
  23. public ushort Hz { get; set; }
  24. public byte T { get; set; }
  25. public byte P { get; set; }
  26. public ushort S { get; set; }
  27. public TreatmentStep(ushort hz, byte t, byte p, ushort s)
  28. {
  29. Hz = hz;
  30. T = t;
  31. P = p;
  32. S = s;
  33. }
  34. public TreatmentStep(double hz, byte t, double p, ushort s)
  35. {
  36. Hz = (ushort)(hz * 10.0);
  37. T = t;
  38. P = (byte)(p);
  39. S = s;
  40. }
  41. }
  42. public class SingleInstance<T> where T : new()
  43. {
  44. private static T instance;
  45. private static object lck = new object();
  46. public static T getInstance(Func<T> allocator = null)
  47. {
  48. lock (lck)
  49. {
  50. if (instance != null) return instance;
  51. instance = allocator != null ? allocator() : new T();
  52. return instance;
  53. }
  54. }
  55. }
  56. public class ComAgent
  57. {
  58. public static byte[] createAnswerCommand(bool status) => 0x00.b().pack(status ? 0x54.b() : 0x46.b());
  59. public static byte[] createHandshakeCommand() => 0x4B.b().pack(0x00.b());
  60. public static byte[] createShutdownCommand() => 0x47.b().pack(0x00.b());
  61. public static byte[] createIdleCommand() => 0x49.b().pack(0x00.b());
  62. public static byte[] createChangeStrongthCommand(byte strongth) => 0x40.b().pack(strongth);
  63. public static byte getTCIDByIndex(int index)
  64. {
  65. switch (index)
  66. {
  67. case 0: return 0x10;
  68. case 1: return 0x11;
  69. case 2: return 0x12;
  70. case 3: return 0x13;
  71. case 4: return 0x14;
  72. case 5: return 0x25;
  73. case 6: return 0x26;
  74. case 7: return 0x27;
  75. case 8: return 0x28;
  76. case 9: return 0x29;
  77. default: throw new ComException($"Invaild mode {index}");
  78. }
  79. }
  80. public static byte[] createStartDefinedCommand(int mode, short time, byte strongth)
  81. {
  82. List<byte> buff = new List<byte>();
  83. buff.Add(getTCIDByIndex(mode));
  84. buff.Add(0x53);
  85. buff.AddRange(time.buff());
  86. buff.AddRange(strongth.buff());
  87. buff.Add(0x00);
  88. return buff.ToArray();
  89. }
  90. public static byte[] createStartManualCommand(short time, byte strongth, params TreatmentStep[] steps)
  91. {
  92. List<byte> buff = new List<byte>();
  93. buff.Add(48);
  94. buff.Add(83);
  95. buff.AddRange(time.buff());
  96. buff.AddRange(strongth.buff());
  97. buff.AddRange(((byte)steps.Length).buff());
  98. for (int i = 0; i < steps.Length; i++)
  99. {
  100. TreatmentStep step = steps[i];
  101. buff.AddRange(step.Hz.buff());
  102. buff.AddRange(step.T.buff());
  103. buff.AddRange(step.P.buff());
  104. buff.AddRange(step.S.buff());
  105. }
  106. return buff.ToArray();
  107. }
  108. public static byte[] createStopCommand(byte mode = 0x30) => mode.pack(0x73.b());
  109. private AutoReleaseObject<ISerialPortAdapter> serial;
  110. private Thread sendThread_, recvThread_;
  111. private List<ComAgentListener> listeners;
  112. public string[] blockingSerialPorts { get; set; }
  113. public void addListener(ComAgentListener listener)
  114. {
  115. listeners.Add(listener);
  116. }
  117. public void tryAddListener(ComAgentListener listener)
  118. {
  119. if (!listeners.Contains(listener))
  120. addListener(listener);
  121. }
  122. #if DEBUG
  123. private SerialPortLogWindow window => SingleInstance<SerialPortLogWindow>.getInstance(() =>
  124. {
  125. SerialPortLogWindow win = null;
  126. App.Current.Dispatcher.Invoke(() =>
  127. {
  128. win = new SerialPortLogWindow();
  129. win.Show();
  130. });
  131. return win;
  132. });
  133. private SerialPortSetup setupWindow = SingleInstance<SerialPortSetup>.getInstance(() =>
  134. {
  135. SerialPortSetup win = null;
  136. bool cont = false;
  137. App.Current.Dispatcher.Invoke(() =>
  138. {
  139. while (win == null || win.result == null)
  140. {
  141. win = new SerialPortSetup();
  142. win.ShowDialog();
  143. }
  144. cont = true;
  145. });
  146. while (!cont) Thread.Sleep(10);
  147. return win;
  148. });
  149. #endif
  150. void Log(string msg)
  151. {
  152. #if DEBUG
  153. window.Log($"[{DateTime.Now}] ${msg}");
  154. Console.WriteLine(msg);
  155. #endif
  156. }
  157. public ComAgent()
  158. {
  159. listeners = new List<ComAgentListener>();
  160. }
  161. private byte[] readPackage(ISerialPortAdapter sp)
  162. {
  163. byte[] buff = new byte[2];
  164. List<byte> data = new List<byte>();
  165. while (true)
  166. {
  167. sp.read(buff, 1);
  168. if (buff[0] != 0x10) continue;
  169. sp.read(buff, 1);
  170. if (buff[0] != 0x02) continue;
  171. data.AddRange(new byte[2] { 0x10, 0x02 });
  172. break;
  173. }
  174. while (true)
  175. {
  176. sp.read(buff, 1);
  177. data.Add(buff[0]);
  178. if (buff[0] == 0x10)
  179. {
  180. sp.read(buff, 1);
  181. data.Add(buff[0]);
  182. if (buff[0] == 0x03) break;
  183. }
  184. }
  185. return data.ToArray();
  186. }
  187. private byte[] readPackageAndUnpack(ISerialPortAdapter sp) => readPackage(sp).unpackData();
  188. private bool connect()
  189. {
  190. #if DLOCAL
  191. AutoReleaseObject<ISerialPortAdapter> comt = new TestSerialPort(new byte[]
  192. {
  193. 0x10, 0x02, 0x00, 0x06, 0x44, 0x54, 0x01, 0x00, 0x00, 0x00, 0x10, 0x03
  194. });
  195. comt.reference.Open();
  196. serial = comt;
  197. return true;
  198. #endif
  199. #if DEBUG
  200. AutoReleaseObject<ISerialPortAdapter> com3 = new RealSerialPort(setupWindow.result, 9600);
  201. com3.reference.Open();
  202. serial = com3;
  203. return true;
  204. #endif
  205. string[] ports = (from it in SerialPort.GetPortNames()
  206. where !blockingSerialPorts.Contains(it)
  207. select it).ToArray();
  208. List<Thread> sps = new List<Thread>();
  209. for (int i = 0; i < ports.Length; i++)
  210. {
  211. string mport = ports[i];
  212. Thread mth = new Thread(() =>
  213. {
  214. AutoReleaseObject<ISerialPortAdapter> sp = new RealSerialPort(mport, 9600);
  215. sp.reference.ReadTimeout = sp.reference.WriteTimeout = 1000;
  216. try
  217. {
  218. sp.reference.Open();
  219. sp.reference.send(createHandshakeCommand().packData());
  220. byte[] resp = readPackageAndUnpack(sp.reference);
  221. if (serial != null) return;
  222. if (resp.bEquals(new byte[1] { 0x4B }))
  223. serial = sp;
  224. }
  225. catch (Exception e)
  226. {
  227. Log(e.ToString());
  228. sp.reference.shutdown();
  229. }
  230. })
  231. { IsBackground = true };
  232. sps.Add(mth);
  233. mth.Start();
  234. }
  235. while (true)
  236. {
  237. if ((from it in sps
  238. where it.IsAlive
  239. select it).Count() == 0) break;
  240. if (serial != null) break;
  241. }
  242. return serial != null;
  243. }
  244. private ConcurrentQueue<byte[]> sendQueue;
  245. private object serial_lock_w = new object(), serial_lock_r = new object();
  246. public void enqueueCommand(byte[] buff) => sendQueue.Enqueue(buff.packData());
  247. private void printBuff(string from, byte[] buff)
  248. {
  249. StringBuilder sb = new StringBuilder();
  250. for (int i = 0; i < buff.Length; i++)
  251. {
  252. sb.AppendFormat("{0:x2} ", buff[i]);
  253. }
  254. Log(from + " " + sb.ToString());
  255. }
  256. private void sendThread()
  257. {
  258. while (true)
  259. {
  260. lock (serial_lock_w)
  261. {
  262. if (serial == null)
  263. {
  264. while (!connect()) Thread.Sleep(10);
  265. listeners.ForEach(listener => listener.comAgentConnected());
  266. }
  267. try
  268. {
  269. if (!serial.reference.IsOpen) throw new ComException("Shutdown by client.");
  270. #if !DEBUG
  271. serial.reference.send(createIdleCommand());
  272. #endif
  273. while (sendQueue.TryDequeue(out byte[] buff))
  274. {
  275. serial.reference.send(buff);
  276. printBuff("ME -> Client", buff);
  277. }
  278. }
  279. catch (Exception e)
  280. {
  281. Log($"SendThread {e}");
  282. if (serial != null) serial.reference.shutdown();
  283. serial = null;
  284. if (!sendedDisconnectedMessage)
  285. {
  286. listeners.ForEach(delegate (ComAgentListener listener)
  287. {
  288. listener.comAgentDisconnected(e);
  289. });
  290. sendedDisconnectedMessage = true;
  291. }
  292. break;
  293. }
  294. }
  295. Thread.Sleep(10);
  296. }
  297. }
  298. private bool sendedDisconnectedMessage = false;
  299. private bool __sendThreadAct = false;
  300. private bool __recvThreadAct = false;
  301. public void reconnect()
  302. {
  303. sendedDisconnectedMessage = false;
  304. if (!__sendThreadAct)
  305. {
  306. __sendThreadAct = true;
  307. sendThread_ = new Thread(sendThread)
  308. {
  309. IsBackground = true
  310. };
  311. sendThread_.Start();
  312. }
  313. if (!__recvThreadAct)
  314. {
  315. __recvThreadAct = true;
  316. recvThread_ = new Thread(recvThread)
  317. {
  318. IsBackground = true
  319. };
  320. recvThread_.Start();
  321. }
  322. if (listeners == null)
  323. listeners = new List<ComAgentListener>();
  324. sendQueue = new ConcurrentQueue<byte[]>();
  325. blockingSerialPorts = new string[1] { "COM1" };
  326. }
  327. public void shutdown()
  328. {
  329. enqueueCommand(createShutdownCommand());
  330. }
  331. private void recvThread()
  332. {
  333. while (true)
  334. {
  335. lock (serial_lock_r)
  336. {
  337. if (serial != null)
  338. {
  339. try
  340. {
  341. if (!serial.reference.IsOpen) throw new ComException("Shutdown by client.");
  342. byte[] data = readPackage(serial.reference);
  343. printBuff("Client -> Me", data);
  344. data = data.unpackData();
  345. listeners.ForEach(listener => listener.comAgentReceiveData(data));
  346. }
  347. catch (Exception e)
  348. {
  349. Log($"RecvThread {e}");
  350. #if !DEBUG
  351. if (serial != null) serial.reference.shutdown();
  352. serial = null;
  353. listeners.ForEach(listener => listener.comAgentDisconnected(e));
  354. #endif
  355. if (!sendedDisconnectedMessage)
  356. {
  357. listeners.ForEach(delegate (ComAgentListener listener)
  358. {
  359. listener.comAgentDisconnected(e);
  360. });
  361. sendedDisconnectedMessage = true;
  362. }
  363. break;
  364. }
  365. }
  366. }
  367. Thread.Sleep(10);
  368. }
  369. }
  370. }
  371. }