SiemensS7Net.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Sockets;
  5. using System.Text;
  6. using MECF.Framework.RT.Core.IoProviders.Siemens.IMessage;
  7. using MECF.Framework.RT.Core.IoProviders.Siemens.Net.NetworkBase;
  8. using MECF.Framework.RT.Core.IoProviders.Siemens.Transfer;
  9. namespace MECF.Framework.RT.Core.IoProviders.Siemens
  10. { /// <summary>
  11. /// 一个西门子的客户端类,使用S7协议来进行数据交互 ->
  12. /// A Siemens client class that uses the S7 protocol for data interaction
  13. /// </summary>
  14. /// <remarks>
  15. /// 地址支持的列表如下:
  16. /// <list type="table">
  17. /// <listheader>
  18. /// <term>地址名称</term>
  19. /// <term>地址代号</term>
  20. /// <term>示例</term>
  21. /// <term>地址进制</term>
  22. /// <term>字操作</term>
  23. /// <term>位操作</term>
  24. /// <term>备注</term>
  25. /// </listheader>
  26. /// <item>
  27. /// <term>中间寄存器</term>
  28. /// <term>M</term>
  29. /// <term>M100,M200</term>
  30. /// <term>10</term>
  31. /// <term>√</term>
  32. /// <term>√</term>
  33. /// <term></term>
  34. /// </item>
  35. /// <item>
  36. /// <term>输入寄存器</term>
  37. /// <term>I</term>
  38. /// <term>I100,I200</term>
  39. /// <term>10</term>
  40. /// <term>√</term>
  41. /// <term>√</term>
  42. /// <term></term>
  43. /// </item>
  44. /// <item>
  45. /// <term>输出寄存器</term>
  46. /// <term>Q</term>
  47. /// <term>Q100,Q200</term>
  48. /// <term>10</term>
  49. /// <term>√</term>
  50. /// <term>√</term>
  51. /// <term></term>
  52. /// </item>
  53. /// <item>
  54. /// <term>DB块寄存器</term>
  55. /// <term>DB</term>
  56. /// <term>DB1.100,DB1.200</term>
  57. /// <term>10</term>
  58. /// <term>√</term>
  59. /// <term>√</term>
  60. /// <term></term>
  61. /// </item>
  62. /// <item>
  63. /// <term>V寄存器</term>
  64. /// <term>V</term>
  65. /// <term>V100,V200</term>
  66. /// <term>10</term>
  67. /// <term>√</term>
  68. /// <term>√</term>
  69. /// <term>V寄存器本质就是DB块1</term>
  70. /// </item>
  71. /// <item>
  72. /// <term>定时器的值</term>
  73. /// <term>T</term>
  74. /// <term>T100,T200</term>
  75. /// <term>10</term>
  76. /// <term>√</term>
  77. /// <term>√</term>
  78. /// <term>未测试通过</term>
  79. /// </item>
  80. /// <item>
  81. /// <term>计数器的值</term>
  82. /// <term>C</term>
  83. /// <term>C100,C200</term>
  84. /// <term>10</term>
  85. /// <term>√</term>
  86. /// <term>√</term>
  87. /// <term>未测试通过</term>
  88. /// </item>
  89. /// </list>
  90. /// <note type="important">对于200smartPLC的V区,就是DB1.X,例如,V100=DB1.100</note>
  91. /// </remarks>
  92. /// <example>
  93. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="Usage" title="简单的短连接使用" />
  94. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="Usage2" title="简单的长连接使用" />
  95. /// </example>
  96. public class SiemensS7Net : NetworkDeviceBase<S7Message, ReverseBytesTransform>
  97. {
  98. #region Constructor
  99. /// <summary>
  100. /// 实例化一个西门子的S7协议的通讯对象 ->
  101. /// Instantiate a communication object for a Siemens S7 protocol
  102. /// </summary>
  103. /// <param name="siemens">指定西门子的型号</param>
  104. public SiemensS7Net(SiemensPLCS siemens)
  105. {
  106. Initialization(siemens, string.Empty);
  107. }
  108. /// <summary>
  109. /// 实例化一个西门子的S7协议的通讯对象并指定Ip地址 ->
  110. /// Instantiate a communication object for a Siemens S7 protocol and specify an IP address
  111. /// </summary>
  112. /// <param name="siemens">指定西门子的型号</param>
  113. /// <param name="ipAddress">Ip地址</param>
  114. public SiemensS7Net(SiemensPLCS siemens, string ipAddress)
  115. {
  116. Initialization(siemens, ipAddress);
  117. }
  118. /// <summary>
  119. /// 初始化方法 -> Initialize method
  120. /// </summary>
  121. /// <param name="siemens">指定西门子的型号 -> Designation of Siemens</param>
  122. /// <param name="ipAddress">Ip地址 -> IpAddress</param>
  123. private void Initialization(SiemensPLCS siemens, string ipAddress)
  124. {
  125. WordLength = 2;
  126. IpAddress = ipAddress;
  127. Port = 102;
  128. CurrentPlc = siemens;
  129. switch (siemens)
  130. {
  131. case SiemensPLCS.S1200: plcHead1[21] = 0; break;
  132. case SiemensPLCS.S300: plcHead1[21] = 2; break;
  133. case SiemensPLCS.S400: plcHead1[21] = 3; plcHead1[17] = 0x00; break;
  134. case SiemensPLCS.S1500: plcHead1[21] = 0; break;
  135. case SiemensPLCS.S200Smart:
  136. {
  137. plcHead1 = plcHead1_200smart;
  138. plcHead2 = plcHead2_200smart;
  139. break;
  140. }
  141. case SiemensPLCS.S200:
  142. {
  143. plcHead1 = plcHead1_200;
  144. plcHead2 = plcHead2_200;
  145. break;
  146. }
  147. default: plcHead1[18] = 0; break;
  148. }
  149. }
  150. /// <summary>
  151. /// PLC的槽号,针对S7-400的PLC设置的
  152. /// </summary>
  153. public byte Slot
  154. {
  155. get => plc_slot;
  156. set
  157. {
  158. plc_slot = value;
  159. plcHead1[21] = (byte)((this.plc_rack * 0x20) + this.plc_slot);
  160. }
  161. }
  162. /// <summary>
  163. /// PLC的机架号,针对S7-400的PLC设置的
  164. /// </summary>
  165. public byte Rack
  166. {
  167. get => plc_rack;
  168. set
  169. {
  170. this.plc_rack = value;
  171. plcHead1[21] = (byte)((this.plc_rack * 0x20) + this.plc_slot);
  172. }
  173. }
  174. /// <summary>
  175. /// 获取或设置当前PLC的连接方式,PG: 0x01,OP: 0x02,S7Basic: 0x03...0x10<br />
  176. /// Get or set the current PLC connection mode, PG: 0x01, OP: 0x02, S7Basic: 0x03...0x10
  177. /// </summary>
  178. public byte ConnectionType
  179. {
  180. get => this.plcHead1[20];
  181. set
  182. {
  183. if (CurrentPlc == SiemensPLCS.S200 ||
  184. CurrentPlc == SiemensPLCS.S200Smart)
  185. {
  186. }
  187. else
  188. {
  189. this.plcHead1[20] = value;
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// 西门子相关的本地TSAP参数信息<br />
  195. /// A parameter information related to Siemens
  196. /// </summary>
  197. public int LocalTSAP
  198. {
  199. get => this.plcHead1[16] * 256 + this.plcHead1[17];
  200. set
  201. {
  202. if (CurrentPlc == SiemensPLCS.S200 ||
  203. CurrentPlc == SiemensPLCS.S200Smart)
  204. {
  205. }
  206. else
  207. {
  208. this.plcHead1[16] = BitConverter.GetBytes(value)[1];
  209. this.plcHead1[17] = BitConverter.GetBytes(value)[0];
  210. }
  211. }
  212. }
  213. #endregion
  214. #region NetworkDoubleBase Override
  215. /// <summary>
  216. /// 连接上服务器后需要进行的二次握手操作 -> Two handshake actions required after connecting to the server
  217. /// </summary>
  218. /// <param name="socket">网络套接字 -> Network sockets</param>
  219. /// <returns>是否初始化成功,依据具体的协议进行重写 ->
  220. /// Whether the initialization succeeds and is rewritten according to the specific protocol</returns>
  221. protected override OperateResult InitializationOnConnect(Socket socket)
  222. {
  223. // 第一次握手 -> First handshake
  224. OperateResult<byte[]> read_first = ReadFromCoreServer(socket, plcHead1);
  225. if (!read_first.IsSuccess) return read_first;
  226. // 第二次握手 -> Second handshake
  227. OperateResult<byte[]> read_second = ReadFromCoreServer(socket, plcHead2);
  228. if (!read_second.IsSuccess) return read_second;
  229. // 返回成功的信号 -> Return a successful signal
  230. return OperateResult.CreateSuccessResult();
  231. }
  232. #endregion
  233. #region Read OrderNumber
  234. /// <summary>
  235. /// 从PLC读取订货号信息 -> Reading order number information from PLC
  236. /// </summary>
  237. /// <returns>CPU的订货号信息 -> Order number information for the CPU</returns>
  238. public OperateResult<string> ReadOrderNumber()
  239. {
  240. OperateResult<byte[]> read = ReadFromCoreServer(plcOrderNumber);
  241. if (!read.IsSuccess) return OperateResult.CreateFailedResult<string>(read);
  242. return OperateResult.CreateSuccessResult(Encoding.ASCII.GetString(read.Content, 71, 20));
  243. }
  244. #endregion
  245. #region Start Stop
  246. /// <summary>
  247. /// 对PLC进行热启动
  248. /// </summary>
  249. /// <returns>是否启动成功的结果对象</returns>
  250. public OperateResult HotStart()
  251. {
  252. OperateResult<byte[]> read = ReadFromCoreServer(S7_HOT_START);
  253. if (!read.IsSuccess) return read;
  254. if (read.Content.Length < 19) return new OperateResult("Receive error");
  255. if (read.Content[19] != pduStart) return new OperateResult("Can not start PLC");
  256. else if (read.Content[20] != pduAlreadyStarted) return new OperateResult("Can not start PLC");
  257. return OperateResult.CreateSuccessResult();
  258. }
  259. /// <summary>
  260. /// 对PLC进行冷启动
  261. /// </summary>
  262. /// <returns>是否启动成功的结果对象</returns>
  263. public OperateResult ColdStart()
  264. {
  265. OperateResult<byte[]> read = ReadFromCoreServer(S7_COLD_START);
  266. if (!read.IsSuccess) return read;
  267. if (read.Content.Length < 19) return new OperateResult("Receive error");
  268. if (read.Content[19] != pduStart) return new OperateResult("Can not start PLC");
  269. else if (read.Content[20] != pduAlreadyStarted) return new OperateResult("Can not start PLC");
  270. return OperateResult.CreateSuccessResult();
  271. }
  272. /// <summary>
  273. /// 对PLC进行停止
  274. /// </summary>
  275. /// <returns>是否启动成功的结果对象</returns>
  276. public OperateResult Stop()
  277. {
  278. OperateResult<byte[]> read = ReadFromCoreServer(S7_STOP);
  279. if (!read.IsSuccess) return read;
  280. if (read.Content.Length < 19) return new OperateResult("Receive error");
  281. if (read.Content[19] != pduStop) return new OperateResult("Can not stop PLC");
  282. else if (read.Content[20] != pduAlreadyStopped) return new OperateResult("Can not stop PLC");
  283. return OperateResult.CreateSuccessResult();
  284. }
  285. #endregion
  286. #region Read Support
  287. /// <summary>
  288. /// 从PLC读取数据,地址格式为I100,Q100,DB20.100,M100,T100,C100以字节为单位 ->
  289. /// Read data from PLC, address format I100,Q100,DB20.100,M100,T100,C100 in bytes
  290. /// </summary>
  291. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 ->
  292. /// Starting address, formatted as I100,M100,Q100,DB20.100</param>
  293. /// <param name="length">读取的数量,以字节为单位 -> The number of reads, in bytes</param>
  294. /// <returns>是否读取成功的结果对象 -> Whether to read the successful result object</returns>
  295. /// <remarks>
  296. /// <note type="important">对于200smartPLC的V区,就是DB1.X,例如,V100=DB1.100</note>
  297. /// </remarks>
  298. /// <example>
  299. /// 假设起始地址为M100,M100存储了温度,100.6℃值为1006,M102存储了压力,1.23Mpa值为123,M104,M105,M106,M107存储了产量计数,读取如下:
  300. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="ReadExample2" title="Read示例" />
  301. /// 以下是读取不同类型数据的示例
  302. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="ReadExample1" title="Read示例" />
  303. /// </example>
  304. public override OperateResult<byte[]> Read(string address, ushort length)
  305. {
  306. OperateResult<byte, int, ushort> addressResult = AnalysisAddress(address);
  307. if (!addressResult.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(addressResult);
  308. // 如果长度超过200,分批次读取 -> If the length is more than 200, read in batches
  309. List<byte> bytesContent = new List<byte>();
  310. ushort alreadyFinished = 0;
  311. while (alreadyFinished < length)
  312. {
  313. ushort readLength = (ushort)Math.Min(length - alreadyFinished, 200);
  314. OperateResult<byte[]> read = Read(new OperateResult<byte, int, ushort>[] { addressResult }, new ushort[] { readLength });
  315. if (!read.IsSuccess) return read;
  316. bytesContent.AddRange(read.Content);
  317. alreadyFinished += readLength;
  318. addressResult.Content2 += readLength * 8;
  319. }
  320. return OperateResult.CreateSuccessResult(bytesContent.ToArray());
  321. }
  322. /// <summary>
  323. /// 从PLC读取数据,地址格式为I100,Q100,DB20.100,M100,以位为单位 ->
  324. /// Read the data from the PLC, the address format is I100,Q100,DB20.100,M100, in bits units
  325. /// </summary>
  326. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 ->
  327. /// Starting address, formatted as I100,M100,Q100,DB20.100</param>
  328. /// <returns>是否读取成功的结果对象 -> Whether to read the successful result object</returns>
  329. private OperateResult<byte[]> ReadBitFromPLC(string address)
  330. {
  331. // 指令生成 -> Build bit read command
  332. OperateResult<byte[]> command = BuildBitReadCommand(address);
  333. if (!command.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(command);
  334. // 核心交互 -> Core interactive
  335. OperateResult<byte[]> read = ReadFromCoreServer(command.Content);
  336. if (!read.IsSuccess) return read;
  337. // 分析结果 -> Analysis read result
  338. int receiveCount = 1;
  339. if (read.Content.Length >= 21 && read.Content[20] == 1)
  340. {
  341. byte[] buffer = new byte[receiveCount];
  342. if (22 < read.Content.Length)
  343. {
  344. if (read.Content[21] == 0xFF &&
  345. read.Content[22] == 0x03)
  346. {
  347. buffer[0] = read.Content[25];
  348. }
  349. }
  350. return OperateResult.CreateSuccessResult(buffer);
  351. }
  352. else
  353. {
  354. return new OperateResult<byte[]>(read.ErrorCode, StringResources.Language.SiemensDataLengthCheckFailed);
  355. }
  356. }
  357. /// <summary>
  358. /// 一次性从PLC获取所有的数据,按照先后顺序返回一个统一的Buffer,需要按照顺序处理,两个数组长度必须一致 ->
  359. /// One-time from the PLC to obtain all the data, in order to return a unified buffer, need to be processed sequentially, two array length must be consistent
  360. /// </summary>
  361. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 ->
  362. /// Starting address, formatted as I100,M100,Q100,DB20.100</param>
  363. /// <param name="length">数据长度数组 -> Array of data Lengths</param>
  364. /// <returns>是否读取成功的结果对象 -> Whether to read the successful result object</returns>
  365. /// <exception cref="NullReferenceException"></exception>
  366. /// <remarks>
  367. /// <note type="warning">批量读取的长度有限制,最大为19个地址</note>
  368. /// </remarks>
  369. /// <example>
  370. /// 参照<see cref="Read(string, ushort)"/>
  371. /// </example>
  372. public OperateResult<byte[]> Read(string[] address, ushort[] length)
  373. {
  374. OperateResult<byte, int, ushort>[] addressResult = new OperateResult<byte, int, ushort>[address.Length];
  375. for (int i = 0; i < address.Length; i++)
  376. {
  377. OperateResult<byte, int, ushort> tmp = AnalysisAddress(address[i]);
  378. if (!tmp.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(addressResult[i]);
  379. addressResult[i] = tmp;
  380. }
  381. return Read(addressResult, length);
  382. }
  383. private OperateResult<byte[]> Read(OperateResult<byte, int, ushort>[] address, ushort[] length)
  384. {
  385. // 构建指令 -> Build read command
  386. OperateResult<byte[]> command = BuildReadCommand(address, length);
  387. if (!command.IsSuccess) return command;
  388. // 核心交互 -> Core Interactions
  389. OperateResult<byte[]> read = ReadFromCoreServer(command.Content);
  390. if (!read.IsSuccess) return read;
  391. // 分析结果 -> Analysis results
  392. int receiveCount = 0;
  393. for (int i = 0; i < length.Length; i++)
  394. {
  395. receiveCount += length[i];
  396. }
  397. if (read.Content.Length >= 21 && read.Content[20] == length.Length)
  398. {
  399. byte[] buffer = new byte[receiveCount];
  400. int kk = 0;
  401. int ll = 0;
  402. for (int ii = 21; ii < read.Content.Length; ii++)
  403. {
  404. if ((ii + 1) < read.Content.Length)
  405. {
  406. if (read.Content[ii] == 0xFF &&
  407. read.Content[ii + 1] == 0x04)
  408. {
  409. Array.Copy(read.Content, ii + 4, buffer, ll, length[kk]);
  410. ii += length[kk] + 3;
  411. ll += length[kk];
  412. kk++;
  413. }
  414. }
  415. }
  416. return OperateResult.CreateSuccessResult(buffer);
  417. }
  418. else
  419. {
  420. return new OperateResult<byte[]>(read.ErrorCode, StringResources.Language.SiemensDataLengthCheckFailed);
  421. }
  422. }
  423. /// <summary>
  424. /// 读取指定地址的bool数据,地址格式为I100,M100,Q100,DB20.100 ->
  425. /// reads bool data for the specified address in the format I100,M100,Q100,DB20.100
  426. /// </summary>
  427. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 ->
  428. /// Starting address, formatted as I100,M100,Q100,DB20.100</param>
  429. /// <returns>是否读取成功的结果对象 -> Whether to read the successful result object</returns>
  430. /// <remarks>
  431. /// <note type="important">
  432. /// 对于200smartPLC的V区,就是DB1.X,例如,V100=DB1.100
  433. /// </note>
  434. /// </remarks>
  435. /// <example>
  436. /// 假设读取M100.0的位是否通断
  437. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="ReadBool" title="ReadBool示例" />
  438. /// </example>
  439. public OperateResult<bool> ReadBool(string address)
  440. {
  441. return ByteTransformHelper.GetResultFromBytes(ReadBitFromPLC(address), m => m[0] != 0x00);
  442. }
  443. /// <summary>
  444. /// 读取指定地址的byte数据,地址格式I100,M100,Q100,DB20.100 ->
  445. /// Reads the byte data of the specified address, the address format I100,Q100,DB20.100,M100
  446. /// </summary>
  447. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 ->
  448. /// Starting address, formatted as I100,M100,Q100,DB20.100</param>
  449. /// <returns>是否读取成功的结果对象 -> Whether to read the successful result object</returns>
  450. /// <example>参考<see cref="Read(string, ushort)"/>的注释</example>
  451. public OperateResult<byte> ReadByte(string address)
  452. {
  453. return ByteTransformHelper.GetResultFromArray(Read(address, 1));
  454. }
  455. #endregion
  456. #region Write Base
  457. /// <summary>
  458. /// 基础的写入数据的操作支持 -> Operational support for the underlying write data
  459. /// </summary>
  460. /// <param name="entireValue">完整的字节数据 -> Full byte data</param>
  461. /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
  462. private OperateResult WriteBase(byte[] entireValue)
  463. {
  464. OperateResult<byte[]> write = ReadFromCoreServer(entireValue);
  465. if (!write.IsSuccess) return write;
  466. if (write.Content[write.Content.Length - 1] != 0xFF)
  467. {
  468. // 写入异常 -> WriteError
  469. return new OperateResult(write.Content[write.Content.Length - 1], StringResources.Language.SiemensWriteError + write.Content[write.Content.Length - 1]);
  470. }
  471. else
  472. {
  473. return OperateResult.CreateSuccessResult();
  474. }
  475. }
  476. /// <summary>
  477. /// 将数据写入到PLC数据,地址格式为I100,Q100,DB20.100,M100,以字节为单位 ->
  478. /// Writes data to the PLC data, in the address format I100,Q100,DB20.100,M100, in bytes
  479. /// </summary>
  480. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 ->
  481. /// Starting address, formatted as I100,M100,Q100,DB20.100</param>
  482. /// <param name="value">写入的原始数据 -> Raw data written to</param>
  483. /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
  484. /// <example>
  485. /// 假设起始地址为M100,M100,M101存储了温度,100.6℃值为1006,M102,M103存储了压力,1.23Mpa值为123,M104-M107存储了产量计数,写入如下:
  486. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="WriteExample2" title="Write示例" />
  487. /// 以下是写入不同类型数据的示例
  488. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="WriteExample1" title="Write示例" />
  489. /// </example>
  490. public override OperateResult Write(string address, byte[] value)
  491. {
  492. OperateResult<byte, int, ushort> analysis = AnalysisAddress(address);
  493. if (!analysis.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(analysis);
  494. int length = value.Length;
  495. ushort alreadyFinished = 0;
  496. while (alreadyFinished < length)
  497. {
  498. ushort writeLength = (ushort)Math.Min(length - alreadyFinished, 200);
  499. byte[] buffer = ByteTransform.TransByte(value, alreadyFinished, writeLength);
  500. OperateResult<byte[]> command = BuildWriteByteCommand(analysis, buffer);
  501. if (!command.IsSuccess) return command;
  502. OperateResult write = WriteBase(command.Content);
  503. if (!write.IsSuccess) return write;
  504. alreadyFinished += writeLength;
  505. analysis.Content2 += writeLength * 8;
  506. }
  507. return OperateResult.CreateSuccessResult();
  508. }
  509. /// <summary>
  510. /// 写入PLC的一个位,例如"M100.6","I100.7","Q100.0","DB20.100.0",如果只写了"M100"默认为"M100.0" ->
  511. /// Write a bit of PLC, for example "M100.6", "I100.7", "Q100.0", "DB20.100.0", if only write "M100" defaults to "M100.0"
  512. /// </summary>
  513. /// <param name="address">起始地址,格式为"M100.6", "I100.7", "Q100.0", "DB20.100.0" ->
  514. /// Start address, format "M100.6", "I100.7", "Q100.0", "DB20.100.0"</param>
  515. /// <param name="value">写入的数据,True或是False -> Writes the data, either True or False</param>
  516. /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
  517. /// <example>
  518. /// 假设写入M100.0的位是否通断
  519. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Profinet\SiemensS7Net.cs" region="WriteBool" title="WriteBool示例" />
  520. /// </example>
  521. public OperateResult Write(string address, bool value)
  522. {
  523. // 生成指令 -> Build Command
  524. OperateResult<byte[]> command = BuildWriteBitCommand(address, value);
  525. if (!command.IsSuccess) return command;
  526. return WriteBase(command.Content);
  527. }
  528. #endregion
  529. #region Write bool[]
  530. /// <summary>
  531. /// 向PLC中写入bool数组,比如你写入M100,那么data[0]对应M100.0 ->
  532. /// Write the bool array to the PLC, for example, if you write M100, then data[0] corresponds to M100.0
  533. /// </summary>
  534. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 -> Starting address, formatted as I100,mM100,Q100,DB20.100</param>
  535. /// <param name="values">要写入的bool数组,长度为8的倍数 -> The bool array to write, a multiple of 8 in length</param>
  536. /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
  537. /// <remarks>
  538. /// <note type="warning">
  539. /// 批量写入bool数组存在一定的风险,原因是只能批量写入长度为8的倍数的数组,否则会影响其他的位的数据,请谨慎使用。
  540. /// </note>
  541. /// </remarks>
  542. public OperateResult Write(string address, bool[] values)
  543. {
  544. return Write(address, SoftBasic.BoolArrayToByte(values));
  545. }
  546. #endregion
  547. #region Write Byte
  548. /// <summary>
  549. /// 向PLC中写入byte数据,返回值说明 -> Write byte data to the PLC, return value description
  550. /// </summary>
  551. /// <param name="address">起始地址,格式为I100,M100,Q100,DB20.100 -> Starting address, formatted as I100,mM100,Q100,DB20.100</param>
  552. /// <param name="value">byte数据 -> Byte data</param>
  553. /// <returns>是否写入成功的结果对象 -> Whether to write a successful result object</returns>
  554. public OperateResult Write(string address, byte value)
  555. {
  556. return Write(address, new byte[] { value });
  557. }
  558. #endregion
  559. #region ReadWrite String
  560. /// <summary>
  561. /// 向设备中写入字符串,编码格式为ASCII
  562. /// </summary>
  563. /// <param name="address">数据地址</param>
  564. /// <param name="value">字符串数据</param>
  565. /// <returns>是否写入成功的结果对象</returns>
  566. /// <example>
  567. /// 以下为三菱的连接对象示例,其他的设备读写情况参照下面的代码:
  568. /// <code lang="cs" source="HslCommunication_Net45.Test\Documentation\Samples\Core\NetworkDeviceBase.cs" region="WriteString" title="String类型示例" />
  569. /// </example>
  570. public override OperateResult Write(string address, string value)
  571. {
  572. if (value == null) value = string.Empty;
  573. byte[] buffer = Encoding.ASCII.GetBytes(value);
  574. if (CurrentPlc != SiemensPLCS.S200Smart)
  575. {
  576. // need read one time
  577. OperateResult<byte[]> readLength = Read(address, 2);
  578. if (!readLength.IsSuccess) return readLength;
  579. if (readLength.Content[0] == 255) return new OperateResult<string>("Value in plc is not string type");
  580. if (readLength.Content[0] == 0) readLength.Content[0] = 254; // allow to create new string
  581. if (value.Length > readLength.Content[0]) return new OperateResult<string>("String length is too long than plc defined");
  582. return Write(address, SoftBasic.SpliceTwoByteArray(new byte[] { readLength.Content[0], (byte)buffer.Length }, buffer));
  583. }
  584. else
  585. {
  586. return Write(address, SoftBasic.SpliceTwoByteArray(new byte[] { (byte)buffer.Length }, buffer));
  587. }
  588. }
  589. /// <summary>
  590. /// 读取西门子的地址的字符串信息,这个信息是和西门子绑定在一起,长度随西门子的信息动态变化的
  591. /// </summary>
  592. /// <param name="address">数据地址,具体的格式需要参照类的说明文档</param>
  593. /// <returns>带有是否成功的字符串结果类对象</returns>
  594. public OperateResult<string> ReadString(string address)
  595. {
  596. if (CurrentPlc != SiemensPLCS.S200Smart)
  597. {
  598. var read = Read(address, 2);
  599. if (!read.IsSuccess) return OperateResult.CreateFailedResult<string>(read);
  600. if (read.Content[0] == 0 || read.Content[0] == 255) return new OperateResult<string>("Value in plc is not string type"); // max string length can't be zero
  601. var readString = Read(address, (ushort)(2 + read.Content[1]));
  602. if (!readString.IsSuccess) return OperateResult.CreateFailedResult<string>(readString);
  603. return OperateResult.CreateSuccessResult(Encoding.ASCII.GetString(readString.Content, 2, readString.Content.Length - 2));
  604. }
  605. else
  606. {
  607. var read = Read(address, 1);
  608. if (!read.IsSuccess) return OperateResult.CreateFailedResult<string>(read);
  609. var readString = Read(address, (ushort)(1 + read.Content[0]));
  610. if (!readString.IsSuccess) return OperateResult.CreateFailedResult<string>(readString);
  611. return OperateResult.CreateSuccessResult(Encoding.ASCII.GetString(readString.Content, 1, readString.Content.Length - 1));
  612. }
  613. }
  614. #endregion
  615. #region Head Codes
  616. private byte[] plcHead1 = new byte[22]
  617. {
  618. 0x03,0x00,0x00,0x16,0x11,0xE0,0x00,0x00,0x00,0x01,0x00,0xC0,0x01,0x0A,0xC1,0x02,
  619. 0x01,0x02,0xC2,0x02,0x01,0x00
  620. };
  621. private byte[] plcHead2 = new byte[25]
  622. {
  623. 0x03,0x00,0x00,0x19,0x02,0xF0,0x80,0x32,0x01,0x00,0x00,0x04,0x00,0x00,0x08,0x00,
  624. 0x00,0xF0,0x00,0x00,0x01,0x00,0x01,0x01,0xE0
  625. };
  626. private byte[] plcOrderNumber = new byte[]
  627. {
  628. 0x03,0x00,0x00,0x21,0x02,0xF0,0x80,0x32,0x07,0x00,0x00,0x00,0x01,0x00,0x08,0x00,
  629. 0x08,0x00,0x01,0x12,0x04,0x11,0x44,0x01,0x00,0xFF,0x09,0x00,0x04,0x00,0x11,0x00,
  630. 0x00
  631. };
  632. private SiemensPLCS CurrentPlc = SiemensPLCS.S1200;
  633. private byte[] plcHead1_200smart = new byte[22]
  634. {
  635. 0x03,0x00,0x00,0x16,0x11,0xE0,0x00,0x00,0x00,0x01,0x00,0xC1,0x02,0x10,0x00,0xC2,
  636. 0x02,0x03,0x00,0xC0,0x01,0x0A
  637. };
  638. private byte[] plcHead2_200smart = new byte[25]
  639. {
  640. 0x03,0x00,0x00,0x19,0x02,0xF0,0x80,0x32,0x01,0x00,0x00,0xCC,0xC1,0x00,0x08,0x00,
  641. 0x00,0xF0,0x00,0x00,0x01,0x00,0x01,0x03,0xC0
  642. };
  643. private byte[] plcHead1_200 = new byte[]
  644. {
  645. 0x03,0x00,0x00,0x16,0x11,0xE0,0x00,0x00,0x00,0x01,0x00,0xC1,0x02,0x4D,0x57,0xC2,
  646. 0x02,0x4D,0x57,0xC0,0x01,0x09
  647. };
  648. private byte[] plcHead2_200 = new byte[]
  649. {
  650. 0x03,0x00,0x00,0x19,0x02,0xF0,0x80,0x32,0x01,0x00,0x00,0x00,0x00,0x00,0x08,0x00,
  651. 0x00,0xF0,0x00,0x00,0x01,0x00,0x01,0x03,0xC0
  652. };
  653. byte[] S7_STOP = {
  654. 0x03, 0x00, 0x00, 0x21, 0x02, 0xf0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x10, 0x00,
  655. 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x50, 0x5f, 0x50, 0x52, 0x4f, 0x47, 0x52, 0x41,
  656. 0x4d
  657. };
  658. byte[] S7_HOT_START = {
  659. 0x03, 0x00, 0x00, 0x25, 0x02, 0xf0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x14, 0x00,
  660. 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x00, 0x09, 0x50, 0x5f, 0x50, 0x52,
  661. 0x4f, 0x47, 0x52, 0x41, 0x4d
  662. };
  663. byte[] S7_COLD_START = {
  664. 0x03, 0x00, 0x00, 0x27, 0x02, 0xf0, 0x80, 0x32, 0x01, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x16, 0x00,
  665. 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfd, 0x00, 0x02, 0x43, 0x20, 0x09, 0x50, 0x5f,
  666. 0x50, 0x52, 0x4f, 0x47, 0x52, 0x41, 0x4d
  667. };
  668. #endregion
  669. #region Private Member
  670. private byte plc_rack = 0x00;
  671. private byte plc_slot = 0x00;
  672. const byte pduStart = 0x28; // CPU start
  673. const byte pduStop = 0x29; // CPU stop
  674. const byte pduAlreadyStarted = 0x02; // CPU already in run mode
  675. const byte pduAlreadyStopped = 0x07; // CPU already in stop mode
  676. #endregion
  677. #region Object Override
  678. /// <summary>
  679. /// 返回表示当前对象的字符串 -> Returns a String representing the current object
  680. /// </summary>
  681. /// <returns>字符串信息 -> String information</returns>
  682. public override string ToString()
  683. {
  684. return $"SiemensS7Net[{IpAddress}:{Port}]";
  685. }
  686. #endregion
  687. #region Static Method Helper
  688. /// <summary>
  689. /// 计算特殊的地址信息 -> Calculate Special Address information
  690. /// </summary>
  691. /// <param name="address">字符串地址 -> String address</param>
  692. /// <returns>实际值 -> Actual value</returns>
  693. public static int CalculateAddressStarted(string address)
  694. {
  695. if (address.IndexOf('.') < 0)
  696. {
  697. return Convert.ToInt32(address) * 8;
  698. }
  699. else
  700. {
  701. string[] temp = address.Split('.');
  702. return Convert.ToInt32(temp[0]) * 8 + Convert.ToInt32(temp[1]);
  703. }
  704. }
  705. /// <summary>
  706. /// 解析数据地址,解析出地址类型,起始地址,DB块的地址 ->
  707. /// Parse data address, parse out address type, start address, db block address
  708. /// </summary>
  709. /// <param name="address">起始地址,例如M100,I0,Q0,DB2.100 ->
  710. /// Start address, such as M100,I0,Q0,DB2.100</param>
  711. /// <returns>解析数据地址,解析出地址类型,起始地址,DB块的地址 ->
  712. /// Parse data address, parse out address type, start address, db block address</returns>
  713. public static OperateResult<byte, int, ushort> AnalysisAddress(string address)
  714. {
  715. var result = new OperateResult<byte, int, ushort>();
  716. try
  717. {
  718. result.Content3 = 0;
  719. if (address[0] == 'I')
  720. {
  721. result.Content1 = 0x81;
  722. result.Content2 = CalculateAddressStarted(address.Substring(1));
  723. }
  724. else if (address[0] == 'Q')
  725. {
  726. result.Content1 = 0x82;
  727. result.Content2 = CalculateAddressStarted(address.Substring(1));
  728. }
  729. else if (address[0] == 'M')
  730. {
  731. result.Content1 = 0x83;
  732. result.Content2 = CalculateAddressStarted(address.Substring(1));
  733. }
  734. else if (address[0] == 'D' || address.Substring(0, 2) == "DB")
  735. {
  736. result.Content1 = 0x84;
  737. string[] adds = address.Split('.');
  738. if (address[1] == 'B')
  739. {
  740. result.Content3 = Convert.ToUInt16(adds[0].Substring(2));
  741. }
  742. else
  743. {
  744. result.Content3 = Convert.ToUInt16(adds[0].Substring(1));
  745. }
  746. result.Content2 = CalculateAddressStarted(address.Substring(address.IndexOf('.') + 4));
  747. }
  748. else if (address[0] == 'T')
  749. {
  750. result.Content1 = 0x1D;
  751. result.Content2 = CalculateAddressStarted(address.Substring(1));
  752. }
  753. else if (address[0] == 'C')
  754. {
  755. result.Content1 = 0x1C;
  756. result.Content2 = CalculateAddressStarted(address.Substring(1));
  757. }
  758. else if (address[0] == 'V')
  759. {
  760. result.Content1 = 0x84;
  761. result.Content3 = 1;
  762. result.Content2 = CalculateAddressStarted(address.Substring(1));
  763. }
  764. else
  765. {
  766. result.Message = StringResources.Language.NotSupportedDataType;
  767. result.Content1 = 0;
  768. result.Content2 = 0;
  769. result.Content3 = 0;
  770. return result;
  771. }
  772. }
  773. catch (Exception ex)
  774. {
  775. result.Message = ex.Message;
  776. return result;
  777. }
  778. result.IsSuccess = true;
  779. return result;
  780. }
  781. #endregion
  782. #region Build Command
  783. /// <summary>
  784. /// 生成一个读取字数据指令头的通用方法 ->
  785. /// A general method for generating a command header to read a Word data
  786. /// </summary>
  787. /// <param name="address">起始地址,例如M100,I0,Q0,DB2.100 ->
  788. /// Start address, such as M100,I0,Q0,DB2.100</param>
  789. /// <param name="length">读取数据长度 -> Read Data length</param>
  790. /// <returns>包含结果对象的报文 -> Message containing the result object</returns>
  791. public static OperateResult<byte[]> BuildReadCommand(string address, ushort length)
  792. {
  793. OperateResult<byte, int, ushort> analysis = AnalysisAddress(address);
  794. if (!analysis.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(analysis);
  795. return BuildReadCommand(new OperateResult<byte, int, ushort>[] { analysis }, new ushort[] { length });
  796. }
  797. /// <summary>
  798. /// 生成一个读取字数据指令头的通用方法 ->
  799. /// A general method for generating a command header to read a Word data
  800. /// </summary>
  801. /// <param name="address">起始地址,例如M100,I0,Q0,DB2.100 ->
  802. /// Start address, such as M100,I0,Q0,DB2.100</param>
  803. /// <param name="length">读取数据长度 -> Read Data length</param>
  804. /// <returns>包含结果对象的报文 -> Message containing the result object</returns>
  805. public static OperateResult<byte[]> BuildReadCommand(OperateResult<byte, int, ushort>[] address, ushort[] length)
  806. {
  807. if (address == null) throw new NullReferenceException("address");
  808. if (length == null) throw new NullReferenceException("count");
  809. if (address.Length != length.Length) throw new Exception(StringResources.Language.TwoParametersLengthIsNotSame);
  810. if (length.Length > 19) throw new Exception(StringResources.Language.SiemensReadLengthCannotLargerThan19);
  811. int readCount = length.Length;
  812. byte[] _PLCCommand = new byte[19 + readCount * 12];
  813. // ======================================================================================
  814. _PLCCommand[0] = 0x03; // 报文头 -> Head
  815. _PLCCommand[1] = 0x00;
  816. _PLCCommand[2] = (byte)(_PLCCommand.Length / 256); // 长度 -> Length
  817. _PLCCommand[3] = (byte)(_PLCCommand.Length % 256);
  818. _PLCCommand[4] = 0x02; // 固定 -> Fixed
  819. _PLCCommand[5] = 0xF0;
  820. _PLCCommand[6] = 0x80;
  821. _PLCCommand[7] = 0x32; // 协议标识 -> Protocol identification
  822. _PLCCommand[8] = 0x01; // 命令:发 -> Command: Send
  823. _PLCCommand[9] = 0x00; // redundancy identification (reserved): 0x0000;
  824. _PLCCommand[10] = 0x00; // protocol data unit reference; it’s increased by request event;
  825. _PLCCommand[11] = 0x00;
  826. _PLCCommand[12] = 0x01; // 参数命令数据总长度 -> Parameter command Data total length
  827. _PLCCommand[13] = (byte)((_PLCCommand.Length - 17) / 256);
  828. _PLCCommand[14] = (byte)((_PLCCommand.Length - 17) % 256);
  829. _PLCCommand[15] = 0x00; // 读取内部数据时为00,读取CPU型号为Data数据长度 -> Read internal data is 00, read CPU model is data length
  830. _PLCCommand[16] = 0x00;
  831. // =====================================================================================
  832. _PLCCommand[17] = 0x04; // 读写指令,04读,05写 -> Read-write instruction, 04 read, 05 Write
  833. _PLCCommand[18] = (byte)readCount; // 读取数据块个数 -> Number of data blocks read
  834. for (int ii = 0; ii < readCount; ii++)
  835. {
  836. //===========================================================================================
  837. // 指定有效值类型 -> Specify a valid value type
  838. _PLCCommand[19 + ii * 12] = 0x12;
  839. // 接下来本次地址访问长度 -> The next time the address access length
  840. _PLCCommand[20 + ii * 12] = 0x0A;
  841. // 语法标记,ANY -> Syntax tag, any
  842. _PLCCommand[21 + ii * 12] = 0x10;
  843. // 按字为单位 -> by word
  844. _PLCCommand[22 + ii * 12] = 0x02; // (byte)(address[ii].Content1 == 0x1D ? 0x1D : address[ii].Content1 == 0x1C ? 0x1C : 0x02);
  845. // 访问数据的个数 -> Number of Access data
  846. _PLCCommand[23 + ii * 12] = (byte)(length[ii] / 256);
  847. _PLCCommand[24 + ii * 12] = (byte)(length[ii] % 256);
  848. // DB块编号,如果访问的是DB块的话 -> DB block number, if you are accessing a DB block
  849. _PLCCommand[25 + ii * 12] = (byte)(address[ii].Content3 / 256);
  850. _PLCCommand[26 + ii * 12] = (byte)(address[ii].Content3 % 256);
  851. // 访问数据类型 -> Accessing data types
  852. _PLCCommand[27 + ii * 12] = address[ii].Content1;
  853. // 偏移位置 -> Offset position
  854. _PLCCommand[28 + ii * 12] = (byte)(address[ii].Content2 / 256 / 256 % 256);
  855. _PLCCommand[29 + ii * 12] = (byte)(address[ii].Content2 / 256 % 256);
  856. _PLCCommand[30 + ii * 12] = (byte)(address[ii].Content2 % 256);
  857. }
  858. return OperateResult.CreateSuccessResult(_PLCCommand);
  859. }
  860. /// <summary>
  861. /// 生成一个位读取数据指令头的通用方法 ->
  862. /// A general method for generating a bit-read-Data instruction header
  863. /// </summary>
  864. /// <param name="address">起始地址,例如M100.0,I0.1,Q0.1,DB2.100.2 ->
  865. /// Start address, such as M100.0,I0.1,Q0.1,DB2.100.2
  866. /// </param>
  867. /// <returns>包含结果对象的报文 -> Message containing the result object</returns>
  868. public static OperateResult<byte[]> BuildBitReadCommand(string address)
  869. {
  870. OperateResult<byte, int, ushort> analysis = AnalysisAddress(address);
  871. if (!analysis.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(analysis);
  872. byte[] _PLCCommand = new byte[31];
  873. _PLCCommand[0] = 0x03;
  874. _PLCCommand[1] = 0x00;
  875. // 长度 -> Length
  876. _PLCCommand[2] = (byte)(_PLCCommand.Length / 256);
  877. _PLCCommand[3] = (byte)(_PLCCommand.Length % 256);
  878. // 固定 -> Fixed
  879. _PLCCommand[4] = 0x02;
  880. _PLCCommand[5] = 0xF0;
  881. _PLCCommand[6] = 0x80;
  882. _PLCCommand[7] = 0x32;
  883. // 命令:发 -> command to send
  884. _PLCCommand[8] = 0x01;
  885. // 标识序列号
  886. _PLCCommand[9] = 0x00;
  887. _PLCCommand[10] = 0x00;
  888. _PLCCommand[11] = 0x00;
  889. _PLCCommand[12] = 0x01;
  890. // 命令数据总长度 -> Identification serial Number
  891. _PLCCommand[13] = (byte)((_PLCCommand.Length - 17) / 256);
  892. _PLCCommand[14] = (byte)((_PLCCommand.Length - 17) % 256);
  893. _PLCCommand[15] = 0x00;
  894. _PLCCommand[16] = 0x00;
  895. // 命令起始符 -> Command start character
  896. _PLCCommand[17] = 0x04;
  897. // 读取数据块个数 -> Number of data blocks read
  898. _PLCCommand[18] = 0x01;
  899. //===========================================================================================
  900. // 读取地址的前缀 -> Read the prefix of the address
  901. _PLCCommand[19] = 0x12;
  902. _PLCCommand[20] = 0x0A;
  903. _PLCCommand[21] = 0x10;
  904. // 读取的数据时位 -> Data read-time bit
  905. _PLCCommand[22] = 0x01;
  906. // 访问数据的个数 -> Number of Access data
  907. _PLCCommand[23] = 0x00;
  908. _PLCCommand[24] = 0x01;
  909. // DB块编号,如果访问的是DB块的话 -> DB block number, if you are accessing a DB block
  910. _PLCCommand[25] = (byte)(analysis.Content3 / 256);
  911. _PLCCommand[26] = (byte)(analysis.Content3 % 256);
  912. // 访问数据类型 -> Types of reading data
  913. _PLCCommand[27] = analysis.Content1;
  914. // 偏移位置 -> Offset position
  915. _PLCCommand[28] = (byte)(analysis.Content2 / 256 / 256 % 256);
  916. _PLCCommand[29] = (byte)(analysis.Content2 / 256 % 256);
  917. _PLCCommand[30] = (byte)(analysis.Content2 % 256);
  918. return OperateResult.CreateSuccessResult(_PLCCommand);
  919. }
  920. /// <summary>
  921. /// 生成一个写入字节数据的指令 -> Generate an instruction to write byte data
  922. /// </summary>
  923. /// <param name="address">起始地址,示例M100,I100,Q100,DB1.100 -> Start Address, example M100,I100,Q100,DB1.100</param>
  924. /// <param name="data">原始的字节数据 -> Raw byte data</param>
  925. /// <returns>包含结果对象的报文 -> Message containing the result object</returns>
  926. public static OperateResult<byte[]> BuildWriteByteCommand(string address, byte[] data)
  927. {
  928. if (data == null) data = new byte[0];
  929. OperateResult<byte, int, ushort> analysis = AnalysisAddress(address);
  930. if (!analysis.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(analysis);
  931. return BuildWriteByteCommand(analysis, data);
  932. }
  933. /// <summary>
  934. /// 生成一个写入字节数据的指令 -> Generate an instruction to write byte data
  935. /// </summary>
  936. /// <param name="analysis">起始地址,示例M100,I100,Q100,DB1.100 -> Start Address, example M100,I100,Q100,DB1.100</param>
  937. /// <param name="data">原始的字节数据 -> Raw byte data</param>
  938. /// <returns>包含结果对象的报文 -> Message containing the result object</returns>
  939. public static OperateResult<byte[]> BuildWriteByteCommand(OperateResult<byte, int, ushort> analysis, byte[] data)
  940. {
  941. byte[] _PLCCommand = new byte[35 + data.Length];
  942. _PLCCommand[0] = 0x03;
  943. _PLCCommand[1] = 0x00;
  944. // 长度 -> Length
  945. _PLCCommand[2] = (byte)((35 + data.Length) / 256);
  946. _PLCCommand[3] = (byte)((35 + data.Length) % 256);
  947. // 固定 -> Fixed
  948. _PLCCommand[4] = 0x02;
  949. _PLCCommand[5] = 0xF0;
  950. _PLCCommand[6] = 0x80;
  951. _PLCCommand[7] = 0x32;
  952. // 命令 发 -> command to send
  953. _PLCCommand[8] = 0x01;
  954. // 标识序列号 -> Identification serial Number
  955. _PLCCommand[9] = 0x00;
  956. _PLCCommand[10] = 0x00;
  957. _PLCCommand[11] = 0x00;
  958. _PLCCommand[12] = 0x01;
  959. // 固定 -> Fixed
  960. _PLCCommand[13] = 0x00;
  961. _PLCCommand[14] = 0x0E;
  962. // 写入长度+4 -> Write Length +4
  963. _PLCCommand[15] = (byte)((4 + data.Length) / 256);
  964. _PLCCommand[16] = (byte)((4 + data.Length) % 256);
  965. // 读写指令 -> Read and write instructions
  966. _PLCCommand[17] = 0x05;
  967. // 写入数据块个数 -> Number of data blocks written
  968. _PLCCommand[18] = 0x01;
  969. // 固定,返回数据长度 -> Fixed, return data length
  970. _PLCCommand[19] = 0x12;
  971. _PLCCommand[20] = 0x0A;
  972. _PLCCommand[21] = 0x10;
  973. // 写入方式,1是按位,2是按字 -> Write mode, 1 is bitwise, 2 is by word
  974. _PLCCommand[22] = 0x02;
  975. // 写入数据的个数 -> Number of Write Data
  976. _PLCCommand[23] = (byte)(data.Length / 256);
  977. _PLCCommand[24] = (byte)(data.Length % 256);
  978. // DB块编号,如果访问的是DB块的话 -> DB block number, if you are accessing a DB block
  979. _PLCCommand[25] = (byte)(analysis.Content3 / 256);
  980. _PLCCommand[26] = (byte)(analysis.Content3 % 256);
  981. // 写入数据的类型 -> Types of writing data
  982. _PLCCommand[27] = analysis.Content1;
  983. // 偏移位置 -> Offset position
  984. _PLCCommand[28] = (byte)(analysis.Content2 / 256 / 256 % 256); ;
  985. _PLCCommand[29] = (byte)(analysis.Content2 / 256 % 256);
  986. _PLCCommand[30] = (byte)(analysis.Content2 % 256);
  987. // 按字写入 -> Write by Word
  988. _PLCCommand[31] = 0x00;
  989. _PLCCommand[32] = 0x04;
  990. // 按位计算的长度 -> The length of the bitwise calculation
  991. _PLCCommand[33] = (byte)(data.Length * 8 / 256);
  992. _PLCCommand[34] = (byte)(data.Length * 8 % 256);
  993. data.CopyTo(_PLCCommand, 35);
  994. return OperateResult.CreateSuccessResult(_PLCCommand);
  995. }
  996. /// <summary>
  997. /// 生成一个写入位数据的指令 -> Generate an instruction to write bit data
  998. /// </summary>
  999. /// <param name="address">起始地址,示例M100,I100,Q100,DB1.100 -> Start Address, example M100,I100,Q100,DB1.100</param>
  1000. /// <param name="data">是否通断 -> Power on or off</param>
  1001. /// <returns>包含结果对象的报文 -> Message containing the result object</returns>
  1002. public static OperateResult<byte[]> BuildWriteBitCommand(string address, bool data)
  1003. {
  1004. OperateResult<byte, int, ushort> analysis = AnalysisAddress(address);
  1005. if (!analysis.IsSuccess) return OperateResult.CreateFailedResult<byte[]>(analysis);
  1006. byte[] buffer = new byte[1];
  1007. buffer[0] = data ? (byte)0x01 : (byte)0x00;
  1008. byte[] _PLCCommand = new byte[35 + buffer.Length];
  1009. _PLCCommand[0] = 0x03;
  1010. _PLCCommand[1] = 0x00;
  1011. // 长度 -> length
  1012. _PLCCommand[2] = (byte)((35 + buffer.Length) / 256);
  1013. _PLCCommand[3] = (byte)((35 + buffer.Length) % 256);
  1014. // 固定 -> fixed
  1015. _PLCCommand[4] = 0x02;
  1016. _PLCCommand[5] = 0xF0;
  1017. _PLCCommand[6] = 0x80;
  1018. _PLCCommand[7] = 0x32;
  1019. // 命令 发 -> command to send
  1020. _PLCCommand[8] = 0x01;
  1021. // 标识序列号 -> Identification serial Number
  1022. _PLCCommand[9] = 0x00;
  1023. _PLCCommand[10] = 0x00;
  1024. _PLCCommand[11] = 0x00;
  1025. _PLCCommand[12] = 0x01;
  1026. // 固定 -> fixed
  1027. _PLCCommand[13] = 0x00;
  1028. _PLCCommand[14] = 0x0E;
  1029. // 写入长度+4 -> Write Length +4
  1030. _PLCCommand[15] = (byte)((4 + buffer.Length) / 256);
  1031. _PLCCommand[16] = (byte)((4 + buffer.Length) % 256);
  1032. // 命令起始符 -> Command start character
  1033. _PLCCommand[17] = 0x05;
  1034. // 写入数据块个数 -> Number of data blocks written
  1035. _PLCCommand[18] = 0x01;
  1036. _PLCCommand[19] = 0x12;
  1037. _PLCCommand[20] = 0x0A;
  1038. _PLCCommand[21] = 0x10;
  1039. // 写入方式,1是按位,2是按字 -> Write mode, 1 is bitwise, 2 is by word
  1040. _PLCCommand[22] = 0x01;
  1041. // 写入数据的个数 -> Number of Write Data
  1042. _PLCCommand[23] = (byte)(buffer.Length / 256);
  1043. _PLCCommand[24] = (byte)(buffer.Length % 256);
  1044. // DB块编号,如果访问的是DB块的话 -> DB block number, if you are accessing a DB block
  1045. _PLCCommand[25] = (byte)(analysis.Content3 / 256);
  1046. _PLCCommand[26] = (byte)(analysis.Content3 % 256);
  1047. // 写入数据的类型 -> Types of writing data
  1048. _PLCCommand[27] = analysis.Content1;
  1049. // 偏移位置 -> Offset position
  1050. _PLCCommand[28] = (byte)(analysis.Content2 / 256 / 256);
  1051. _PLCCommand[29] = (byte)(analysis.Content2 / 256);
  1052. _PLCCommand[30] = (byte)(analysis.Content2 % 256);
  1053. // 按位写入 -> Bitwise Write
  1054. _PLCCommand[31] = 0x00;
  1055. _PLCCommand[32] = 0x03;
  1056. // 按位计算的长度 -> The length of the bitwise calculation
  1057. _PLCCommand[33] = (byte)(buffer.Length / 256);
  1058. _PLCCommand[34] = (byte)(buffer.Length % 256);
  1059. buffer.CopyTo(_PLCCommand, 35);
  1060. return OperateResult.CreateSuccessResult(_PLCCommand);
  1061. }
  1062. #endregion
  1063. }
  1064. }