public void TestMulti() { var operations = new List <ReadOperationParameter> { new ReadOperationParameter { Area = PlcArea.DB, Offset = TestByteOffset, Type = typeof(byte), Args = new int[] { 1, TestDbNr } }, new ReadOperationParameter { Area = PlcArea.DB, Offset = TestBitOffset, Type = typeof(bool), Args = new int[] { 1, TestDbNr } } }; var writeOperations = new List <WriteOperationParameter> { new WriteOperationParameter { Area = PlcArea.DB, Offset = TestByteOffset, Type = typeof(byte), Args = new int[] { 1, TestDbNr }, Data = (byte)0x05 }, new WriteOperationParameter { Area = PlcArea.DB, Offset = TestBitOffset, Type = typeof(bool), Args = new int[] { 1, TestDbNr }, Data = true } }; var client = new Dacs7Client(); client.Connect(ConnectionString); client.WriteAny(writeOperations); var result = client.ReadAnyRaw(operations); client.Disconnect(); Assert.False(client.IsConnected); }
/// <summary> /// Read the meta data of a block from the PLC. /// </summary> /// <param name="blockType">Specify the block type to read. e.g. DB <see cref="PlcBlockType"/></param> /// <param name="blocknumber">Specify the Number of the block</param> /// <returns><see cref="IPlcBlockInfo"/> where you have access tho the detailed meta data of the block.</returns> public static async Task <IPlcBlockInfo> ReadBlockInfoAsync(this Dacs7Client client, PlcBlockType type, int blocknumber) { var result = await client.ProtocolHandler.ReadBlockInfoAsync(type, blocknumber).ConfigureAwait(false); if (result != null) { return(new PlcBlockInfo { ADDLength = result.ADDLength, Author = result.Author?.Trim('\0'), BlockFlags = result.BlockFlags, BlockLanguage = result.BlockLanguage, BlockNumber = result.BlockNumber, BlockSecurity = result.BlockSecurity, Checksum = result.Checksum, CodeSize = result.CodeSize, Family = result.Family?.Trim('\0'), LastCodeChange = result.LastCodeChange, LastInterfaceChange = result.LastInterfaceChange, LengthLoadMemory = result.LengthLoadMemory, LocalDataSize = result.LocalDataSize, Name = result.Name?.Trim('\0'), SSBLength = result.SSBLength, SubBlockType = result.SubBlockType, VersionHeaderMajor = result.VersionHeaderMajor, VersionHeaderMinor = result.VersionHeaderMinor }); } return(null); }
public void TestaBunchOfMultiReads() { var db = 10; var operations = new List <ReadOperationParameter> { new ReadOperationParameter { Area = PlcArea.DB, Offset = 0, Type = typeof(byte), Args = new int[] { 1, db } }, new ReadOperationParameter { Area = PlcArea.DB, Offset = 1, Type = typeof(bool), Args = new int[] { 1, db } }, }; for (int i = 0; i < 100; i++) { operations.Add(new ReadOperationParameter { Area = PlcArea.DB, Offset = 1 + i, Type = typeof(bool), Args = new int[] { 1, db } }); } var client = new Dacs7Client(); client.Connect(ConnectionString); var result = client.ReadAnyRaw(operations); Assert.Equal(operations.Count(), result.Count()); operations.RemoveAt(0); result = client.ReadAnyRaw(operations); Assert.Equal(operations.Count(), result.Count()); client.Disconnect(); Assert.False(client.IsConnected); }
//private static async Task<int> Watch(WatchOptions watchOptions) //{ // var client = new Dacs7Client(_factory); // try // { // await client.ConnectAsync(watchOptions.ConnectionString); // client.Subscribe(1000, (Subscription subscription, DataChangeNotification notification, IList<string> stringTable) => // { // foreach (var item in notification.MonitoredItems) // { // var clientItem = subscription.FindItemByClientHandle(item.ClientHandle); // _logger.LogInformation($"DataChanged: {clientItem.DisplayName}={item.Value}"); // } // }, watchOptions.Tags.Select(x => MonitorItem.Create(x, 1))); // Console.WriteLine("Press any key to stop!"); // Console.ReadKey(); // } // catch (Exception ex) // { // _logger.LogError($"An error occured in Watch: {ex.Message}"); // return 1; // } // finally // { // await client.DisconnectAsync(); // } // return 0; //} //private static async Task<int> WatchAlarms(WatchAlarmsOptions watchOptions) //{ // var client = new Dacs7Client(_factory); // try // { // await client.ConnectAsync(watchOptions.ConnectionString); // var filter = new EventFilter // { // SelectClauses = Events.DefaultEventAttributes // }; // filter.CreateDefaultFilter(1, 1000, null); // await client.Subscribe(100, (Subscription subscription, EventNotificationList notification, IList<string> stringTable) => // { // foreach (var item in notification.Events) // { // _logger.LogInformation($"Event: {item.EventFields.Aggregate((x, y) => $"{x.ToString()};{y.ToString()}") }"); // } // }, new[] { MonitorItem.Create(Objects.Server, 100, filter, Attributes.EventNotifier) }) // .Refresh(); // Console.WriteLine("Press any key to stop!"); // Console.ReadKey(); // } // catch (Exception ex) // { // _logger.LogError($"An error occured in Watch: {ex.Message}"); // return 1; // } // finally // { // await client.DisconnectAsync(); // } // return 0; //} private static async Task <int> Write(WriteOptions writeOptions) { var client = new Dacs7Client(writeOptions.Address); try { await client.ConnectAsync(); var write = writeOptions.Tags.Select(x => { var s = x.Split('='); return(KeyValuePair.Create <string, object>(s[0], s[1])); } ).ToList(); await client.WriteAsync(write); foreach (var item in write) { _logger?.LogInformation($"Write: {item.Key}={item.Value}"); } } catch (Exception ex) { _logger?.LogError($"An error occured in Write: {ex.Message}"); return(1); } finally { await client.DisconnectAsync(); } return(0); }
public async Task ReadMultibleData() { var client = new Dacs7Client(Address); try { await client.ConnectAsync(); var results = (await client.ReadAsync(ReadItemSpecification.Create <byte[]>("DB1114", 0, 1000), ReadItemSpecification.Create <byte[]>("DB1114", 2200, 100), ReadItemSpecification.Create <byte[]>("DB1114", 1000, 1000), ReadItemSpecification.Create <byte[]>("DB1114", 200, 100))).ToArray(); Assert.Equal(4, results.Count()); Assert.Equal(1000, results[0].Data.Length); Assert.Equal(100, results[1].Data.Length); Assert.Equal(1000, results[2].Data.Length); Assert.Equal(100, results[3].Data.Length); } finally { await client.DisconnectAsync(); } }
/// <summary> /// Reads data from the plc. /// </summary> /// <param name="values">a list of <see cref="ReadItem"/></param> /// <returns>returns a enumerable with the read values</returns> public static async Task <IEnumerable <DataValue> > ReadAsync(this Dacs7Client client, IEnumerable <ReadItem> values) { var readItems = values as IList <ReadItem> ?? new List <ReadItem>(values); var result = await client.ProtocolHandler.ReadAsync(readItems).ConfigureAwait(false); return(new List <DataValue>(result.Select((entry) => new DataValue(entry.Key, entry.Value)))); }
public void PerfTest() { var client = new Dacs7Client(); client.Connect(ConnectionString); var offset = 0; var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 100; i++) { var reads = new List <ReadOperationParameter> { ReadOperationParameter.CreateForBit(250, offset, 0), ReadOperationParameter.CreateForBit(250, offset, 1), ReadOperationParameter.CreateForBit(250, offset, 2), ReadOperationParameter.CreateForBit(250, offset, 3), ReadOperationParameter.CreateForBit(250, offset, 4) }; var result = client.ReadAny(reads); if (!(bool)result.FirstOrDefault()) { Console.WriteLine($"Bit 0 is false!"); } Console.WriteLine($"{i}"); } sw.Stop(); client.Disconnect(); }
public async Task ServerDisconnectAfterSucessfullyConnectedAndWaitingForAutoReconnectTest(int sleepTime) { // simaulate plc disconnect after sleeptime _ = Task.Run(() => RunPlcSimu(1994, sleepTime, PlcShutdonMode.StopAfterPlcSetupWasReceivedAndResponded)); var client = new Dacs7Client("127.0.0.1:1994", PlcConnectionType.Basic, 500, null, 500) { PduSize = 960 }; await client.ConnectAsync(); Assert.True(client.IsConnected, "Not Connected!"); await Task.Delay(sleepTime * 2); Assert.False(client.IsConnected, "Not Disconnected!"); _ = Task.Run(() => RunPlcSimu(1994, 2000, PlcShutdonMode.StopAfterPlcSetupWasReceivedAndResponded)); await Task.Delay(500); // wait for autoReconnect Assert.True(client.IsConnected, "Not Reconnected!"); await client.DisconnectAsync(); Assert.False(client.IsConnected, "Not Disconnected!"); }
public void ConnectionStringTest() { var client = new Dacs7Client(); const string connectionString = "Data Source = " + Ip + ":102,0,2"; client.Connect(connectionString); Assert.True(client.IsConnected); }
public void ConnectAsyncTest() { var client = new Dacs7Client(); client.ConnectAsync(ConnectionString).Wait(); Assert.True(client.IsConnected); client.DisconnectAsync().Wait(); Assert.False(client.IsConnected); }
private static IEnumerable <WriteItem> CreateWriteNodeIdCollection(this Dacs7Client client, IEnumerable <KeyValuePair <string, object> > values) { return(new List <WriteItem>(values.Select(item => { var result = client.RegisteredOrGiven(item.Key).Clone(); result.Data = result.ConvertDataToMemory(item.Value); return WriteItem.NormalizeAndValidate(result); }))); }
public async Task ServerDisconnectAftePlcSetupReceivedTest(int sleepTime) { _ = Task.Run(() => RunPlcSimu(1996, sleepTime, PlcShutdonMode.StopAfterPlcSetupReceived)); var client = new Dacs7Client("127.0.0.1:1996", PlcConnectionType.Basic, 500) { PduSize = 960 }; await Assert.ThrowsAsync <Dacs7NotConnectedException>(async() => await client.ConnectAsync()); }
public void TestGeneric() { var client = new Dacs7Client(); client.Connect(ConnectionString); for (int i = 0; i < 8; i++) { var offset = TestBitOffset + i; //Set to false and read client.WriteAny <bool>(TestDbNr, offset, false); var boolValue1 = client.ReadAny <bool>(TestDbNr, offset); //Set to true and read client.WriteAny(TestDbNr, offset, true); var boolValue2 = client.ReadAny <bool>(TestDbNr, offset); Assert.NotEqual(boolValue1, boolValue2); client.WriteAny <int>(TestDbNr, TestByteOffset, 512); var intValue1 = client.ReadAny <int>(TestDbNr, TestByteOffset); client.WriteAny <int>(TestDbNr, TestByteOffset, i); var intValue2 = client.ReadAny <int>(TestDbNr, TestByteOffset); Assert.NotEqual(intValue1, intValue2); Assert.Equal(512, intValue1); Assert.Equal(i, intValue2); client.WriteAny(TestDbNr, TestByteOffset, "TEST", 4); var strValue1 = client.ReadAny <string>(TestDbNr, TestByteOffset, 4)?.FirstOrDefault(); var writeVal = i.ToString().PadRight(4, 'X'); client.WriteAny(TestDbNr, TestByteOffset, writeVal, 4); var strValue2 = client.ReadAny <string>(TestDbNr, TestByteOffset, 4)?.FirstOrDefault(); Assert.NotEqual(strValue1, strValue2); Assert.Equal("TEST", strValue1); Assert.Equal(writeVal, strValue2); var firstWriteVal = "TEST".ToCharArray(); client.WriteAny(TestDbNr, TestByteOffset, firstWriteVal, 4); var charValue1 = client.ReadAny <char>(TestDbNr, TestByteOffset, 4); var secondWriteVal = i.ToString().PadRight(4, 'X').ToCharArray(); client.WriteAny(TestDbNr, TestByteOffset, secondWriteVal, 4); var charValue2 = client.ReadAny <char>(TestDbNr, TestByteOffset, 4); Assert.False(charValue1.SequenceEqual(charValue2)); Assert.True(firstWriteVal.SequenceEqual(charValue1)); Assert.True(secondWriteVal.SequenceEqual(charValue2)); } client.Disconnect(); }
/// <summary> /// Reads the counts of all blocks available in the plc /// </summary> /// <param name="client"></param> /// <returns></returns> public static async Task <IPlcBlocksCount> ReadBlocksCountAsync(this Dacs7Client client) { var result = await client.ProtocolHandler.ReadBocksCountInfoAsync().ConfigureAwait(false); if (result != null) { return(result.Counts); } return(null); }
private static int CalculateSizeForGenericWriteOperation <T>(PlcArea area, T value, int length = -1) { var size = Dacs7Client.CalculateSizeForGenericWriteOperation(area, value, length, out Type elementType); if (typeof(T) == typeof(string)) { size -= 2; } return(size); }
public async Task Setup() { _client = new Dacs7Client(Address, PlcConnectionType.Pg, 5000) { MaxAmQCalled = 5, MaxAmQCalling = 5 }; await _client.ConnectAsync(); _item = ReadItem.CreateFromTag(Tag); }
public void GetBlocksOfTypeTest() { var client = new Dacs7Client(); client.Connect(ConnectionString); Assert.True(client.IsConnected); var bc = client.GetBlocksOfType(PlcBlockType.Ob); client.Disconnect(); Assert.False(client.IsConnected); }
public void GetWriteItemMaxLengthForPdu240Test() { ushort pdu = 240; var max = pdu - 28; var client = new Dacs7Client("120.0.0.1") { PduSize = pdu }; Assert.Equal(pdu, client.PduSize); Assert.Equal(max, client.GetWriteItemMaxLength()); }
public void GetReadItemMaxLengthForPdu1920Test() { ushort pdu = 1920; var max = pdu - 18; var client = new Dacs7Client("120.0.0.1") { PduSize = pdu }; Assert.Equal(pdu, client.PduSize); Assert.Equal(max, client.GetReadItemMaxLength()); }
public void ReadPendingAlarmsAsyncTest() { var client = new Dacs7Client(); client.ConnectAsync(ConnectionString).Wait(); Assert.True(client.IsConnected); var alarms = client.ReadPendingAlarmsAsync().Result; client.DisconnectAsync().Wait(); Assert.False(client.IsConnected); }
public void ReadWriteAnyAsyncTest() { var client = new Dacs7Client(); client.ConnectAsync(ConnectionString).Wait(); Assert.True(client.IsConnected); client.WriteAnyAsync(PlcArea.DB, TestByteOffset, (byte)0x05, new int[] { 1, TestDbNr }).Wait();; var bytes = client.ReadAnyAsync(PlcArea.DB, TestByteOffset, typeof(byte), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(bytes); Assert.Equal((byte)0x05, bytes[0]); client.WriteAnyAsync(PlcArea.DB, TestByteOffset, (byte)0x00, new int[] { 1, TestDbNr }).Wait(); bytes = client.ReadAnyAsync(PlcArea.DB, TestByteOffset, typeof(byte), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(bytes); Assert.Equal((byte)0x00, bytes[0]); client.WriteAnyAsync(PlcArea.DB, TestByteOffset, (byte)0x05, new int[] { 1, TestDbNr }).Wait(); bytes = client.ReadAnyAsync(PlcArea.DB, TestByteOffset, typeof(byte), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(bytes); Assert.Equal((byte)0x05, bytes[0]); client.WriteAnyAsync(PlcArea.DB, TestByteOffset, (byte)0x00, new int[] { 1, TestDbNr }).Wait(); bytes = client.ReadAnyAsync(PlcArea.DB, TestByteOffset, typeof(byte), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(bytes); Assert.Equal((byte)0x00, bytes[0]); client.WriteAnyAsync(PlcArea.DB, TestBitOffset, true, new int[] { 1, TestDbNr }).Wait(); var state = client.ReadAnyAsync(PlcArea.DB, TestBitOffset, typeof(bool), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(state); Assert.Equal((byte)0x01, state[0]); client.WriteAnyAsync(PlcArea.DB, TestBitOffset, false, new int[] { 1, TestDbNr }).Wait(); state = client.ReadAnyAsync(PlcArea.DB, TestBitOffset, typeof(bool), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(state); Assert.Equal((byte)0x00, state[0]); client.WriteAnyAsync(PlcArea.DB, TestBitOffset, true, new int[] { 1, TestDbNr }).Wait(); state = client.ReadAnyAsync(PlcArea.DB, TestBitOffset, typeof(bool), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(state); Assert.Equal((byte)0x01, state[0]); client.WriteAnyAsync(PlcArea.DB, TestBitOffset, false, new int[] { 1, TestDbNr }).Wait(); state = client.ReadAnyAsync(PlcArea.DB, TestBitOffset, typeof(bool), new int[] { 1, TestDbNr }).Result as byte[]; Assert.NotNull(state); Assert.Equal((byte)0x00, state[0]); client.DisconnectAsync().Wait(); Assert.False(client.IsConnected); }
public void GetPlcTimeTest() { var client = new Dacs7Client(); client.Connect(ConnectionString); Assert.True(client.IsConnected); var bc = client.GetPlcTime(); client.Disconnect(); Assert.False(client.IsConnected); }
private static async Task <int> Read(ReadOptions readOptions, ILoggerFactory loggerFactory) { var client = new Dacs7Client(readOptions.Address, PlcConnectionType.Pg, 5000, loggerFactory) { MaxAmQCalled = (ushort)readOptions.MaxJobs, MaxAmQCalling = (ushort)readOptions.MaxJobs }; var logger = loggerFactory?.CreateLogger("Dacs7Cli.Read"); try { await client.ConnectAsync(); if (readOptions.RegisterItems) { await client.RegisterAsync(readOptions.Tags); } var swTotal = new Stopwatch(); var tasks = new List <Task <IEnumerable <DataValue> > >(); for (var i = 0; i < readOptions.Loops; i++) { try { tasks.Add(client.ReadAsync(readOptions.Tags)); } catch (Exception ex) { logger?.LogError($"Exception in loop {ex.Message}."); } } await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); } catch (Exception ex) { logger?.LogError($"An error occurred in Read: {ex.Message} - {ex.InnerException?.Message}"); return(1); } finally { if (readOptions.RegisterItems) { await client.UnregisterAsync(readOptions.Tags); } await client.DisconnectAsync(); } return(0); }
public void ReadBlockInfoNoExistingTest() { var client = new Dacs7Client(); client.Connect(ConnectionString); Assert.True(client.IsConnected); var blkInfo = client.ReadBlockInfo(PlcBlockType.Db, 9999); Assert.Equal(9999, blkInfo.BlockNumber); client.Disconnect(); Assert.False(client.IsConnected); }
public void ReadBlockInfoFromSdbTest() { var client = new Dacs7Client(); client.Connect(ConnectionString); Assert.True(client.IsConnected); var blkInfo = client.ReadBlockInfo(PlcBlockType.Sdb, 0); Assert.Equal(0, blkInfo.BlockNumber); client.Disconnect(); Assert.False(client.IsConnected); }
public void ReadBlockInfo2Test() { var client = new Dacs7Client(); client.Connect(ConnectionString); Assert.True(client.IsConnected); var blkInfo = client.UploadPlcBlock(PlcBlockType.Db, TestDbNr); blkInfo = client.UploadPlcBlock(PlcBlockType.Db, 250); client.Disconnect(); Assert.False(client.IsConnected); }
public void ReadNotExistingItem() { var client = new Dacs7Client(); //client.OnLogEntry += Console.WriteLine; client.Connect(ConnectionString); Assert.True(client.IsConnected); const int length = ushort.MaxValue; Assert.Throws <Dacs7ContentException>(() => client.ReadAny(PlcArea.DB, 0, typeof(byte), new[] { length, LongDbNumer })); client.Disconnect(); Assert.False(client.IsConnected); }
public void GetBlocksOfTypeTest2() { var client = new Dacs7Client(); client.Connect(ConnectionString); Assert.True(client.IsConnected); var bc = client.GetBlocksOfType(PlcBlockType.Sdb); foreach (var c in bc) { Console.WriteLine(c.Number); } client.Disconnect(); Assert.False(client.IsConnected); }
public void ReadBlockInfoAsyncTest() { var client = new Dacs7Client(); client.ConnectAsync(ConnectionString).Wait(); Assert.True(client.IsConnected); client.ConnectAsync(ConnectionString).Wait(); var blkInfo = client.ReadBlockInfoAsync(PlcBlockType.Db, TestDbNr).Result; Assert.Equal(TestDbNr, blkInfo.BlockNumber); client.DisconnectAsync().Wait(); Assert.False(client.IsConnected); }
private static async Task <int> ReadAlarms(ReadAlarmsOptions readOptions, ILoggerFactory loggerFactory) { var client = new Dacs7Client(readOptions.Address, PlcConnectionType.Pg, 5000, loggerFactory) { MaxAmQCalled = (ushort)readOptions.MaxJobs, MaxAmQCalling = (ushort)readOptions.MaxJobs }; var logger = loggerFactory?.CreateLogger("Dacs7Cli.ReadAlarms"); try { long msTotal = 0; await client.ConnectAsync(); try { var sw = new Stopwatch(); sw.Start(); var results = await client.ReadPendingAlarmsAsync(); foreach (var alarm in results) { Console.WriteLine($"Alarm update: ID: {alarm.Id} MsgNumber: {alarm.MsgNumber} IsAck: {alarm.IsAck} ", alarm); } sw.Stop(); msTotal += sw.ElapsedMilliseconds; logger?.LogDebug($"ReadAlarmsTime: {sw.Elapsed}"); } catch (Exception ex) { logger?.LogError($"Exception in read alarms {ex.Message}."); } } catch (Exception ex) { logger?.LogError($"An error occured in ReadAlarms: {ex.Message} - {ex.InnerException?.Message}"); return(1); } finally { await client.DisconnectAsync(); } return(0); }