123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410 |
- using S7.Net;
- using S7.Net.Types;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Timers;
- namespace PLCS7
- {
- interface IPLCS7
- {
- bool PLCConnect();
- void PLCDisconnect();
- bool WriteToPLC(object abstractPLCMsg, PLCDataType whoami);
- List<object> ReadFromPLC(PLCDataType whichToRead, int index);
- }
- public enum PLCDataType
- {
- terminal,
- central,
- parkingSpace
- }
- public abstract class AbstractPLCLinker : IPLCS7
- {
- protected const int mainBlockOffset = 18;
- protected const int parkingSpaceOffset = 18;
- /// <summary>
- /// PLC 连接状态flag
- /// </summary>
- public bool isConnected = false;
- /// <summary>
- /// plc中cpu类型
- /// </summary>
- protected CpuType cpu;
- /// <summary>
- /// PLC的IP地址
- /// </summary>
- protected string ip;
- /// <summary>
- /// PLC的端口号
- /// </summary>
- protected Int16 rack;
- /// <summary>
- /// 工作站号
- /// </summary>
- protected Int16 slot;
- /// <summary>
- /// 终端DB块iD
- /// </summary>
- protected int terminalDB;
- /// <summary>
- /// 中心DB块iD
- /// </summary>
- protected int centralDB;
- /// <summary>
- /// 车位DB块ID
- /// </summary>
- protected int parkingSpaceDB;
- /// <summary>
- /// 终端个数
- /// </summary>
- protected int terminalCount;
- /// <summary>
- /// 停车位个数
- /// </summary>
- protected int parkingSpaceCount;
- /// <summary>
- /// PLC S7连接对象
- /// </summary>
- protected static Plc plc = null;
- public bool PLCConnect()
- {
- if (plc == null)
- {
- plc = new Plc(cpu, ip, rack, slot);
- }
- if (plc != null)
- {
- ErrorCode err = plc.Open();
- if (err != ErrorCode.NoError) { Console.WriteLine("connection error"); isConnected = false; }
- else { Console.WriteLine("connected"); isConnected = true; }
- }
- else { isConnected = false; }
- return isConnected;
- }
- public void PLCDisconnect()
- {
- if (plc != null)
- {
- plc.Close();
- }
- }
- public abstract List<object> ReadFromPLC(PLCDataType whichToRead, int index);
- public abstract bool WriteToPLC(object abstractPLCMsg, PLCDataType whoami);
- }
- public class PLCLinker : AbstractPLCLinker
- {
- ///// <summary>
- ///// PLC刷新频率,来自于配置文件
- ///// </summary>
- //private int PLC_refresh_interval;
- ///// <summary>
- ///// 无法获取配置文件时使用的PLC刷新频率
- ///// </summary>
- //private const short PLC_TIME_SCALE = 200;
- //************************************** 方法区 *************************************
- public void test()
- {
- Random rnd = new Random();
- Task t = Task.Factory.StartNew(() =>
- {
- while (true)
- {
- TerminalStru terminal1 = new TerminalStru();
- terminal1 = (TerminalStru)ReadStruFromPLC(terminal1, 27, 0);
- Console.WriteLine(terminal1.ToString());
- Thread.Sleep(200);
- terminal1.terminalStatus = (short)rnd.Next(1, 6);
- terminal1.licenseCodeA = rnd.Next(3000, 9999);
- terminal1.receiptNum = rnd.Next(3000, 9999);
- terminal1.licVerification = (short)rnd.Next(1, 555);
- WriteStruToPLC(terminal1, 27, 0);
- //List<byte> bList = Struct.ToBytes(terminal1).ToList();
- //WriteMultipleBytes(27, bList, 0);
- ////203 chars
- //string str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbccc";
- ////pl.WriteMultipleBytes(1, (Encoding.ASCII.GetBytes(str)).ToList());
- //byte[] bytes = pl.ReadMultipleBytes(27, 50).ToArray();
- //string str2 = Encoding.ASCII.GetString(bytes);
- //Console.WriteLine(str2);
- //if (str == str2)
- //{
- // Console.WriteLine("equals");
- //}
- //else
- //{
- // Console.WriteLine("error, unequal");
- //}
- Thread.Sleep(2000);
- }
- });
- t.Wait();
- }
- /// <summary>
- /// PLCLinker构造函数
- /// </summary>
- /// <param name="cpu"></param>
- /// <param name="ip"></param>
- /// <param name="rack"></param>
- /// <param name="slot"></param>
- /// <param name="terminalDB"></param>
- /// <param name="centralDB"></param>
- /// <param name="parkingSpaceDB"></param>
- public PLCLinker(CpuType cpu, string ip, short rack, short slot, int terminalDB, int centralDB, int parkingSpaceDB, int terminalCount, int parkingSpaceCount)
- {
- this.cpu = cpu;
- this.ip = ip;
- this.rack = rack;
- this.slot = slot;
- this.terminalDB = terminalDB;
- this.centralDB = centralDB;
- this.parkingSpaceDB = parkingSpaceDB;
- this.terminalCount = terminalCount;
- this.parkingSpaceCount = parkingSpaceCount;
- isConnected = PLCConnect();
- }
- /// <summary>
- /// 读取指定数据块中多个字节
- /// </summary>
- /// <param name="db"></param>
- /// <param name="length"></param>
- /// <param name="startAddr"></param>
- /// <returns></returns>
- private List<byte> ReadMultipleBytes(int db, int length, int startAddr = 0)
- {
- List<byte> resultBytes = new List<byte>();
- int index = startAddr;
- int remains = length;
- while (remains > 0)
- {
- int maxToRead = Math.Min(remains, 200);
- try
- {
- byte[] temp = plc.ReadBytes(DataType.DataBlock, db, index, maxToRead);
- if (temp == null)
- return new List<byte>();
- resultBytes.AddRange(temp);
- remains -= maxToRead;
- index += maxToRead;
- }
- catch { }
- }
- return resultBytes;
- }
- /// <summary>
- /// 写入指定数据块中多个字节
- /// </summary>
- /// <param name="db"></param>
- /// <param name="bytesToWrite"></param>
- /// <param name="startAddr"></param>
- /// <returns></returns>
- private ErrorCode WriteMultipleBytes(int db, List<byte> bytesToWrite, int startAddr = 0)
- {
- int index = startAddr;
- int remains = bytesToWrite.Count();
- try
- {
- while (remains > 0)
- {
- int maxToWrite = Math.Min(remains, 200);
- ErrorCode ec = plc.WriteBytes(DataType.DataBlock, db, index, bytesToWrite.GetRange(index, maxToWrite).ToArray());
- index += maxToWrite;
- remains -= maxToWrite;
- if (!ec.Equals(ErrorCode.NoError)) { return ec; }
- }
- }
- catch (Exception e) { Console.WriteLine(e.Message); }
- return ErrorCode.NoError;
- }
- /// <summary>
- /// 从PLC中读取结构体
- /// </summary>
- /// <param name="obj"></param>
- /// <param name="db"></param>
- /// <param name="startAddr"></param>
- /// <returns></returns>
- private object ReadStruFromPLC(object obj, int db, int startAddr = 0)
- {
- Type structType = obj.GetType();
- object returnedObj;
- try
- {
- //returnedObj = plc.ReadStruct(structType, db, startAddr);
- int numBytes = Struct.GetStructSize(structType);
- var resultBytes = plc.ReadBytes(DataType.DataBlock, db, startAddr, numBytes);
- returnedObj = Struct.FromBytes(structType, resultBytes);
- if (returnedObj != null) { return returnedObj; }
- }
- catch (Exception e)
- {
- Console.WriteLine(e.Message);
- }
- return null;
- //Console.WriteLine(ts.ToString());
- }
- /// <summary>
- /// 向PLC中写入结构体
- /// </summary>
- /// <param name="obj"></param>
- /// <param name="db"></param>
- /// <param name="startAddr"></param>
- private ErrorCode WriteStruToPLC(object obj, int db, int startAddr = 0)
- {
- Console.WriteLine("write to PLC");
- ErrorCode ec = ErrorCode.NoError;
- try
- {
- //ec = plc.WriteStruct(obj, 22, startAddr);
- List<byte> bList = Struct.ToBytes(obj).ToList();
- ec = WriteMultipleBytes(db, bList, startAddr);
- }
- catch (Exception e) { Console.WriteLine(ec.ToString() + "," + e.Message); }
- return ec;
- }
- private short BytesRevert(short num)
- {
- byte[] temp = BitConverter.GetBytes(num);
- Array.Reverse(temp);
- return BitConverter.ToInt16(temp, 0);
- }
- private int BytesRevert(int num)
- {
- byte[] temp = BitConverter.GetBytes(num);
- Array.Reverse(temp);
- return BitConverter.ToInt32(temp, 0);
- }
- /// <summary>
- /// 读取PLC数据块
- /// </summary>
- /// <param name="whichToRead"></param>
- /// <param name="index"></param>
- /// <returns></returns>
- public override List<object> ReadFromPLC(PLCDataType whichToRead, int index)
- {
- //更新设备状态
- isConnected = plc.IsConnected;
- List<object> result = new List<object>();
- if (isConnected)
- {
- switch (whichToRead)
- {
- case PLCDataType.central:
- object obj = ReadStruFromPLC(new MainBlockStru(), centralDB);
- if (obj != null) { result.Add(obj); }
- break;
- case PLCDataType.terminal:
- TerminalStru ts = new TerminalStru();
- //index 在合理范围读取单一元素,否则全部读取
- if (index > 0 && index < terminalCount)
- {
- obj = ReadStruFromPLC(ts, terminalDB, Struct.GetStructSize(ts.GetType()) * (index - 1));
- if (obj != null) { result.Add(obj); }
- }
- else
- {
- for (int i = 0; i < terminalCount; i++)
- {
- obj = ReadStruFromPLC(ts, terminalDB, Struct.GetStructSize(ts.GetType()) * i);
- if (obj != null) { result.Add(obj); }
- }
- }
- break;
- case PLCDataType.parkingSpace:
- ParkingSpaceStru pss = new ParkingSpaceStru();
- //index 在合理范围读取单一元素,否则全部读取
- if (index > 0 && index < parkingSpaceCount)
- {
- obj = ReadStruFromPLC(pss, parkingSpaceDB, Struct.GetStructSize(pss.GetType()) * (index - 1));
- if (obj != null) { result.Add(obj); }
- }
- else
- {
- for (int i = 0; i < parkingSpaceCount; i++)
- {
- obj = ReadStruFromPLC(pss, parkingSpaceDB, Struct.GetStructSize(pss.GetType()) * i);
- if (obj != null) { result.Add(obj); }
- }
- }
- break;
- default:
- Console.WriteLine("wrong type");
- break;
- }
- }
- return result;
- }
- /// <summary>
- /// 写入PLC,其中可写入但不需写入字段请赋值为-1
- /// </summary>
- /// <param name="abstractPLCMsg"></param>
- /// <param name="whoami"></param>
- /// <returns></returns>
- public override bool WriteToPLC(object abstractPLCMsg, PLCDataType whoami)
- {
- //更新设备状态
- isConnected = plc.IsConnected;
- if (abstractPLCMsg == null)
- return false;
- if (isConnected)
- {
- if (abstractPLCMsg.GetType().Equals(typeof(TerminalStru)))
- {
- TerminalStru ts = (TerminalStru)abstractPLCMsg;
- if (ts.terminalID < 0 || ts.terminalID >= terminalCount) { return false; }
- int offset = 36 * (ts.terminalID - 1);
- if (whoami.Equals(PLCDataType.central))
- {
- if (ts.paymentStatus != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 22 + offset, BitConverter.GetBytes(BytesRevert(ts.paymentStatus))); }
- if (ts.licVerification != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 24 + offset, BitConverter.GetBytes(BytesRevert(ts.licVerification))); }
- if (ts.parkingFee != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 26 + offset, BitConverter.GetBytes(BytesRevert(ts.parkingFee))); }
- if (ts.userType != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 28 + offset, BitConverter.GetBytes(BytesRevert(ts.userType))); }
- }
- else if (whoami.Equals(PLCDataType.terminal))
- {
- if (ts.btnStatus != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 4 + offset, BitConverter.GetBytes(BytesRevert(ts.btnStatus))); }
- if (ts.terminalStatus != (short)-1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 4 + offset, BitConverter.GetBytes(BytesRevert(ts.terminalStatus))); }
- if (ts.licenseCodeA != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 6 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeA))); }
- if (ts.licenseCodeB != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 10 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeB))); }
- if (ts.licenseCodeC != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 14 + offset, BitConverter.GetBytes(BytesRevert(ts.licenseCodeC))); }
- if (ts.receiptNum != -1) { plc.WriteBytes(DataType.DataBlock, terminalDB, 18 + offset, BitConverter.GetBytes(BytesRevert(ts.receiptNum))); }
- }
- }
- else if (abstractPLCMsg.GetType().Equals(typeof(MainBlockStru)) && whoami.Equals(PLCDataType.central))
- {
- //只允许中控写入,且中控只允许写入号牌获取状态
- MainBlockStru mbs = (MainBlockStru)abstractPLCMsg;
- byte[] temp = BitConverter.GetBytes(BytesRevert(mbs.licenseReceived));
- ErrorCode ec = plc.WriteBytes(DataType.DataBlock, centralDB, mainBlockOffset, temp);
- if (!ec.Equals(ErrorCode.NoError)) { return false; }
- }
- else if (abstractPLCMsg.GetType().Equals(typeof(ParkingSpaceStru)) && whoami.Equals(PLCDataType.central))
- {
- //只允许中控写入,中控只允许写车位状态
- ParkingSpaceStru pss = (ParkingSpaceStru)abstractPLCMsg;
- int offset = 24 * (pss.parkingSpace - 1) + parkingSpaceOffset;
- byte[] temp = BitConverter.GetBytes(BytesRevert(pss.spaceStatus));
- ErrorCode ec = plc.WriteBytes(DataType.DataBlock, parkingSpaceDB, offset, temp);
- if (!ec.Equals(ErrorCode.NoError)) { return false; }
- }
- else { return false; }
- }
- else { return false; }
- return true;
- }
- }
- }
|