Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions NET/AdsMapperCli/DestinationDataObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,37 @@ namespace AdsMapperCli
/* PLC Struct:
TYPE ST_Test :
STRUCT
bBoolValue1 : BOOL := TRUE;
nByteValue1 : BYTE := 255;
nSbyteValue1 : BYTE := 127;
nUshortValue1 : UINT := 65535;
nShortValue1 : INT := 32767;
nUintValue1 : UDINT := 4294967295;
nIntValue1 : DINT := 2147483647;
fFloatValue1 : REAL := -1.11;
fDoubleValue1 : LREAL := 1.11;
fDoubleValue2 : LREAL := 2.22;
fDoubleValue3 : LREAL := 3.33;
fDoubleValue4MappedName : LREAL := 4.44;
tPlcTimeValue1 : TIME := T#1H33M44S555MS;
dPlcDateValue1 : DATE := D#2021-08-30;
dtPlcDateTimeValue1 : DATE_AND_TIME := DT#2021-08-30-11:12:13;
aIntArrayValue : ARRAY[0..2] OF DINT := [1, 2, 3];
eEnumStateValue : E_State := E_State.eRunning;
sPlcVersion : STRING(10) := '21.08.30.0';
sUtf7String : STRING(6) := 'ÄÖö@Ü7';
wsUnicodeString : WSTRING(6) := "ÄÖö@Ü8";
bBoolValue1 : BOOL := TRUE;
nByteValue1 : BYTE := 255;
nSbyteValue1 : BYTE := 127;
nUshortValue1 : UINT := 65535;
nShortValue1 : INT := 32767;
nUintValue1 : UDINT := 4294967295;
nIntValue1 : DINT := 2147483647;
fFloatValue1 : REAL := -1.11;
fDoubleValue1 : LREAL := 1.11;
fDoubleValue2 : LREAL := 2.22;
fDoubleValue3 : LREAL := 3.33;
fDoubleValue4MappedName : LREAL := 4.44;
tPlcTimeValue1 : TIME := T#1H33M44S555MS;
dPlcDateValue1 : DATE := D#2021-08-30;
dtPlcDateTimeValue1 : DATE_AND_TIME := DT#2021-08-30-11:12:13;
aIntArrayValue : ARRAY[0..2] OF DINT := [1, 2, 3];
eEnumStateValue : E_State := E_State.eRunning;
sPlcVersion : STRING(10) := '21.08.30.0';
sUtf7String : STRING(6) := 'ÄÖö@Ü7';
wsUnicodeString : WSTRING(6) := "ÄÖö@Ü8";
END_STRUCT
END_TYPE

{attribute 'qualified_only'}
{attribute 'strict'}
TYPE E_State :
(
eNone := 0,
eStartup := 1,
eRunning := 2,
eStop := 3
eNone := 0,
eStartup := 1,
eRunning := 2,
eStop := 3
);
END_TYPE
*/
Expand Down Expand Up @@ -78,9 +78,10 @@ public class DestinationDataObject : IPlcState
public string Utf7String { get; set; }
public string UnicodeString { get; set; }

