PLCS7.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. using S7.Net;
  2. using S7.Net.Types;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Timers;
  12. namespace PLCS7
  13. {
  14. public interface IPLCS7
  15. {
  16. bool PLCConnect();
  17. void PLCDisconnect();
  18. bool WriteToPLC(object abstractPLCMsg, PLCDataType whoami);
  19. List<object> ReadFromPLC(PLCDataType whichToRead, int index);
  20. }
  21. public enum PLCDataType
  22. {
  23. terminal,
  24. central,
  25. parkingSpace
  26. }
  27. public abstract class AbstractPLCLinker : IPLCS7
  28. {
  29. protected const int mainBlockOffset = 52;
  30. protected const int parkingSpaceOffset = 18;
  31. /// <summary>
  32. /// PLC 连接状态flag
  33. /// </summary>
  34. public bool isConnected = false;
  35. /// <summary>
  36. /// plc中cpu类型
  37. /// </summary>
  38. protected CpuType cpu;
  39. /// <summary>
  40. /// PLC的IP地址
  41. /// </summary>
  42. protected string ip;
  43. /// <summary>
  44. /// PLC的端口号
  45. /// </summary>
  46. protected Int16 rack;
  47. /// <summary>
  48. /// 工作站号
  49. /// </summary>
  50. protected Int16 slot;
  51. /// <summary>
  52. /// 终端DB块iD
  53. /// </summary>
  54. protected int terminalDB;
  55. /// <summary>
  56. /// 中心DB块iD
  57. /// </summary>
  58. protected int centralDB;
  59. /// <summary>
  60. /// 车位DB块ID
  61. /// </summary>
  62. protected int parkingSpaceDB;
  63. /// <summary>
  64. /// 终端个数
  65. /// </summary>
  66. protected int terminalCount;
  67. /// <summary>
  68. /// 停车位个数
  69. /// </summary>
  70. protected int parkingSpaceCount;
  71. /// <summary>
  72. /// PLC S7连接对象
  73. /// </summary>
  74. protected static Plc plc = null;
  75. public bool PLCConnect()
  76. {
  77. if (plc == null)
  78. {
  79. plc = new Plc(cpu, ip, rack, slot);
  80. }
  81. if (plc != null)
  82. {
  83. ErrorCode err = plc.Open();
  84. if (err != ErrorCode.NoError) { Console.WriteLine("connection error"); isConnected = false; }
  85. else { Console.WriteLine("connected"); isConnected = true; }
  86. }
  87. else { isConnected = false; }
  88. return isConnected;
  89. }
  90. public void PLCDisconnect()
  91. {
  92. if (plc != null)
  93. {
  94. plc.Close();
  95. }
  96. }
  97. public abstract List<object> ReadFromPLC(PLCDataType whichToRead, int index);
  98. public abstract bool WriteToPLC(object abstractPLCMsg, PLCDataType whoami);
  99. }
  100. public class PLCLinker : AbstractPLCLinker
  101. {
  102. ///// <summary>
  103. ///// PLC刷新频率,来自于配置文件
  104. ///// </summary>
  105. //private int PLC_refresh_interval;
  106. ///// <summary>
  107. ///// 无法获取配置文件时使用的PLC刷新频率
  108. ///// </summary>
  109. //private const short PLC_TIME_SCALE = 200;
  110. //************************************** 方法区 *************************************
  111. public void test()
  112. {
  113. Random rnd = new Random();
  114. Task t = Task.Factory.StartNew(() =>
  115. {
  116. while (true)
  117. {
  118. TerminalStru terminal1 = new TerminalStru();
  119. terminal1 = (TerminalStru)ReadStruFromPLC(terminal1, 27, 0);
  120. Console.WriteLine(terminal1.ToString());
  121. Thread.Sleep(200);
  122. terminal1.terminalStatus = (short)rnd.Next(1, 6);
  123. terminal1.licenseCodeA = rnd.Next(3000, 9999);
  124. terminal1.receiptNum = rnd.Next(3000, 9999);
  125. terminal1.licVerification = (short)rnd.Next(1, 555);
  126. WriteStruToPLC(terminal1, 27, 0);
  127. //List<byte> bList = Struct.ToBytes(terminal1).ToList();
  128. //WriteMultipleBytes(27, bList, 0);
  129. ////203 chars
  130. //string str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccc";
  131. ////pl.WriteMultipleBytes(1, (Encoding.ASCII.GetBytes(str)).ToList());
  132. //byte[] bytes = pl.ReadMultipleBytes(27, 50).ToArray();
  133. //string str2 = Encoding.ASCII.GetString(bytes);
  134. //Console.WriteLine(str2);
  135. //if (str == str2)
  136. //{
  137. // Console.WriteLine("equals");
  138. //}
  139. //else
  140. //{
  141. // Console.WriteLine("error, unequal");
  142. //}
  143. Thread.Sleep(2000);
  144. }
  145. });
  146. t.Wait();
  147. }
  148. /// <summary>
  149. /// PLCLinker构造函数
  150. /// </summary>
  151. /// <param name="cpu"></param>
  152. /// <param name="ip"></param>
  153. /// <param name="rack"></param>
  154. /// <param name="slot"></param>
  155. /// <param name="terminalDB"></param>
  156. /// <param name="centralDB"></param>
  157. /// <param name="parkingSpaceDB"></param>
  158. public PLCLinker(CpuType cpu, string ip, short rack, short slot, int terminalDB, int centralDB, int parkingSpaceDB, int terminalCount, int parkingSpaceCount)
  159. {
  160. this.cpu = cpu;
  161. this.ip = ip;
  162. this.rack = rack;
  163. this.slot = slot;
  164. this.terminalDB = terminalDB;
  165. this.centralDB = centralDB;
  166. this.parkingSpaceDB = parkingSpaceDB;
  167. this.terminalCount = terminalCount;
  168. this.parkingSpaceCount = parkingSpaceCount;
  169. isConnected = PLCConnect();
  170. }
  171. /// <summary>
  172. /// 读取指定数据块中多个字节
  173. /// </summary>
  174. /// <param name="db"></param>
  175. /// <param name="length"></param>
  176. /// <param name="startAddr"></param>
  177. /// <returns></returns>
  178. private List<byte> ReadMultipleBytes(int db, int length, int startAddr = 0)
  179. {
  180. List<byte> resultBytes = new List<byte>();
  181. int index = startAddr;
  182. int remains = length;
  183. while (remains > 0)
  184. {
  185. int maxToRead = Math.Min(remains, 200);
  186. try
  187. {
  188. byte[] temp = plc.ReadBytes(DataType.DataBlock, db, index, maxToRead);
  189. if (temp == null)
  190. return new List<byte>();
  191. resultBytes.AddRange(temp);
  192. remains -= maxToRead;
  193. index += maxToRead;
  194. }
  195. catch { }
  196. }
  197. return resultBytes;
  198. }
  199. /// <summary>
  200. /// 写入指定数据块中多个字节
  201. /// </summary>
  202. /// <param name="db"></param>
  203. /// <param name="bytesToWrite"></param>
  204. /// <param name="startAddr"></param>
  205. /// <returns></returns>
  206. private ErrorCode WriteMultipleBytes(int db, List<byte> bytesToWrite, int startAddr = 0)
  207. {
  208. int index = startAddr;
  209. int remains = bytesToWrite.Count();
  210. try
  211. {
  212. while (remains > 0)
  213. {
  214. int maxToWrite = Math.Min(remains, 200);
  215. ErrorCode ec = plc.WriteBytes(DataType.DataBlock, db, index, bytesToWrite.GetRange(index, maxToWrite).ToArray());
  216. index += maxToWrite;
  217. remains -= maxToWrite;
  218. if (!ec.Equals(ErrorCode.NoError)) { return ec; }
  219. }
  220. }
  221. catch (Exception e) { Console.WriteLine(e.Message); }
  222. return ErrorCode.NoError;
  223. }
  224. /// <summary>
  225. /// 从PLC中读取结构体
  226. /// </summary>
  227. /// <param name="obj"></param>
  228. /// <param name="db"></param>
  229. /// <param name="startAddr"></param>
  230. /// <returns></returns>
  231. private object ReadStruFromPLC(object obj, int db, int startAddr = 0)
  232. {
  233. Type structType = obj.GetType();
  234. object returnedObj;
  235. try
  236. {
  237. //returnedObj = plc.ReadStruct(structType, db, startAddr);
  238. int numBytes = Struct.GetStructSize(structType);
  239. var resultBytes = plc.ReadBytes(DataType.DataBlock, db, startAddr, numBytes);
  240. returnedObj = Struct.FromBytes(structType, resultBytes);
  241. if (returnedObj != null) { return returnedObj; }
  242. }
  243. catch (Exception e)
  244. {
  245. Console.WriteLine(e.Message);
  246. }
  247. return null;
  248. //Console.WriteLine(ts.ToString());
  249. }
  250. /// <summary>
  251. /// 向PLC中写入结构体
  252. /// </summary>
  253. /// <param name="obj"></param>
  254. /// <param name="db"></param>
  255. /// <param name="startAddr"></param>
  256. private ErrorCode WriteStruToPLC(object obj, int db, int startAddr = 0)
  257. {
  258. Console.WriteLine("write to PLC");
  259. ErrorCode ec = ErrorCode.NoError;
  260. try
  261. {
  262. //ec = plc.WriteStruct(obj, 22, startAddr);
  263. List<byte> bList = Struct.ToBytes(obj).ToList();
  264. ec = WriteMultipleBytes(db, bList, startAddr);
  265. }
  266. catch (Exception e) { Console.WriteLine(ec.ToString() + "," + e.Message); }
  267. return ec;
  268. }
  269. private short BytesRevert(short num)
  270. {
  271. byte[] temp = BitConverter.GetBytes(num);
  272. Array.Reverse(temp);
  273. return BitConverter.ToInt16(temp, 0);
  274. }
  275. private int BytesRevert(int num)
  276. {
  277. byte[] temp = BitConverter.GetBytes(num);
  278. Array.Reverse(temp);
  279. return BitConverter.ToInt32(temp, 0);
  280. }
  281. /// <summary>
  282. /// 读取PLC数据块
  283. /// </summary>
  284. /// <param name="whichToRead"></param>
  285. /// <param name="index"></param>
  286. /// <returns></returns>
  287. public override List<object> ReadFromPLC(PLCDataType whichToRead, int index)
  288. {
  289. //更新设备状态
  290. isConnected = plc.IsConnected;
  291. List<object> result = new List<object>();
  292. if (isConnected)
  293. {
  294. switch (whichToRead)
  295. {
  296. case PLCDataType.central:
  297. object obj = ReadStruFromPLC(new MainBlockStru(), centralDB);
  298. if (obj != null) { result.Add(obj); }
  299. break;
  300. case PLCDataType.terminal:
  301. TerminalStru ts = new TerminalStru();
  302. //index 在合理范围读取单一元素,否则全部读取
  303. if (index > 0 && index < terminalCount)
  304. {
  305. obj = ReadStruFromPLC(ts, terminalDB, Struct.GetStructSize(ts.GetType()) * (index - 1));
  306. if (obj != null) { result.Add(obj); }
  307. }
  308. else
  309. {
  310. for (int i = 0; i < terminalCount; i++)
  311. {
  312. obj = ReadStruFromPLC(ts, terminalDB, Struct.GetStructSize(ts.GetType()) * i);
  313. if (obj != null) { result.Add(obj); }
  314. }
  315. }
  316. break;
  317. case PLCDataType.parkingSpace:
  318. ParkingSpaceStru pss = new ParkingSpaceStru();
  319. //index 在合理范围读取单一元素,否则全部读取
  320. if (index > 0 && index < parkingSpaceCount)
  321. {
  322. obj = ReadStruFromPLC(pss, parkingSpaceDB, Struct.GetStructSize(pss.GetType()) * (index - 1));
  323. if (obj != null) { result.Add(obj); }
  324. }
  325. else
  326. {
  327. for (int i = 0; i < parkingSpaceCount; i++)
  328. {
  329. obj = ReadStruFromPLC(pss, parkingSpaceDB, Struct.GetStructSize(pss.GetType()) * i);
  330. if (obj != null) { result.Add(obj); }
  331. }
  332. }
  333. break;
  334. default:
  335. Console.WriteLine("wrong type");
  336. break;
  337. }
  338. }
  339. return result;
  340. }
  341. /// <summary>
  342. /// 写入PLC,其中可写入但不需写入字段请赋值为-1
  343. /// </summary>
  344. /// <param name="abstractPLCMsg"></param>
  345. /// <param name="whoami"></param>
  346. /// <returns></returns>
  347. public override bool WriteToPLC(object abstractPLCMsg, PLCDataType whoami)
  348. {
  349. //更新设备状态
  350. isConnected = plc.IsConnected;
  351. if (abstractPLCMsg == null)
  352. return false;
  353. if (isConnected)
  354. {
  355. if (abstractPLCMsg.GetType().Equals(typeof(TerminalStru)))
  356. {
  357. TerminalStru ts = (TerminalStru)abstractPLCMsg;
  358. if (ts.terminalID <= 0 || ts.terminalID > terminalCount) { return false; }
  359. int offset = 42 * (ts.terminalID - 1);
  360. if (whoami.Equals(PLCDataType.central))
  361. {
  362. if (ts.paymentStatus != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 28 + offset, BitConverter.GetBytes(BytesRevert(ts.paymentStatus))); }
  363. if (ts.licVerification != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 30 + offset, BitConverter.GetBytes(BytesRevert(ts.licVerification))); }
  364. if (ts.parkingFee != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 32 + offset, BitConverter.GetBytes(BytesRevert(ts.parkingFee))); }
  365. if (ts.userType != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 34 + offset, BitConverter.GetBytes(BytesRevert(ts.userType))); }
  366. }
  367. else if (whoami.Equals(PLCDataType.terminal))
  368. {
  369. //if (ts.terminalStatus != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 2 + offset, BitConverter.GetBytes(BytesRevert(ts.terminalStatus))); }
  370. if (ts.btnStatus != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 4 + offset, BitConverter.GetBytes(BytesRevert(ts.btnStatus))); }
  371. if (ts.cmd != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 6 + offset, BitConverter.GetBytes(BytesRevert(ts.cmd))); }
  372. if (ts.licenseCodeA != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 8 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeA))); }
  373. if (ts.licenseCodeB != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 12 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeB))); }
  374. if (ts.licenseCodeC != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 16 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeC))); }
  375. if (ts.licenseCodeD != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 20 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeD))); }
  376. if (ts.receiptNum != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 24 + offset, BitConverter.GetBytes(BytesRevert(ts.receiptNum))); }
  377. }
  378. }
  379. else if (abstractPLCMsg.GetType().Equals(typeof(MainBlockStru)) && whoami.Equals(PLCDataType.central))
  380. {
  381. //只允许中控写入,且中控只允许写入号牌获取状态
  382. MainBlockStru mbs = (MainBlockStru)abstractPLCMsg;
  383. byte[] temp = BitConverter.GetBytes(BytesRevert(mbs.licenseReceived));
  384. ErrorCode ec = plc.WriteBytes(DataType.DataBlock, centralDB, mainBlockOffset, temp);
  385. if (!ec.Equals(ErrorCode.NoError)) { return false; }
  386. }
  387. else if (abstractPLCMsg.GetType().Equals(typeof(ParkingSpaceStru)) && whoami.Equals(PLCDataType.central))
  388. {
  389. //只允许中控写入,中控只允许写车位状态
  390. ParkingSpaceStru pss = (ParkingSpaceStru)abstractPLCMsg;
  391. int offset = 24 * (pss.parkingSpace - 1) + parkingSpaceOffset;
  392. byte[] temp = BitConverter.GetBytes(BytesRevert(pss.spaceStatus));
  393. ErrorCode ec = plc.WriteBytes(DataType.DataBlock, parkingSpaceDB, offset, temp);
  394. if (!ec.Equals(ErrorCode.NoError)) { return false; }
  395. }
  396. else { return false; }
  397. }
  398. else { return false; }
  399. return true;
  400. }
  401. /// <summary>
  402. /// 根据地址偏移量写入PLC
  403. /// </summary>
  404. /// <param name="whichToWrite"></param>
  405. /// <param name="offset"></param>
  406. /// <param name="value"></param>
  407. /// <returns></returns>
  408. public bool WriteAccordingToOffset(PLCDataType whichToWrite, int offset, object value)
  409. {
  410. isConnected = plc.IsConnected;
  411. if (value == null)
  412. return false;
  413. if (isConnected)
  414. {
  415. ErrorCode ec = ErrorCode.NoError;
  416. switch (whichToWrite)
  417. {
  418. case PLCDataType.terminal:
  419. if (value.GetType().Equals(typeof(int)))
  420. {
  421. ec = plc.WriteBytes(DataType.DataBlock, terminalDB, offset, BitConverter.GetBytes(BytesRevert((int)value)));
  422. }
  423. else if (value.GetType().Equals(typeof(short)))
  424. {
  425. ec = plc.WriteBytes(DataType.DataBlock, terminalDB, offset, BitConverter.GetBytes(BytesRevert((short)value)));
  426. }
  427. if (ec.Equals(ErrorCode.NoError)) { return true; }
  428. else { return false; }
  429. break;
  430. case PLCDataType.central:
  431. if (value.GetType().Equals(typeof(int)))
  432. {
  433. ec = plc.WriteBytes(DataType.DataBlock, centralDB, offset, BitConverter.GetBytes(BytesRevert((int)value)));
  434. }
  435. else if (value.GetType().Equals(typeof(short)))
  436. {
  437. ec = plc.WriteBytes(DataType.DataBlock, centralDB, offset, BitConverter.GetBytes(BytesRevert((short)value)));
  438. }
  439. if (ec.Equals(ErrorCode.NoError)) { return true; }
  440. else { return false; }
  441. break;
  442. case PLCDataType.parkingSpace:
  443. if (value.GetType().Equals(typeof(int)))
  444. {
  445. ec = plc.WriteBytes(DataType.DataBlock, parkingSpaceDB, offset, BitConverter.GetBytes(BytesRevert((int)value)));
  446. }
  447. else if (value.GetType().Equals(typeof(short)))
  448. {
  449. ec = plc.WriteBytes(DataType.DataBlock, parkingSpaceDB, offset, BitConverter.GetBytes(BytesRevert((short)value)));
  450. }
  451. if (ec.Equals(ErrorCode.NoError)) { return true; }
  452. else { return false; }
  453. break;
  454. }
  455. }
  456. return false;
  457. }
  458. }
  459. }