S7NetTestsAsync.cs 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. #region Using
  2. using System;
  3. using System.Collections.Generic;
  4. using Microsoft.VisualStudio.TestTools.UnitTesting;
  5. using S7.Net.UnitTest.Helpers;
  6. using S7.Net.Types;
  7. using S7.UnitTest.Helpers;
  8. using System.Threading.Tasks;
  9. using System.Threading;
  10. using System.Security.Cryptography;
  11. #if NET5_0_OR_GREATER
  12. using System.Buffers;
  13. #endif
  14. #endregion
  15. /**
  16. * About the tests:
  17. * ---------------------------------------------------------------------------
  18. * The tests were written to show how to use this library to read and write
  19. * different types of values, how to box and unbox values and of course to
  20. * address some of the bugs of the library.
  21. * These tests are not meant to cover 100% the code, but to check that once a
  22. * variable is written, it stores the correct value.
  23. * ----------------------------------------------------------------------------
  24. * The plc used for the tests is the S7 "server" provided by Snap7 opensource
  25. * library, that you can get for free here:http://snap7.sourceforge.net/
  26. * The implementation of the server will not be discussed here, but there are
  27. * some issues with the interop that cause the server, and unit test, to fail
  28. * under some circumstances, like "click on Run all tests" too much.
  29. * This doesn't mean that S7.Net has bugs, but that the implementation of the
  30. * server has problems.
  31. *
  32. */
  33. //Tests for Async Methods
  34. namespace S7.Net.UnitTest
  35. {
  36. public partial class S7NetTests
  37. {
  38. #region Tests
  39. [TestMethod]
  40. public async Task Test_Async_Connection()
  41. {
  42. if (plc.IsConnected == false)
  43. {
  44. await plc.OpenAsync();
  45. }
  46. }
  47. /// <summary>
  48. /// Read/Write a single Int16 or UInt16 with a single request.
  49. /// Test that writing a UInt16 (ushort) and reading it gives the correct value.
  50. /// Test also that writing a Int16 (short) and reading it gives the correct value.
  51. /// </summary>
  52. [TestMethod]
  53. public async Task Test_Async_WriteAndReadInt16Variable()
  54. {
  55. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  56. // To write a ushort i don't need any cast, only unboxing must be done
  57. ushort val = 40000;
  58. await plc.WriteAsync("DB1.DBW0", val);
  59. ushort result = (ushort)await plc.ReadAsync("DB1.DBW0");
  60. Assert.AreEqual(val, result, "A ushort goes from 0 to 64512");
  61. // To write a short i need to convert it to UShort, then i need to reconvert the readed value to get
  62. // the negative sign back
  63. // Depending if i'm writing on a DWORD or on a DEC, i will see ushort or short value in the plc
  64. short value = -100;
  65. Assert.IsTrue(plc.IsConnected, "After connecting, IsConnected must be set to true");
  66. await plc.WriteAsync("DB1.DBW0", value.ConvertToUshort());
  67. short result2 = ((ushort)await plc.ReadAsync("DB1.DBW0")).ConvertToShort();
  68. Assert.AreEqual(value, result2, "A short goes from -32767 to 32766");
  69. }
  70. /// <summary>
  71. /// Read/Write a single Int32 or UInt32 with a single request.
  72. /// Test that writing a UInt32 (uint) and reading it gives the correct value.
  73. /// Test also that writing a Int32 (int) and reading it gives the correct value.
  74. /// </summary>
  75. [TestMethod]
  76. public async Task Test_Async_WriteAndReadInt32Variable()
  77. {
  78. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  79. // To write a uint I don't need any cast, only unboxing must be done
  80. int val = 1000;
  81. await plc.WriteAsync("DB1.DBD40", val);
  82. int result = ((uint)await plc.ReadAsync("DB1.DBD40")).ConvertToInt();
  83. Assert.AreEqual(val, result);
  84. // To write a int I need to convert it to uint, then I need to reconvert the readed value to get
  85. // the negative sign back
  86. // Depending if I'm writing on a DBD or on a LONG, I will see uint or int value in the plc
  87. int value = -60000;
  88. await plc.WriteAsync("DB1.DBD60", value);
  89. int result2 = ((uint)await plc.ReadAsync("DB1.DBD60")).ConvertToInt();
  90. Assert.AreEqual(value, result2);
  91. }
  92. /// <summary>
  93. /// Read/Write a single REAL with a single request.
  94. /// Test that writing a float and reading it gives the correct value.
  95. /// </summary>
  96. [TestMethod]
  97. public async Task Test_Async_WriteAndReadRealVariables()
  98. {
  99. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  100. // Reading and writing a float is quite complicated, because it needs to be converted to DWord before the write,
  101. // then reconvert to float after the read. Float values can contain only 7 digits, so no precision is lost.
  102. float val2 = 1234567;
  103. await plc.WriteAsync("DB1.DBD40", val2.ConvertToUInt());
  104. float result2 = ((uint)await plc.ReadAsync("DB1.DBD40")).ConvertToFloat();
  105. Assert.AreEqual(val2, result2);
  106. float val3 = 12.34567f;
  107. await plc.WriteAsync("DB1.DBD40", val3.ConvertToUInt());
  108. float result3 = ((uint)await plc.ReadAsync("DB1.DBD40")).ConvertToFloat();
  109. Assert.AreEqual(val3, result3);
  110. }
  111. /// <summary>
  112. /// Write/Read a large amount of data to test PDU max
  113. /// </summary>
  114. [TestMethod]
  115. public async Task Test_Async_WriteLargeByteArray()
  116. {
  117. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  118. var randomEngine = new Random();
  119. var data = new byte[8192];
  120. var db = 2;
  121. randomEngine.NextBytes(data);
  122. await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data);
  123. var readData = await plc.ReadBytesAsync(DataType.DataBlock, db, 0, data.Length);
  124. CollectionAssert.AreEqual(data, readData);
  125. }
  126. #if NET5_0_OR_GREATER
  127. /// <summary>
  128. /// Write/Read a large amount of data to test PDU max
  129. /// </summary>
  130. [TestMethod]
  131. public async Task Test_Async_WriteLargeByteArrayWithMemory()
  132. {
  133. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  134. var randomEngine = new Random();
  135. using var dataOwner = MemoryPool<byte>.Shared.Rent(8192);
  136. var data = dataOwner.Memory.Slice(0, 8192);
  137. var db = 2;
  138. randomEngine.NextBytes(data.Span);
  139. await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data);
  140. using var readDataOwner = MemoryPool<byte>.Shared.Rent(data.Length);
  141. var readData = readDataOwner.Memory.Slice(0, data.Length);
  142. await plc.ReadBytesAsync(readData, DataType.DataBlock, db, 0);
  143. CollectionAssert.AreEqual(data.ToArray(), readData.ToArray());
  144. }
  145. #endif
  146. /// <summary>
  147. /// Read/Write a class that has the same properties of a DB with the same field in the same order
  148. /// </summary>
  149. [TestMethod]
  150. public async Task Test_Async_ReadAndWriteClass()
  151. {
  152. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  153. TestClass tc = new TestClass
  154. {
  155. BitVariable00 = true,
  156. BitVariable10 = true,
  157. DIntVariable = -100000,
  158. IntVariable = -15000,
  159. LRealVariable = -154.789,
  160. RealVariable = -154.789f,
  161. DWordVariable = 850,
  162. WStringVariable = "ÄÜÉÊéà",
  163. StringVariable = "Hallo"
  164. };
  165. await plc.WriteClassAsync(tc, DB2);
  166. TestClass tc2 = new TestClass();
  167. // Values that are read from a class are stored inside the class itself, that is passed by reference
  168. await plc.ReadClassAsync(tc2, DB2);
  169. Assert.AreEqual(tc.BitVariable00, tc2.BitVariable00);
  170. Assert.AreEqual(tc.BitVariable10, tc2.BitVariable10);
  171. Assert.AreEqual(tc.DIntVariable, tc2.DIntVariable);
  172. Assert.AreEqual(tc.IntVariable, tc2.IntVariable);
  173. Assert.AreEqual(tc.LRealVariable, tc2.LRealVariable);
  174. Assert.AreEqual(tc.RealVariable, tc2.RealVariable);
  175. Assert.AreEqual(tc.DWordVariable, tc2.DWordVariable);
  176. Assert.AreEqual(tc.WStringVariable, tc2.WStringVariable);
  177. Assert.AreEqual(tc.StringVariable, tc2.StringVariable);
  178. }
  179. [TestMethod]
  180. public async Task Test_Async_ReadAndWriteNestedClass()
  181. {
  182. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  183. TestClassWithNestedClass tc = new TestClassWithNestedClass
  184. {
  185. BitVariable00 = true,
  186. BitVariable01 = new TestClassInnerWithBool { BitVariable00 = true },
  187. ByteVariable02 = new TestClassInnerWithByte { ByteVariable00 = 128 },
  188. BitVariable03 = true,
  189. ShortVariable04 = new TestClassInnerWithShort { ShortVarialbe00 = -15000 }
  190. };
  191. await plc.WriteClassAsync(tc, DB4);
  192. TestClassWithNestedClass tc2 = new TestClassWithNestedClass();
  193. // Values that are read from a class are stored inside the class itself, that is passed by reference
  194. await plc.ReadClassAsync(tc2, DB4);
  195. Assert.AreEqual(tc.BitVariable00, tc2.BitVariable00);
  196. Assert.AreEqual(tc.BitVariable01.BitVariable00, tc2.BitVariable01.BitVariable00);
  197. Assert.AreEqual(tc.ByteVariable02.ByteVariable00, tc2.ByteVariable02.ByteVariable00);
  198. Assert.AreEqual(tc.BitVariable03, tc2.BitVariable03);
  199. Assert.AreEqual(tc.ShortVariable04.ShortVarialbe00, tc2.ShortVariable04.ShortVarialbe00);
  200. }
  201. /// <summary>
  202. /// Read/Write a struct that has the same properties of a DB with the same field in the same order
  203. /// </summary>
  204. [TestMethod]
  205. public async Task Test_Async_ReadAndWriteStruct()
  206. {
  207. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  208. TestStruct tc = new TestStruct
  209. {
  210. BitVariable00 = true,
  211. BitVariable10 = true,
  212. DIntVariable = -100000,
  213. IntVariable = -15000,
  214. LRealVariable = -154.789,
  215. RealVariable = -154.789f,
  216. DWordVariable = 850,
  217. WStringVariable = "ÄÜÉÊéà",
  218. StringVariable = "Hallo"
  219. };
  220. plc.WriteStruct(tc, DB2);
  221. // Values that are read from a struct are stored in a new struct, returned by the funcion ReadStruct
  222. TestStruct tc2 = (TestStruct)await plc.ReadStructAsync(typeof(TestStruct), DB2);
  223. Assert.AreEqual(tc.BitVariable00, tc2.BitVariable00);
  224. Assert.AreEqual(tc.BitVariable10, tc2.BitVariable10);
  225. Assert.AreEqual(tc.DIntVariable, tc2.DIntVariable);
  226. Assert.AreEqual(tc.IntVariable, tc2.IntVariable);
  227. Assert.AreEqual(tc.LRealVariable, tc2.LRealVariable);
  228. Assert.AreEqual(tc.RealVariable, tc2.RealVariable);
  229. Assert.AreEqual(tc.DWordVariable, tc2.DWordVariable);
  230. Assert.AreEqual(tc.WStringVariable, tc2.WStringVariable);
  231. Assert.AreEqual(tc.StringVariable, tc2.StringVariable);
  232. }
  233. /// <summary>
  234. /// Read/Write a struct that has the same properties of a DB with the same field in the same order
  235. /// </summary>
  236. [TestMethod]
  237. public async Task Test_Async_ReadAndWriteLongStruct()
  238. {
  239. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  240. TestLongStruct tc = new TestLongStruct
  241. {
  242. IntVariable0 = 0,
  243. IntVariable1 = 1,
  244. IntVariable10 = 10,
  245. IntVariable11 = 11,
  246. IntVariable20 = 20,
  247. IntVariable21 = 21,
  248. IntVariable30 = 30,
  249. IntVariable31 = 31,
  250. IntVariable40 = 40,
  251. IntVariable41 = 41,
  252. IntVariable50 = 50,
  253. IntVariable51 = 51,
  254. IntVariable60 = 60,
  255. IntVariable61 = 61,
  256. IntVariable70 = 70,
  257. IntVariable71 = 71,
  258. IntVariable80 = 80,
  259. IntVariable81 = 81,
  260. IntVariable90 = 90,
  261. IntVariable91 = 91,
  262. IntVariable100 = 100,
  263. IntVariable101 = 101,
  264. IntVariable110 = 200,
  265. IntVariable111 = 201
  266. };
  267. plc.WriteStruct(tc, DB2);
  268. // Values that are read from a struct are stored in a new struct, returned by the funcion ReadStruct
  269. TestLongStruct tc2 = (TestLongStruct)await plc.ReadStructAsync(typeof(TestLongStruct), DB2);
  270. Assert.AreEqual(tc.IntVariable0, tc2.IntVariable0);
  271. Assert.AreEqual(tc.IntVariable1, tc2.IntVariable1);
  272. Assert.AreEqual(tc.IntVariable10, tc2.IntVariable10);
  273. Assert.AreEqual(tc.IntVariable11, tc2.IntVariable11);
  274. Assert.AreEqual(tc.IntVariable20, tc2.IntVariable20);
  275. Assert.AreEqual(tc.IntVariable21, tc2.IntVariable21);
  276. Assert.AreEqual(tc.IntVariable30, tc2.IntVariable30);
  277. Assert.AreEqual(tc.IntVariable31, tc2.IntVariable31);
  278. Assert.AreEqual(tc.IntVariable40, tc2.IntVariable40);
  279. Assert.AreEqual(tc.IntVariable41, tc2.IntVariable41);
  280. Assert.AreEqual(tc.IntVariable50, tc2.IntVariable50);
  281. Assert.AreEqual(tc.IntVariable51, tc2.IntVariable51);
  282. Assert.AreEqual(tc.IntVariable60, tc2.IntVariable60);
  283. Assert.AreEqual(tc.IntVariable61, tc2.IntVariable61);
  284. Assert.AreEqual(tc.IntVariable70, tc2.IntVariable70);
  285. Assert.AreEqual(tc.IntVariable71, tc2.IntVariable71);
  286. Assert.AreEqual(tc.IntVariable80, tc2.IntVariable80);
  287. Assert.AreEqual(tc.IntVariable81, tc2.IntVariable81);
  288. Assert.AreEqual(tc.IntVariable90, tc2.IntVariable90);
  289. Assert.AreEqual(tc.IntVariable91, tc2.IntVariable91);
  290. Assert.AreEqual(tc.IntVariable100, tc2.IntVariable100);
  291. Assert.AreEqual(tc.IntVariable101, tc2.IntVariable101);
  292. Assert.AreEqual(tc.IntVariable110, tc2.IntVariable110);
  293. Assert.AreEqual(tc.IntVariable111, tc2.IntVariable111);
  294. }
  295. /// <summary>
  296. /// Read/Write a class that has the same properties of a DB with the same field in the same order
  297. /// </summary>
  298. [TestMethod]
  299. public async Task Test_Async_ReadAndWriteLongClass()
  300. {
  301. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  302. TestLongClass tc = new TestLongClass
  303. {
  304. IntVariable0 = 0,
  305. IntVariable1 = 1,
  306. IntVariable10 = 10,
  307. IntVariable11 = 11,
  308. IntVariable20 = 20,
  309. IntVariable21 = 21,
  310. IntVariable30 = 30,
  311. IntVariable31 = 31,
  312. IntVariable40 = 40,
  313. IntVariable41 = 41,
  314. IntVariable50 = 50,
  315. IntVariable51 = 51,
  316. IntVariable60 = 60,
  317. IntVariable61 = 61,
  318. IntVariable70 = 70,
  319. IntVariable71 = 71,
  320. IntVariable80 = 80,
  321. IntVariable81 = 81,
  322. IntVariable90 = 90,
  323. IntVariable91 = 91,
  324. IntVariable100 = 100,
  325. IntVariable101 = 101,
  326. IntVariable110 = 200,
  327. IntVariable111 = 201
  328. };
  329. await plc.WriteClassAsync(tc, DB2);
  330. // Values that are read from a struct are stored in a new struct, returned by the funcion ReadStruct
  331. TestLongClass tc2 = new TestLongClass();
  332. await plc.ReadClassAsync(tc2, DB2);
  333. Assert.AreEqual(tc.IntVariable0, tc2.IntVariable0);
  334. Assert.AreEqual(tc.IntVariable1, tc2.IntVariable1);
  335. Assert.AreEqual(tc.IntVariable10, tc2.IntVariable10);
  336. Assert.AreEqual(tc.IntVariable11, tc2.IntVariable11);
  337. Assert.AreEqual(tc.IntVariable20, tc2.IntVariable20);
  338. Assert.AreEqual(tc.IntVariable21, tc2.IntVariable21);
  339. Assert.AreEqual(tc.IntVariable30, tc2.IntVariable30);
  340. Assert.AreEqual(tc.IntVariable31, tc2.IntVariable31);
  341. Assert.AreEqual(tc.IntVariable40, tc2.IntVariable40);
  342. Assert.AreEqual(tc.IntVariable41, tc2.IntVariable41);
  343. Assert.AreEqual(tc.IntVariable50, tc2.IntVariable50);
  344. Assert.AreEqual(tc.IntVariable51, tc2.IntVariable51);
  345. Assert.AreEqual(tc.IntVariable60, tc2.IntVariable60);
  346. Assert.AreEqual(tc.IntVariable61, tc2.IntVariable61);
  347. Assert.AreEqual(tc.IntVariable70, tc2.IntVariable70);
  348. Assert.AreEqual(tc.IntVariable71, tc2.IntVariable71);
  349. Assert.AreEqual(tc.IntVariable80, tc2.IntVariable80);
  350. Assert.AreEqual(tc.IntVariable81, tc2.IntVariable81);
  351. Assert.AreEqual(tc.IntVariable90, tc2.IntVariable90);
  352. Assert.AreEqual(tc.IntVariable91, tc2.IntVariable91);
  353. Assert.AreEqual(tc.IntVariable100, tc2.IntVariable100);
  354. Assert.AreEqual(tc.IntVariable101, tc2.IntVariable101);
  355. Assert.AreEqual(tc.IntVariable110, tc2.IntVariable110);
  356. Assert.AreEqual(tc.IntVariable111, tc2.IntVariable111);
  357. }
  358. /// <summary>
  359. /// Tests that a read and a write on addresses bigger than 8192 are executed correctly
  360. /// </summary>
  361. [TestMethod]
  362. public async Task Test_Async_WriteAndReadInt16VariableAddress8192()
  363. {
  364. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  365. // To write a ushort i don't need any cast, only unboxing must be done
  366. ushort val = 8192;
  367. await plc.WriteAsync("DB2.DBW8192", val);
  368. ushort result = (ushort)await plc.ReadAsync("DB2.DBW8192");
  369. Assert.AreEqual(val, result, "A ushort goes from 0 to 64512");
  370. // To write a short i need to convert it to UShort, then i need to reconvert the readed value to get
  371. // the negative sign back
  372. // Depending if i'm writing on a DWORD or on a DEC, i will see ushort or short value in the plc
  373. short value = -8192;
  374. Assert.IsTrue(plc.IsConnected, "After connecting, IsConnected must be set to true");
  375. await plc.WriteAsync("DB2.DBW8192", value.ConvertToUshort());
  376. short result2 = ((ushort)await plc.ReadAsync("DB2.DBW8192")).ConvertToShort();
  377. Assert.AreEqual(value, result2, "A short goes from -32767 to 32766");
  378. }
  379. /// <summary>
  380. /// Tests that a read and a write on addresses bigger than 8192 are executed correctly
  381. /// </summary>
  382. [TestMethod]
  383. public async Task Test_Async_WriteAndReadInt16VariableAddress16384()
  384. {
  385. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  386. // To write a ushort i don't need any cast, only unboxing must be done
  387. ushort val = 16384;
  388. await plc.WriteAsync("DB2.DBW16384", val);
  389. ushort result = (ushort)await plc.ReadAsync("DB2.DBW16384");
  390. Assert.AreEqual(val, result, "A ushort goes from 0 to 64512");
  391. // To write a short i need to convert it to UShort, then i need to reconvert the readed value to get
  392. // the negative sign back
  393. // Depending if i'm writing on a DWORD or on a DEC, i will see ushort or short value in the plc
  394. short value = -16384;
  395. Assert.IsTrue(plc.IsConnected, "After connecting, IsConnected must be set to true");
  396. await plc.WriteAsync("DB2.DBW16384", value.ConvertToUshort());
  397. short result2 = ((ushort)await plc.ReadAsync("DB2.DBW16384")).ConvertToShort();
  398. Assert.AreEqual(value, result2, "A short goes from -32767 to 32766");
  399. }
  400. [TestMethod]
  401. public async Task Test_Async_ReadMultipleBytes()
  402. {
  403. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  404. bool val = true;
  405. await plc.WriteAsync("DB2.DBX0.5", val);
  406. bool result = (bool)await plc.ReadAsync("DB2.DBX0.5");
  407. Assert.AreEqual(val, result);
  408. ushort val1 = 16384;
  409. await plc.WriteAsync("DB2.DBW16384", val1);
  410. ushort result1 = (ushort)await plc.ReadAsync("DB2.DBW16384");
  411. Assert.AreEqual(val1, result1, "A ushort goes from 0 to 64512");
  412. bool val2 = true;
  413. await plc.WriteAsync("DB2.DBX8192.7", val2);
  414. bool result2 = (bool)await plc.ReadAsync("DB2.DBX8192.7");
  415. Assert.AreEqual(val2, result2);
  416. ushort val3 = 129;
  417. await plc.WriteAsync("DB2.DBW16", val3);
  418. ushort result3 = (ushort)await plc.ReadAsync("DB2.DBW16");
  419. Assert.AreEqual(val3, result3, "A ushort goes from 0 to 64512");
  420. byte[] val4 = new byte[] { 0x12, 0x34 };
  421. await plc.WriteAsync("DB2.DBB2048", val4[0]);
  422. await plc.WriteAsync("DB2.DBB2049", val4[1]);
  423. byte result4b0 = (byte)await plc.ReadAsync("DB2.DBB2048");
  424. byte result4b1 = (byte)await plc.ReadAsync("DB2.DBB2049");
  425. Assert.AreEqual(val4[0], result4b0);
  426. Assert.AreEqual(val4[1], result4b1);
  427. bool val6 = true;
  428. await plc.WriteAsync("DB2.DBX16384.6", val6);
  429. bool result6 = (bool)await plc.ReadAsync("DB2.DBX16384.6");
  430. Assert.AreEqual(val6, result6);
  431. var dataItems = new List<DataItem>()
  432. {
  433. new DataItem
  434. {
  435. Count = 1,
  436. DataType = DataType.DataBlock,
  437. DB = 2,
  438. StartByteAdr = 0,
  439. BitAdr = 5,
  440. VarType = VarType.Bit
  441. }
  442. ,new DataItem
  443. {
  444. Count = 1,
  445. DataType = DataType.DataBlock,
  446. DB = 2,
  447. StartByteAdr = 16384,
  448. VarType = VarType.Word
  449. },
  450. new DataItem
  451. {
  452. Count = 1,
  453. DataType = DataType.DataBlock,
  454. DB = 2,
  455. StartByteAdr = 8192,
  456. BitAdr = 7,
  457. VarType = VarType.Bit
  458. },
  459. new DataItem
  460. {
  461. Count = 1,
  462. DataType = DataType.DataBlock,
  463. DB = 2,
  464. StartByteAdr = 16,
  465. VarType = VarType.Word
  466. },
  467. // single byte
  468. new DataItem
  469. {
  470. Count = 1,
  471. DataType = DataType.DataBlock,
  472. DB = 2,
  473. StartByteAdr = 2048,
  474. VarType = VarType.Byte
  475. },
  476. // multiple bytes
  477. new DataItem
  478. {
  479. Count = 2,
  480. DataType = DataType.DataBlock,
  481. DB = 2,
  482. StartByteAdr = 2048,
  483. VarType = VarType.Byte
  484. },
  485. new DataItem
  486. {
  487. Count = 1,
  488. DataType = DataType.DataBlock,
  489. DB = 2,
  490. StartByteAdr = 16384,
  491. BitAdr = 6,
  492. VarType = VarType.Bit
  493. },
  494. };
  495. var dataItemsRes = await plc.ReadMultipleVarsAsync(dataItems);
  496. Assert.AreEqual(val, dataItemsRes[0].Value);
  497. Assert.AreEqual(val1, dataItemsRes[1].Value);
  498. Assert.AreEqual(val2, dataItemsRes[2].Value);
  499. Assert.AreEqual(val3, dataItemsRes[3].Value);
  500. Assert.AreEqual(val4[0], dataItemsRes[4].Value);
  501. Assert.AreEqual(val4[0], ((byte[])dataItemsRes[5].Value)[0]); //dataItem[5].Value should be byte[2]
  502. Assert.AreEqual(val4[1], ((byte[])dataItemsRes[5].Value)[1]);
  503. Assert.AreEqual(val6, dataItemsRes[6].Value);
  504. }
  505. /// <summary>
  506. /// Tests that a read and a write on addresses bigger than 8192 are executed correctly
  507. /// </summary>
  508. [TestMethod]
  509. public async Task Test_Async_WriteAndReadBooleanVariable()
  510. {
  511. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  512. // tests when writing true/false
  513. await plc.WriteAsync("DB1.DBX0.0", false);
  514. var boolVariable = (bool)await plc.ReadAsync("DB1.DBX0.0");
  515. Assert.IsFalse(boolVariable);
  516. await plc.WriteAsync("DB1.DBX0.0", true);
  517. boolVariable = (bool)await plc.ReadAsync("DB1.DBX0.0");
  518. Assert.IsTrue(boolVariable);
  519. // tests when writing 0/1
  520. await plc.WriteAsync("DB1.DBX0.0", 0);
  521. boolVariable = (bool)await plc.ReadAsync("DB1.DBX0.0");
  522. Assert.IsFalse(boolVariable);
  523. await plc.WriteAsync("DB1.DBX0.0", 1);
  524. boolVariable = (bool)await plc.ReadAsync("DB1.DBX0.0");
  525. Assert.IsTrue(boolVariable);
  526. await plc.WriteAsync("DB1.DBX0.7", 1);
  527. boolVariable = (bool)await plc.ReadAsync("DB1.DBX0.7");
  528. Assert.IsTrue(boolVariable);
  529. await plc.WriteAsync("DB1.DBX0.7", 0);
  530. boolVariable = (bool)await plc.ReadAsync("DB1.DBX0.7");
  531. Assert.IsFalse(boolVariable);
  532. await plc.WriteAsync("DB1.DBX658.0", 1);
  533. boolVariable = (bool)await plc.ReadAsync("DB1.DBX658.0");
  534. Assert.IsTrue(boolVariable);
  535. await plc.WriteAsync("DB1.DBX658.7", 1);
  536. boolVariable = (bool)await plc.ReadAsync("DB1.DBX658.7");
  537. Assert.IsTrue(boolVariable);
  538. await plc.WriteAsync("DB2.DBX9658.0", 1);
  539. boolVariable = (bool)await plc.ReadAsync("DB2.DBX9658.0");
  540. Assert.IsTrue(boolVariable);
  541. }
  542. [TestMethod]
  543. public async Task Test_Async_ReadClassIgnoresNonPublicSetters()
  544. {
  545. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  546. TestClassWithPrivateSetters tc = new TestClassWithPrivateSetters
  547. {
  548. BitVariable00 = true,
  549. BitVariable10 = true,
  550. DIntVariable = -100000,
  551. IntVariable = -15000,
  552. LRealVariable = -154.789,
  553. RealVariable = -154.789f,
  554. DWordVariable = 850,
  555. WStringVariable = "ÄÜÉÊéà",
  556. StringVariable = "Hallo"
  557. };
  558. await plc.WriteClassAsync(tc, DB2);
  559. TestClassWithPrivateSetters tc2 = new TestClassWithPrivateSetters();
  560. // Values that are read from a class are stored inside the class itself, that is passed by reference
  561. var res = await plc.ReadClassAsync(tc2, DB2);
  562. tc = (TestClassWithPrivateSetters)res.Item2;
  563. Assert.AreEqual(tc.BitVariable00, tc2.BitVariable00);
  564. Assert.AreEqual(tc.BitVariable10, tc2.BitVariable10);
  565. Assert.AreEqual(tc.DIntVariable, tc2.DIntVariable);
  566. Assert.AreEqual(tc.IntVariable, tc2.IntVariable);
  567. Assert.AreEqual(tc.LRealVariable, tc2.LRealVariable, 0.1);
  568. Assert.AreEqual(tc.RealVariable, tc2.RealVariable);
  569. Assert.AreEqual(tc.DWordVariable, tc2.DWordVariable);
  570. Assert.AreEqual(TestClassWithPrivateSetters.PRIVATE_SETTER_VALUE, tc2.PrivateSetterProperty);
  571. Assert.AreEqual(TestClassWithPrivateSetters.PROTECTED_SETTER_VALUE, tc2.ProtectedSetterProperty);
  572. Assert.AreEqual(TestClassWithPrivateSetters.INTERNAL_SETTER_VALUE, tc2.InternalSetterProperty);
  573. Assert.AreEqual(TestClassWithPrivateSetters.JUST_A_GETTER_VALUE, tc2.JustAGetterProperty);
  574. }
  575. [TestMethod]
  576. public async Task Test_Async_ReadBytesReturnsNullIfPlcIsNotConnected()
  577. {
  578. using (var notConnectedPlc = new Plc(CpuType.S7300, "255.255.255.255", 0, 0))
  579. {
  580. Assert.IsFalse(notConnectedPlc.IsConnected);
  581. TestClass tc = new TestClass();
  582. await Assert.ThrowsExceptionAsync<PlcException>(async () => await notConnectedPlc.ReadClassAsync(tc, DB2));
  583. }
  584. }
  585. [TestMethod]
  586. public async Task Test_Async_ReadClassWithGenericReturnsSameResultAsReadClassWithoutGeneric()
  587. {
  588. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  589. TestClass tc = new TestClass
  590. {
  591. BitVariable00 = true,
  592. BitVariable10 = true,
  593. DIntVariable = -100000,
  594. IntVariable = -15000,
  595. LRealVariable = -154.789,
  596. RealVariable = -154.789f,
  597. DWordVariable = 850,
  598. WStringVariable = "ÄÜÉÊéà",
  599. StringVariable = "Hallo"
  600. };
  601. await plc.WriteClassAsync(tc, DB2);
  602. // Values that are read from a class are stored inside the class itself, that is passed by reference
  603. TestClass tc2 = new TestClass();
  604. var res = await plc.ReadClassAsync(tc2, DB2);
  605. tc2 = (TestClass)res.Item2;
  606. TestClass tc2Generic = await plc.ReadClassAsync<TestClass>(DB2);
  607. Assert.AreEqual(tc2.BitVariable00, tc2Generic.BitVariable00);
  608. Assert.AreEqual(tc2.BitVariable10, tc2Generic.BitVariable10);
  609. Assert.AreEqual(tc2.DIntVariable, tc2Generic.DIntVariable);
  610. Assert.AreEqual(tc2.IntVariable, tc2Generic.IntVariable);
  611. Assert.AreEqual(Math.Round(tc2.LRealVariable, 3), Math.Round(tc2Generic.LRealVariable, 3));
  612. Assert.AreEqual(tc2.RealVariable, tc2Generic.RealVariable);
  613. Assert.AreEqual(tc2.DWordVariable, tc2Generic.DWordVariable);
  614. Assert.AreEqual(tc2.WStringVariable, tc2Generic.WStringVariable);
  615. Assert.AreEqual(tc2.StringVariable, tc2Generic.StringVariable);
  616. }
  617. [TestMethod]
  618. public async Task Test_Async_ReadClassWithGenericReturnsNullIfPlcIsNotConnected()
  619. {
  620. using (var notConnectedPlc = new Plc(CpuType.S7300, "255.255.255.255", 0, 0))
  621. {
  622. Assert.IsFalse(notConnectedPlc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  623. await Assert.ThrowsExceptionAsync<PlcException>(async () => await notConnectedPlc.ReadClassAsync<TestClass>(DB2));
  624. }
  625. }
  626. [TestMethod]
  627. public async Task Test_Async_ReadClassWithGenericAndClassFactoryReturnsSameResultAsReadClassWithoutGeneric()
  628. {
  629. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  630. TestClass tc = new TestClass
  631. {
  632. BitVariable00 = true,
  633. BitVariable10 = true,
  634. DIntVariable = -100000,
  635. IntVariable = -15000,
  636. LRealVariable = -154.789,
  637. RealVariable = -154.789f,
  638. DWordVariable = 850,
  639. WStringVariable = "ÄÜÉÊéà",
  640. StringVariable = "Hallo"
  641. };
  642. await plc.WriteClassAsync(tc, DB2);
  643. // Values that are read from a class are stored inside the class itself, that is passed by reference
  644. TestClass tc2Generic = await plc.ReadClassAsync<TestClass>(DB2);
  645. TestClass tc2GenericWithClassFactory = await plc.ReadClassAsync(() => new TestClass(), DB2);
  646. Assert.AreEqual(tc2Generic.BitVariable00, tc2GenericWithClassFactory.BitVariable00);
  647. Assert.AreEqual(tc2Generic.BitVariable10, tc2GenericWithClassFactory.BitVariable10);
  648. Assert.AreEqual(tc2Generic.DIntVariable, tc2GenericWithClassFactory.DIntVariable);
  649. Assert.AreEqual(Math.Round(tc2Generic.LRealVariable, 3), Math.Round(tc2GenericWithClassFactory.LRealVariable, 3));
  650. Assert.AreEqual(tc2Generic.RealVariable, tc2GenericWithClassFactory.RealVariable);
  651. Assert.AreEqual(tc2Generic.DWordVariable, tc2GenericWithClassFactory.DWordVariable);
  652. Assert.AreEqual(tc2Generic.WStringVariable, tc2GenericWithClassFactory.WStringVariable);
  653. Assert.AreEqual(tc2Generic.StringVariable, tc2GenericWithClassFactory.StringVariable);
  654. }
  655. [TestMethod]
  656. public async Task Test_Async_ReadClassWithGenericAndClassFactoryThrowsExceptionPlcIsNotConnected()
  657. {
  658. using (var notConnectedPlc = new Plc(CpuType.S7300, "255.255.255.255", 0, 0))
  659. {
  660. Assert.IsFalse(notConnectedPlc.IsConnected);
  661. await Assert.ThrowsExceptionAsync<PlcException>(async () => await notConnectedPlc.ReadClassAsync(() => new TestClass(), DB2));
  662. }
  663. }
  664. [TestMethod]
  665. public async Task Test_Async_ReadClassWithNestedClassAfterBit()
  666. {
  667. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  668. Assert.AreEqual(6, Types.Class.GetClassSize(new TestClassWithNestedClass()));
  669. TestClassWithNestedClass tc = new TestClassWithNestedClass();
  670. tc.BitVariable00 = true;
  671. tc.BitVariable01.BitVariable00 = true;
  672. tc.ByteVariable02.ByteVariable00 = 128;
  673. tc.BitVariable03 = true;
  674. tc.ShortVariable04.ShortVarialbe00 = -15000;
  675. TestClassWithNestedClass tc2 = await plc.ReadClassAsync<TestClassWithNestedClass>(DB4);
  676. Assert.AreEqual(tc.BitVariable00, tc2.BitVariable00);
  677. Assert.AreEqual(tc.BitVariable01.BitVariable00, tc2.BitVariable01.BitVariable00);
  678. Assert.AreEqual(tc.ByteVariable02.ByteVariable00, tc2.ByteVariable02.ByteVariable00);
  679. Assert.AreEqual(tc.BitVariable03, tc2.BitVariable03);
  680. Assert.AreEqual(tc.ShortVariable04.ShortVarialbe00, tc2.ShortVariable04.ShortVarialbe00);
  681. }
  682. [TestMethod]
  683. public async Task Test_Async_ReadStructThrowsExceptionPlcIsNotConnected()
  684. {
  685. using (var notConnectedPlc = new Plc(CpuType.S7300, "255.255.255.255", 0, 0))
  686. {
  687. Assert.IsFalse(notConnectedPlc.IsConnected);
  688. await Assert.ThrowsExceptionAsync<PlcException>(async () => await notConnectedPlc.ReadStructAsync(typeof(TestStruct), DB2));
  689. }
  690. }
  691. [TestMethod]
  692. public async Task Test_Async_ReadStructWithGenericReturnsSameResultAsReadStructWithoutGeneric()
  693. {
  694. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  695. TestStruct ts = new TestStruct
  696. {
  697. BitVariable00 = true,
  698. BitVariable10 = true,
  699. DIntVariable = -100000,
  700. IntVariable = -15000,
  701. LRealVariable = -154.789,
  702. RealVariable = -154.789f,
  703. DWordVariable = 850,
  704. WStringVariable = "ÄÜÉÊéà",
  705. StringVariable = "Hallo"
  706. };
  707. plc.WriteStruct(ts, DB2);
  708. // Values that are read from a struct are stored in a new struct, returned by the funcion ReadStruct
  709. TestStruct ts2 = (TestStruct)await plc.ReadStructAsync(typeof(TestStruct), DB2);
  710. var test = await plc.ReadStructAsync<TestStruct>(DB2);
  711. TestStruct ts2Generic = test.Value;
  712. Assert.AreEqual(ts2.BitVariable00, ts2Generic.BitVariable00);
  713. Assert.AreEqual(ts2.BitVariable10, ts2Generic.BitVariable10);
  714. Assert.AreEqual(ts2.DIntVariable, ts2Generic.DIntVariable);
  715. Assert.AreEqual(ts2.IntVariable, ts2Generic.IntVariable);
  716. Assert.AreEqual(ts2.LRealVariable, ts2Generic.LRealVariable);
  717. Assert.AreEqual(ts2.RealVariable, ts2Generic.RealVariable);
  718. Assert.AreEqual(ts2.DWordVariable, ts2Generic.DWordVariable);
  719. Assert.AreEqual(ts2.WStringVariable, ts2Generic.WStringVariable);
  720. Assert.AreEqual(ts2.StringVariable, ts2Generic.StringVariable);
  721. }
  722. [TestMethod]
  723. public async Task Test_Async_ReadStructWithGenericThrowsExceptionIfPlcIsNotConnected()
  724. {
  725. using (var notConnectedPlc = new Plc(CpuType.S7300, "255.255.255.255", 0, 0))
  726. {
  727. Assert.IsFalse(notConnectedPlc.IsConnected);
  728. await Assert.ThrowsExceptionAsync<PlcException>(async () => await notConnectedPlc.ReadStructAsync<TestStruct>(DB2));
  729. }
  730. }
  731. /// <summary>
  732. /// Tests that the method ReadClass returns the number of bytes read from the plc
  733. /// </summary>
  734. [TestMethod]
  735. public async Task Test_Async_ReadClassReturnsNumberOfReadBytesFromThePlc()
  736. {
  737. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  738. TestClass tc = new TestClass
  739. {
  740. BitVariable00 = true,
  741. BitVariable10 = true,
  742. DIntVariable = -100000,
  743. IntVariable = -15000,
  744. LRealVariable = -154.789,
  745. RealVariable = -154.789f,
  746. DWordVariable = 850,
  747. WStringVariable = "ÄÜÉÊéà",
  748. StringVariable = "Hallo"
  749. };
  750. plc.WriteClass(tc, DB2);
  751. int expectedReadBytes = (int)Types.Class.GetClassSize(tc);
  752. TestClass tc2 = new TestClass();
  753. // Values that are read from a class are stored inside the class itself, that is passed by reference
  754. var res = await plc.ReadClassAsync(tc2, DB2);
  755. int actualReadBytes = res.Item1;
  756. Assert.AreEqual(expectedReadBytes, actualReadBytes);
  757. }
  758. [TestMethod]
  759. public async Task Test_Async_ReadClassWithArray()
  760. {
  761. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  762. TestClassWithArrays tc = new TestClassWithArrays
  763. {
  764. Bool = true
  765. };
  766. tc.BoolValues[1] = true;
  767. tc.Int = int.MinValue;
  768. tc.Ints[0] = int.MinValue;
  769. tc.Ints[1] = int.MaxValue;
  770. tc.Short = short.MinValue;
  771. tc.Shorts[0] = short.MinValue;
  772. tc.Shorts[1] = short.MaxValue;
  773. tc.Double = float.MinValue;
  774. tc.Doubles[0] = float.MinValue + 1;
  775. tc.Doubles[1] = float.MaxValue;
  776. tc.UShort = ushort.MinValue + 1;
  777. tc.UShorts[0] = ushort.MinValue + 1;
  778. tc.UShorts[1] = ushort.MaxValue;
  779. plc.WriteClass(tc, DB2);
  780. TestClassWithArrays tc2 = await plc.ReadClassAsync<TestClassWithArrays>(DB2);
  781. Assert.AreEqual(tc.Bool, tc2.Bool);
  782. Assert.AreEqual(tc.BoolValues[0], tc2.BoolValues[0]);
  783. Assert.AreEqual(tc.BoolValues[1], tc2.BoolValues[1]);
  784. Assert.AreEqual(tc.Int, tc2.Int);
  785. Assert.AreEqual(tc.Ints[0], tc2.Ints[0]);
  786. Assert.AreEqual(tc.Ints[1], tc.Ints[1]);
  787. Assert.AreEqual(tc.Short, tc2.Short);
  788. Assert.AreEqual(tc.Shorts[0], tc2.Shorts[0]);
  789. Assert.AreEqual(tc.Shorts[1], tc2.Shorts[1]);
  790. Assert.AreEqual(tc.Double, tc2.Double);
  791. Assert.AreEqual(tc.Doubles[0], tc2.Doubles[0]);
  792. Assert.AreEqual(tc.Doubles[1], tc2.Doubles[1]);
  793. Assert.AreEqual(tc.UShort, tc2.UShort);
  794. Assert.AreEqual(tc.UShorts[0], tc2.UShorts[0]);
  795. Assert.AreEqual(tc.UShorts[1], tc2.UShorts[1]);
  796. }
  797. [TestMethod]
  798. public async Task Test_Async_ReadClassWithArrayAndCustomType()
  799. {
  800. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  801. TestClassWithCustomType tc = new TestClassWithCustomType
  802. {
  803. Int = int.MinValue,
  804. CustomType = new CustomType()
  805. };
  806. tc.CustomType.Bools[1] = true;
  807. tc.CustomTypes[0] = new CustomType();
  808. tc.CustomTypes[1] = new CustomType();
  809. tc.CustomTypes[0].Bools[0] = true;
  810. tc.CustomTypes[1].Bools[1] = true;
  811. plc.WriteClass(tc, DB2);
  812. TestClassWithCustomType tc2 = await plc.ReadClassAsync<TestClassWithCustomType>(DB2);
  813. Assert.AreEqual(tc.Int, tc2.Int);
  814. Assert.AreEqual(tc.CustomType.Bools[0], tc2.CustomType.Bools[0]);
  815. Assert.AreEqual(tc.CustomType.Bools[1], tc2.CustomType.Bools[1]);
  816. Assert.AreEqual(tc.CustomTypes[0].Bools[0], tc2.CustomTypes[0].Bools[0]);
  817. Assert.AreEqual(tc.CustomTypes[0].Bools[1], tc2.CustomTypes[0].Bools[1]);
  818. Assert.AreEqual(tc.CustomTypes[1].Bools[0], tc2.CustomTypes[1].Bools[0]);
  819. Assert.AreEqual(tc.CustomTypes[1].Bools[1], tc2.CustomTypes[1].Bools[1]);
  820. }
  821. [TestMethod]
  822. public async Task Test_Async_ReadWriteSingle()
  823. {
  824. float test_value = 55.6632f;
  825. await plc.WriteAsync("DB1.DBD0", test_value);
  826. var helper = await plc.ReadAsync("DB1.DBD0");
  827. float test_value2 = Conversion.ConvertToFloat((uint)helper);
  828. Assert.AreEqual(test_value, test_value2, "Compare Write/Read"); //No delta, datatype matches
  829. }
  830. [TestMethod]
  831. public async Task Test_Async_ReadWriteBytesMany()
  832. {
  833. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  834. var count = 2000;
  835. var dataItems = new List<byte>();
  836. for (int i = 0; i < count; i++)
  837. {
  838. dataItems.Add((byte)(i % 256));
  839. }
  840. await plc.WriteBytesAsync(DataType.DataBlock, 2, 0, dataItems.ToArray());
  841. var res = await plc.ReadBytesAsync(DataType.DataBlock, 2, 0, count);
  842. for (int x = 0; x < count; x++)
  843. {
  844. Assert.AreEqual(x % 256, res[x], string.Format("Bit {0} failed", x));
  845. }
  846. }
  847. #if NET5_0_OR_GREATER
  848. [TestMethod]
  849. public async Task Test_Async_ReadWriteBytesManyWithMemory()
  850. {
  851. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  852. using var data = MemoryPool<byte>.Shared.Rent(2000);
  853. for (int i = 0; i < data.Memory.Length; i++)
  854. data.Memory.Span[i] = (byte)(i % 256);
  855. await plc.WriteBytesAsync(DataType.DataBlock, 2, 0, data.Memory);
  856. using var readData = MemoryPool<byte>.Shared.Rent(data.Memory.Length);
  857. await plc.ReadBytesAsync(readData.Memory.Slice(0, data.Memory.Length), DataType.DataBlock, 2, 0);
  858. for (int x = 0; x < data.Memory.Length; x++)
  859. {
  860. Assert.AreEqual(x % 256, readData.Memory.Span[x], string.Format("Bit {0} failed", x));
  861. }
  862. }
  863. #endif
  864. /// <summary>
  865. /// Write a large amount of data and test cancellation
  866. /// </summary>
  867. [TestMethod]
  868. public async Task Test_Async_WriteLargeByteArrayWithCancellation()
  869. {
  870. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  871. var cancellationSource = new CancellationTokenSource();
  872. var cancellationToken = cancellationSource.Token;
  873. var randomEngine = new Random();
  874. var data = new byte[8192];
  875. var db = 2;
  876. randomEngine.NextBytes(data);
  877. cancellationSource.CancelAfter(System.TimeSpan.FromMilliseconds(5));
  878. try
  879. {
  880. await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data, cancellationToken);
  881. }
  882. catch(OperationCanceledException)
  883. {
  884. // everything is good, that is the exception we expect
  885. Console.WriteLine("Operation was cancelled as expected.");
  886. return;
  887. }
  888. catch(Exception e)
  889. {
  890. Assert.Fail($"Wrong exception type received. Expected {typeof(OperationCanceledException)}, received {e.GetType()}.");
  891. }
  892. // Depending on how tests run, this can also just succeed without getting cancelled at all. Do nothing in this case.
  893. Console.WriteLine("Task was not cancelled as expected.");
  894. }
  895. #if NET5_0_OR_GREATER
  896. /// <summary>
  897. /// Write a large amount of data and test cancellation
  898. /// </summary>
  899. [TestMethod]
  900. public async Task Test_Async_WriteLargeByteArrayWithCancellationWithMemory()
  901. {
  902. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  903. var cancellationSource = new CancellationTokenSource();
  904. var cancellationToken = cancellationSource.Token;
  905. using var dataOwner = MemoryPool<byte>.Shared.Rent(8192);
  906. var data = dataOwner.Memory.Slice(0, 8192);
  907. var randomEngine = new Random();
  908. var db = 2;
  909. randomEngine.NextBytes(data.Span);
  910. cancellationSource.CancelAfter(System.TimeSpan.FromMilliseconds(5));
  911. try
  912. {
  913. await plc.WriteBytesAsync(DataType.DataBlock, db, 0, data, cancellationToken);
  914. }
  915. catch (OperationCanceledException)
  916. {
  917. // everything is good, that is the exception we expect
  918. Console.WriteLine("Operation was cancelled as expected.");
  919. return;
  920. }
  921. catch (Exception e)
  922. {
  923. Assert.Fail($"Wrong exception type received. Expected {typeof(OperationCanceledException)}, received {e.GetType()}.");
  924. }
  925. // Depending on how tests run, this can also just succeed without getting cancelled at all. Do nothing in this case.
  926. Console.WriteLine("Task was not cancelled as expected.");
  927. }
  928. #endif
  929. /// <summary>
  930. /// Write a large amount of data and test cancellation
  931. /// </summary>
  932. [TestMethod]
  933. public async Task Test_Async_ParseDataIntoDataItemsAlignment()
  934. {
  935. Assert.IsTrue(plc.IsConnected, "Before executing this test, the plc must be connected. Check constructor.");
  936. var db = 2;
  937. // First write a sensible S7 string capacity
  938. await plc.WriteBytesAsync(DataType.DataBlock, db, 0, new byte[] {5, 0});
  939. // Read two data items, with the first having odd number of bytes (7),
  940. // and the second has to be aligned on a even address
  941. var dataItems = new List<DataItem>
  942. {
  943. new DataItem
  944. {
  945. DataType = DataType.DataBlock,
  946. DB = db,
  947. VarType = VarType.S7String,
  948. Count = 5
  949. },
  950. new DataItem
  951. {
  952. DataType = DataType.DataBlock,
  953. DB = db,
  954. VarType = VarType.Word,
  955. }
  956. };
  957. await plc.ReadMultipleVarsAsync(dataItems, CancellationToken.None);
  958. }
  959. #endregion
  960. }
  961. }