//public Motor MotorObject { get; set; }
// public Motor MotorObject { get; set; }
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "Only for tests")]
public class Motor
{
public double ActualSpeed { get; set; }
Expand Down
49 changes: 26 additions & 23 deletions NET/AdsMapperCli/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,57 +8,60 @@ namespace AdsMapperCli
{
public static class Program
{
private static readonly ILogger _logger = LogManager.GetCurrentClassLogger();
private static PlcAdsConnectionService _adsConnectionService;
private static PlcAdsStateReader<DestinationDataObject> _plcAdsTestPlaceStatus;
private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();
private static PlcAdsConnectionService adsConnectionService;
private static PlcAdsStateReader<DestinationDataObject> plcAdsTestPlaceStatus;

public static void Main(string[] args)
{
SetupNLog();
try
{
string amsnetid = "172.28.85.92.1.1";
_logger.Info("Setup & Connect to TwinCat on {0}", amsnetid);
_adsConnectionService = new PlcAdsConnectionService(amsnetid, 851);
_adsConnectionService.ConnectionStateChanged += OnConnectionStateChanged;
string amsnetid = "204.35.225.246.1.1";
Logger.Info("Setup & Connect to TwinCat on {0}", amsnetid);
adsConnectionService = new PlcAdsConnectionService(amsnetid, 851);
adsConnectionService.ConnectionStateChanged += OnConnectionStateChanged;

var testPlaceStatusConfig = new PlcAdsStateReaderConfig<DestinationDataObject>
{
VariablePath = $"PCS_Status.stTest",
VariablePath = $"GVL.stTest",
AdsMapperConfiguration = new AdsMapperConfiguration<DestinationDataObject>(
cfg => cfg.ForAllSourceMember(opt => opt.RemovePrefix("f", "n", "b", "a", "e", "t", "d", "dt", "s", "ws"))),
CycleTime = TimeSpan.FromMilliseconds(2),
MaxDelay = TimeSpan.FromMilliseconds(500),
};

// Setup state Reader
_plcAdsTestPlaceStatus = new PlcAdsStateReader<DestinationDataObject>(_adsConnectionService, testPlaceStatusConfig);
_plcAdsTestPlaceStatus.StatesChanged += OnPlcStatesChange;
plcAdsTestPlaceStatus = new PlcAdsStateReader<DestinationDataObject>(adsConnectionService, testPlaceStatusConfig);
plcAdsTestPlaceStatus.StatesChanged += OnPlcStatesChange;

// RocknRoll
_adsConnectionService.Start();
adsConnectionService.Start();

// Wait for termination
var keepRunning = true;
Console.CancelKeyPress += delegate (object sender, ConsoleCancelEventArgs e)
Console.CancelKeyPress += (sender, e) =>
{
e.Cancel = true;
keepRunning = false;
};

while (keepRunning) { }
while (keepRunning)
{
// endless
}

_logger.Info("stopping output");
_plcAdsTestPlaceStatus.StopSampling();
Logger.Info("stopping output");
plcAdsTestPlaceStatus.StopSampling();
}
catch (Exception ex)
{
_logger.Info(ex, "houston we have a problem: {0}", ex.Message);
Logger.Info(ex, "houston we have a problem: {0}", ex.Message);
}
finally
{
_plcAdsTestPlaceStatus?.Dispose();
_adsConnectionService?.Dispose();
plcAdsTestPlaceStatus?.Dispose();
adsConnectionService?.Dispose();
}
}

Expand All @@ -77,13 +80,13 @@ private static void OnConnectionStateChanged(object sender, PlcConnectionChangeA
{
if (e.Connected)
{
_logger.Info("Connected to TwinCat");
_plcAdsTestPlaceStatus.StartSampling();
Logger.Info("Connected to TwinCat");
plcAdsTestPlaceStatus.StartSampling();
}
else
{
Console.WriteLine("Disconnected to TwinCat");
_plcAdsTestPlaceStatus.StopSampling();
plcAdsTestPlaceStatus.StopSampling();
}
}

Expand All @@ -92,8 +95,8 @@ private static void OnPlcStatesChange(object source, PlcMultiStateChangedEventAr
var config = new System.Text.Json.JsonSerializerOptions() { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
config.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());

_logger.Info("New State");
_logger.Info(System.Text.Json.JsonSerializer.Serialize(testPlaceStatusEvent.State, config));
Logger.Info("New State");
Logger.Info(System.Text.Json.JsonSerializer.Serialize(testPlaceStatusEvent.State, config));
}
}
}
13 changes: 8 additions & 5 deletions NET/Build/Mbc.Pcs.Net.TwinCat.EventLog.nuspec
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
<metadata>
<id>Mbc.Pcs.Net.TwinCat.EventLog</id>
<version>1.0.0</version>
<version>1.0.1</version>
<authors>mbc engineering</authors>
<requireLicenseAcceptance>false</requireLicenseAcceptance>
<projectUrl>https://github.com/mbc-engineering/net-pcs</projectUrl>
<description>unofficial assemblies from type libraries for TwinCat Alarm and Event alias TcEventLoggerLib and TcEventLogProxyLib</description>
<dependencies>
<group targetFramework=".NETFramework4.6.1" />
<!-- Version 7.0 is the default value-->
<group targetFramework="net6.0-windows7.0" />
</dependencies>
</metadata>
<files>
<file src="..\libs\Interop.TCEVENTLOGGERLib.dll" target="lib\net461\Interop.TCEVENTLOGGERLib.dll" />
<file src="..\libs\Interop.TcEventLogProxyLib.dll" target="lib\net461\Interop.TcEventLogProxyLib.dll" />
<file src="..\Libs\Interop.TCEVENTLOGGERLib.dll" target="lib\net461\Interop.TCEVENTLOGGERLib.dll" />
<file src="..\Libs\Interop.TcEventLogProxyLib.dll" target="lib\net461\Interop.TcEventLogProxyLib.dll" />
<file src="..\Libs\Interop.TCEVENTLOGGERLib.dll" target="lib\net6.0-windows7.0\Interop.TCEVENTLOGGERLib.dll" />
<file src="..\Libs\Interop.TcEventLogProxyLib.dll" target="lib\net6.0-windows7.0\Interop.TcEventLogProxyLib.dll" />
</files>
</package>
2 changes: 1 addition & 1 deletion NET/CallAds/CallAds.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Beckhoff.TwinCAT.Ads">
<Version>4.3.11</Version>
<Version>5.0.528</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Expand Down
34 changes: 18 additions & 16 deletions NET/CallAds/PcsCommand2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using TwinCAT;
using TwinCAT.Ads;

namespace AtomizerUI.link
Expand All @@ -11,27 +12,28 @@ namespace AtomizerUI.link
public class PcsCommand2<Tout> where Tout : new()
{
private const int DEFAULT_TIME_OUT_SECOND = 8;
private readonly TcAdsClient _adsClient;
private readonly IAdsConnection _adsClient;
/// <summary>
/// Path to the PLC Command variable
/// </summary>
private readonly string _adsCommandVar;
private IDictionary<string, ITcAdsDataType> _commandSymbols;

public PcsCommand2(TcAdsClient adsClient, string adsCommandVar)
public PcsCommand2(IAdsConnection adsClient, string adsCommandVar)
{
if (!adsClient.IsConnected)
{
throw new AdsException($"The ADS client use in the {nameof(PcsCommand2<Tout>)} is not connected.");
}

_adsClient = adsClient;
_adsClient = adsClient;
_adsCommandVar = adsCommandVar;

Timeout = TimeSpan.FromSeconds(DEFAULT_TIME_OUT_SECOND);
}

public PcsCommand2(TcAdsClient adsClient, string commandVar, TimeSpan timeout) : this(adsClient, commandVar)
public PcsCommand2(IAdsConnection adsClient, string commandVar, TimeSpan timeout)
: this(adsClient, commandVar)
{
Timeout = timeout;
}
Expand Down Expand Up @@ -76,15 +78,15 @@ public Tout Execute<Tin>(Tin argsIn)
Value = prop.GetValue(argsIn),
TcAdsDataType = _commandSymbols[symbolFullPath]
});
}
}
}

