DeltaAxCommProtocol.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. using IACommService4CSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace PlcCom
  10. {
  11. public class DeltaAxPLCNetConfig
  12. {
  13. private string axIP = "192.168.0.10";
  14. public string GetAxIP()
  15. {
  16. return axIP;
  17. }
  18. private void SetAxIP(string value)
  19. {
  20. axIP = value;
  21. }
  22. private string axPort = "11740";
  23. public string GetAxPort()
  24. {
  25. return axPort;
  26. }
  27. private void SetAxPort(string value)
  28. {
  29. axPort = value;
  30. }
  31. }
  32. public class DeltaAxCommProtocol : IPlcComProtocol
  33. {
  34. public bool IsConnected { get; set; }
  35. public string AxIP { get; }
  36. public string AxPort { get; }
  37. AXClient_t client;
  38. public DeltaAxCommProtocol(DeltaAxPLCNetConfig deltaAxPLCNetConfig)
  39. {
  40. AxIP= deltaAxPLCNetConfig.GetAxIP();
  41. AxPort= deltaAxPLCNetConfig.GetAxPort();
  42. var rt = Initialize();
  43. client = new AXClient_t();
  44. }
  45. public DeltaAxCommProtocol():this(new DeltaAxPLCNetConfig())
  46. {
  47. }
  48. private uint Initialize()
  49. {
  50. //Configure log
  51. LogConfig_t logConfig = new LogConfig_t();
  52. logConfig.Enable = true;
  53. logConfig.Path = "./";
  54. logConfig.DateFormat = "%Y-%m-%d %H:%M:%S.%q";
  55. logConfig.MaxFileSize = 512 * 1024;
  56. logConfig.MaxBackupIndex = 5;
  57. logConfig.LevelMask = Convert.ToUInt32(LevelMask_t.LOG_LEVEL_FATAL | LevelMask_t.LOG_LEVEL_ERROR | LevelMask_t.LOG_LEVEL_WARN | LevelMask_t.LOG_LEVEL_INFO);
  58. logConfig.CategoryMask = Convert.ToUInt32(CategoryMask_t.LOG_CATEGORY_SYSTEM | CategoryMask_t.LOG_CATEGORY_CONNECT);
  59. var status = IACommService_t.SetLogConfig(logConfig);
  60. //Global initialization
  61. status = IACommService_t.Initialise();
  62. return status;
  63. }
  64. private uint WaitOperationComplete(ICallback callback, uint timeout/*second*/)
  65. {
  66. if (null == callback)
  67. return ErrorCode.InvalidArgument;
  68. uint status = ErrorCode.Good;
  69. TimeSpan begin = new TimeSpan(DateTime.Now.Ticks);
  70. while (!callback.IsDone &&
  71. ((new TimeSpan(DateTime.Now.Ticks)) - begin).TotalSeconds <= timeout)
  72. {
  73. Thread.Sleep(100);
  74. }
  75. if (!callback.IsDone)
  76. {
  77. status = ErrorCode.Timeout;
  78. }
  79. return status;
  80. }
  81. private uint Connect(AXClient_t client)
  82. {
  83. if (null == client)
  84. return ErrorCode.InvalidArgument;
  85. //Connection type
  86. bool isConnectByIPAddr = true;
  87. bool isConnectViaGateWay = false;
  88. //Gateway IP, port
  89. string gatewayIPAddr = "127.0.0.1";
  90. string gatewayPort = "1217";
  91. //Device IP, port, logic address
  92. //string axIPAddr = "192.168.0.10";
  93. //string axPort = "11740";
  94. string axIPAddr = AxIP;
  95. string axPort = AxPort;
  96. string axAddress = "3001.50A8";
  97. //User, password
  98. string userName = "";
  99. string password = "";
  100. uint status;
  101. Console.ForegroundColor = ConsoleColor.Yellow;
  102. Console.WriteLine("===================== Start to Connect ====================");
  103. if (isConnectByIPAddr)
  104. {
  105. if (isConnectViaGateWay)
  106. status = client.ConnectViaGateway(gatewayIPAddr, gatewayPort, axIPAddr, axPort, userName, password);
  107. else
  108. status = client.Connect(axIPAddr, axPort, userName, password);
  109. }
  110. else
  111. {
  112. if (isConnectViaGateWay)
  113. status = client.ConnectViaGatewayByAddress(gatewayIPAddr, gatewayPort, axAddress, userName, password);
  114. else
  115. status = client.ConnectByAddress(axAddress, userName, password);
  116. }
  117. Console.ForegroundColor = ConsoleColor.Yellow;
  118. Console.WriteLine("==================== Connect Completed ===================\n");
  119. return status;
  120. }
  121. /// <summary>
  122. /// 连接PLC
  123. /// </summary>
  124. /// <returns>返回代码,0:成功,其它:失败</returns>
  125. public (uint rt,string errReason) ConnectPLC()
  126. {
  127. //BrowseDeviceCallback browseDeviceCB = new BrowseDeviceCallback();
  128. //rt = AXClient_t.BrowseAsync(null, null, browseDeviceCB);
  129. //if (rt != 0)
  130. // return (rt, "BrowseAsync");
  131. //rt =WaitOperationComplete(browseDeviceCB, 3/*seconds*/);
  132. //if (rt != 0)
  133. // return (rt, "WaitOperationComplete");
  134. var rt = Connect(client);
  135. if (rt != 0)
  136. {
  137. IsConnected = false;
  138. return (rt, "Connect Failed");
  139. }
  140. else
  141. {
  142. var r = ReadValue("Application.Var_state.al", out object al);
  143. if (r == 0 && al is bool b && !b)
  144. {
  145. Close();
  146. return (0x7FFFFFFF, "");
  147. }
  148. IsConnected = true;
  149. return (rt, "Connect Success");
  150. }
  151. }
  152. /// <summary>
  153. /// 关闭连接
  154. /// </summary>
  155. /// <returns>返回代码,0:成功,其它:失败</returns>
  156. public uint Close()
  157. {
  158. var rt=client.Disconnect();
  159. client.Dispose();
  160. return rt;
  161. }
  162. /// <summary>
  163. /// 读取指定地址和指定类型的值
  164. /// </summary>
  165. /// <param name="address">PLC地址字符串</param>
  166. /// <param name="result">返回的读取结果</param>
  167. /// <returns>返回代码,0:成功,其它:失败</returns>
  168. public uint ReadValue(string address, out object result)
  169. {
  170. DataItem_t dataItemFromRead = null;
  171. var status = client.Read(address, ref dataItemFromRead);
  172. if (ErrorCode.Good == status && dataItemFromRead != null)
  173. {
  174. result = dataItemFromRead.Value.Get();
  175. }
  176. else
  177. {
  178. result = null;
  179. }
  180. if (dataItemFromRead != null)
  181. {
  182. dataItemFromRead.Dispose();
  183. }
  184. return status;
  185. }
  186. /// <summary>
  187. /// 批量读取指定地址和指定类型的值
  188. /// </summary>
  189. /// <param name="addresses">PLC地址字符串列表</param>
  190. /// <param name="results">返回的读取结果列表</param>
  191. /// <returns>返回代码,0:成功,其它:失败</returns>
  192. public uint ReadValue(List<string> addresses, out List<object> results)
  193. {
  194. DataItem_t[] dataItemFromReadList = null;
  195. results = null;
  196. var status = client.Read(addresses.ToArray(), ref dataItemFromReadList);
  197. if (ErrorCode.Good == status && dataItemFromReadList != null)
  198. {
  199. results= dataItemFromReadList.Select(x => x.Value.Get()).ToList();
  200. }
  201. if (dataItemFromReadList != null)
  202. {
  203. foreach (var dataItem in dataItemFromReadList)
  204. dataItem.Dispose();
  205. }
  206. return status;
  207. }
  208. /// <summary>
  209. /// 写入指定类型的值到指定地址
  210. /// </summary>
  211. /// <param name="address"></param>
  212. /// <param name="value">要写入的值</param>
  213. /// <returns>返回代码,0:成功,其它:失败</returns>
  214. public uint WriteValue(string address, object value,ref uint result)
  215. {
  216. DataItem_t dataItemToWrite = new DataItem_t(value);
  217. //Write Symbol
  218. return client.Write(address, dataItemToWrite, ref result);
  219. }
  220. public uint WriteValue(List<string> addresses, List<object> values,ref List<uint> resultList)
  221. {
  222. uint[] results = null;
  223. DataItem_t[] dataItems= values.Select(v=> new DataItem_t(v)).ToArray();
  224. var status = client.Write(addresses.ToArray(), dataItems, ref results);
  225. resultList= results?.ToList();
  226. return status;
  227. }
  228. }
  229. public interface ICallback
  230. {
  231. bool IsDone
  232. {
  233. get;
  234. }
  235. }
  236. public class BrowseDeviceCallback : IBrowseDeviceCallback_t, ICallback
  237. {
  238. private bool m_isDone;
  239. private List<BrowsedDeviceInfo_t> m_axDevices = new List<BrowsedDeviceInfo_t>();
  240. public BrowseDeviceCallback()
  241. {
  242. }
  243. ~BrowseDeviceCallback()
  244. {
  245. m_axDevices.Clear();
  246. }
  247. public override void OnBrowseDevices(BrowsedDeviceInfo_t axDevice, uint status, bool bCompleted)
  248. {
  249. if (status == ErrorCode.Good && !bCompleted)
  250. {
  251. Console.ForegroundColor = ConsoleColor.Cyan;
  252. Console.WriteLine(">>>>>>>>>>>>>>>>>>>> Found A New Device <<<<<<<<<<<<<<<<<<<");
  253. }
  254. else if (status == ErrorCode.Failed && !bCompleted)
  255. {
  256. Console.ForegroundColor = ConsoleColor.Red;
  257. Console.WriteLine("Browse Error!");
  258. }
  259. m_isDone = bCompleted;
  260. if (bCompleted)
  261. {
  262. Console.ForegroundColor = ConsoleColor.Cyan;
  263. Console.WriteLine(">>>>>>>>>>>>>>>>>> No More New Device Found <<<<<<<<<<<<<<<");
  264. }
  265. }
  266. public bool IsDone
  267. {
  268. get { return m_isDone; }
  269. }
  270. }
  271. }