_adsClient.WriteSumVariables(symbolsToWrite);

_adsClient.WriteObjectVariables(argsIn, _adsCommandVar, _commandSymbols);

return Execute();
}
}

public Tout Execute()
{
Expand All @@ -97,7 +99,7 @@ public Tout Execute(CancellationToken cancelToken)
try
{
SetExecuteFlag();

var dataExch = new DataExchange();
var cmdHandle = _adsClient.AddDeviceNotificationEx($"{_adsCommandVar}.stHandshake", AdsTransMode.OnChange,
TimeSpan.Zero, TimeSpan.Zero, dataExch, typeof(CommandControlData));
Expand Down Expand Up @@ -127,7 +129,7 @@ public Tout Execute(CancellationToken cancelToken)
var cmdHndl = _adsClient.CreateVariableHandle(_adsCommandVar + ".stHandshake");
try
{
var ccd = (CommandControlData) _adsClient.ReadAny(cmdHndl, typeof (CommandControlData));
var ccd = (CommandControlData)_adsClient.ReadAny(cmdHndl, typeof(CommandControlData));
if (!ccd.Execute && !ccd.Busy)
{
break;
Expand All @@ -136,7 +138,7 @@ public Tout Execute(CancellationToken cancelToken)
finally
{
_adsClient.DeleteVariableHandle(cmdHndl);
}
}

throw new PcsCommandTimeoutException();
}
Expand All @@ -146,14 +148,14 @@ public Tout Execute(CancellationToken cancelToken)
{
_adsClient.DeleteDeviceNotification(cmdHandle);
}
}
}
finally
{
_adsClient.AdsNotificationEx -= OnAdsnotificationEx;
}

// Read Result values
return ReadResult();
return ReadResult();
}

private void ReadSymbols()
Expand All @@ -169,18 +171,18 @@ private void ReadSymbols()
}
}

private Tout ReadResult()
private Tout ReadResult()
{
// Read all output values
var test = new Tout();
Tout result = _adsClient.ReadObjectVariables(new Tout(), _adsCommandVar, _commandSymbols);

return result;
return result;
}

private void SetExecuteFlag()
{
_adsClient.WriteVariable(_adsCommandVar + ".stHandshake.bExecute", true);
_adsClient.WriteVariable(_adsCommandVar + ".stHandshake.bExecute", true);
}

private void ResetExecuteFlag()
Expand All @@ -192,7 +194,7 @@ void OnAdsnotificationEx(object sender, AdsNotificationExEventArgs e)
{
if (e.UserData is DataExchange)
{
((DataExchange) e.UserData).Set(e.Value);
((DataExchange)e.UserData).Set(e.Value);
}
}

Expand All @@ -204,7 +206,7 @@ void CheckResultCode(ushort resultCode)
{
case 0:
// Init state
return;
return;
case 1:
errorMsg = "Running";
break;
Expand Down
7 changes: 1 addition & 6 deletions NET/CallAds/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@ class Program
{
static void Main(string[] args)
{
var client = new TcAdsClient
{
Synchronize = false
};

var client = new AdsClient();
client.Connect(851);
#if true
var command = new PcsCommand2<AddCommandParam.Output>(client, "Commands.AddCommand1");
Expand All @@ -33,7 +29,6 @@ static void Main(string[] args)
Console.ReadKey();
#endif


#if false
var command = new PcsCommand(client, "Commands.stAddCommand")
{
Expand Down
Loading