Initial Push

This commit is contained in:
2026-02-11 08:38:36 +01:00
commit 627050501d
81 changed files with 5500 additions and 0 deletions

63
ads-wrapper/.gitattributes vendored Normal file
View File

@@ -0,0 +1,63 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

363
ads-wrapper/.gitignore vendored Normal file
View File

@@ -0,0 +1,363 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd

331
ads-wrapper/AdsManager.cs Normal file
View File

@@ -0,0 +1,331 @@
using System.Text.Json;
using System.Timers;
using TwinCAT;
using TwinCAT.Ads;
using TwinCAT.Ads.TypeSystem;
using TwinCAT.TypeSystem;
namespace Heisig.HMI.AdsManager;
// AdsManager Interface for dependency injection
public interface IAdsManager
{
public void Register(string variableName, EventHandler<ValueChangedEventArgs> eventHandler);
public void Deregister(string variableName, EventHandler<ValueChangedEventArgs> eventHandler);
public void WriteValue(string variableName, object value);
public object? ReadValue(string variableName);
public ISymbolLoader? GetSymbolLoader();
}
public sealed class AdsManager : IDisposable, IAdsManager
{
enum ConnectionState
{
DISCONNECTED,
CONNECTED
}
// Ads client instance
private readonly AdsClient _adsClient = new();
// Ads symbol loader
private ISymbolLoader? _symbolLoader;
// Last value of online change count
private uint? _lastOnlineChangeCount = null;
// Online change detected
private bool _onlineChangeDetected = false;
// Dictionary with symbols and events for variable changing events
private readonly Dictionary<string, List<EventHandler<ValueChangedEventArgs>>> _test = [];
// Timer to test cyclically if we are still connected
private readonly System.Timers.Timer _timer = new();
// Internal connection state
private ConnectionState _state = ConnectionState.DISCONNECTED;
// Filename with the connection settings
private const string _filename = "AdsSettings.json";
// Settings for the connection
private readonly AdsSettings _settings = new();
// Thread safety lock
private static readonly object _lock = new();
// Json serializer options
private readonly JsonSerializerOptions _jsonOptions = new() { WriteIndented = true };
public AdsManager()
{
// Read settings file
_settings = ReadSettings();
// Start cyclic connection test
_timer.Interval = _settings.ReconnectIntervalMS;
_timer.Elapsed += CheckConnection;
_timer.Start();
}
public void Dispose()
{
_timer.Stop();
_timer.Dispose();
_adsClient.Dispose();
}
private void WriteSettings(AdsSettings settings)
{
string text = JsonSerializer.Serialize(settings, _jsonOptions);
File.WriteAllText(_filename, text);
}
private AdsSettings ReadSettings()
{
AdsSettings settings = new();
string text;
if (!File.Exists(_filename))
WriteSettings(settings);
else
{
text = File.ReadAllText(_filename);
settings = JsonSerializer.Deserialize<AdsSettings>(text) ?? new AdsSettings();
}
return settings;
}
// Register a callback on variable change
public void Register(string variableName, EventHandler<ValueChangedEventArgs> eventHandler)
{
List<EventHandler<ValueChangedEventArgs>> tempList;
// Add new variable entry
#pragma warning disable CA1854 // Methode „IDictionary.TryGetValue(TKey, out TValue)“ bevorzugen
if (!_test.ContainsKey(variableName))
#pragma warning restore CA1854 // Methode „IDictionary.TryGetValue(TKey, out TValue)“ bevorzugen
{
// Add new entry
tempList = [eventHandler];
_test.Add(variableName, tempList);
}
else
{
// Append event to variable
tempList = _test[variableName];
foreach (EventHandler<ValueChangedEventArgs> handler in tempList)
{
if (handler == eventHandler)
return;
}
tempList.Add(eventHandler);
_test[variableName] = tempList;
}
// If we are already connected, directly register variable
if (_state == ConnectionState.CONNECTED)
{
try
{
Symbol? symbol = (Symbol?)_symbolLoader?.Symbols[variableName];
if (symbol != null)
symbol.ValueChanged += eventHandler;
}
catch (Exception)
{
Console.WriteLine($"Variable {variableName} could not be found");
}
Console.WriteLine($"Variable {variableName} registered");
}
}
// Remove a registration from the dictionary
public void Deregister(string variableName, EventHandler<ValueChangedEventArgs> eventHandler)
{
List<EventHandler<ValueChangedEventArgs>>? tempList;
bool eventRemoved = false;
if (_test.TryGetValue(variableName, out tempList))
{
foreach (EventHandler<ValueChangedEventArgs> handler in tempList)
{
if (handler == eventHandler)
{
tempList.Remove(eventHandler);
// If we are connected remove directly remove variable changed event
if (_state == ConnectionState.CONNECTED)
{
try
{
Symbol? symbol = (Symbol?)_symbolLoader?.Symbols[variableName];
if (symbol != null)
symbol.ValueChanged -= eventHandler;
}
catch(Exception)
{
Console.WriteLine($"Variable {variableName} could not be found and deregistered");
}
Console.WriteLine("Variable {0} deregistered", variableName);
}
break;
}
if (eventRemoved)
_test[variableName] = tempList;
}
}
}
private void RegisterValueChangedEvents()
{
if (_symbolLoader == null)
return;
Symbol symbol;
foreach(KeyValuePair<string, List<EventHandler<ValueChangedEventArgs>>> entry in _test)
{
symbol = (Symbol)_symbolLoader.Symbols[entry.Key];
foreach (EventHandler<ValueChangedEventArgs> handler in entry.Value)
symbol.ValueChanged += handler;
}
}
public void WriteValue(string variableName, object value)
{
if (_state == ConnectionState.CONNECTED)
{
_adsClient.TryWriteValue(variableName, value);
}
}
public object? ReadValue(string variableName)
{
if (_state == ConnectionState.CONNECTED)
{
_adsClient.TryReadValue(variableName, out object? value);
return value;
}
else
return null;
}
// Cyclic check if we are still connected to the ads server
private void CheckConnection(object? sender, ElapsedEventArgs e)
{
lock(_lock)
{
// Stop timer
_timer.Stop();
}
switch (_state)
{
case ConnectionState.DISCONNECTED:
// Connect if not already connected
if (!_adsClient.IsConnected)
_adsClient.Connect(_settings.AdsAdress, _settings.AdsPort);
// Check if we have a connection
if (TestIfConnected())
{
Console.WriteLine("Connected");
Console.WriteLine("Reading Symbols ...");
// Load ads symbols
_symbolLoader = SymbolLoaderFactory.Create(_adsClient, SymbolLoaderSettings.Default);
Console.WriteLine("{0} Symbols read", _symbolLoader.Symbols.Count);
// Read last online change count
lock(_lock)
{
_lastOnlineChangeCount = (uint)((Symbol)_symbolLoader.Symbols[_settings.OnlineChangeCntVar]).ReadValue();
// Change state to connected
_state = ConnectionState.CONNECTED;
}
// Register value changed events
RegisterValueChangedEvents();
}
break;
case ConnectionState.CONNECTED:
if (!TestIfConnected())
{
Console.WriteLine("Connection lost");
lock (_lock)
_state = ConnectionState.DISCONNECTED;
}
else
{
try
{
uint onlineChangeCnt = (uint)((Symbol)_symbolLoader!.Symbols[_settings.OnlineChangeCntVar]).ReadValue();
lock (_lock)
{
_onlineChangeDetected = false;
if (onlineChangeCnt != _lastOnlineChangeCount)
_onlineChangeDetected = true;
_lastOnlineChangeCount = (uint)((Symbol)_symbolLoader.Symbols[_settings.OnlineChangeCntVar]).ReadValue();
}
// Reread symbols
if (_onlineChangeDetected)
{
Console.WriteLine("Online change detected. Rereading symbols ...");
_symbolLoader = SymbolLoaderFactory.Create(_adsClient, SymbolLoaderSettings.Default);
Console.WriteLine("{0} Symbols read", _symbolLoader.Symbols.Count);
RegisterValueChangedEvents();
}
}
catch(Exception)
{
Console.WriteLine("Could not read online change count");
}
}
break;
}
lock (_lock)
{
// Restart timer
_timer.Start();
}
}
private bool TestIfConnected()
{
bool connected;
// Test if connection could be established and is still alive
try
{
// Read ads server status
StateInfo state = _adsClient.ReadState();
connected = true;
}
catch (AdsErrorException)
{
connected = false;
}
return connected;
}
public ISymbolLoader? GetSymbolLoader()
{
return _symbolLoader;
}
}

View File

@@ -0,0 +1,29 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GeneratePackageOnBuild>True</GeneratePackageOnBuild>
<Title>Ads Manager</Title>
<Authors>M.Heisig</Authors>
<Company>Heisig GmbH</Company>
<Description>Wrapper für den Ads Client von Beckhoff um automatische reconnects und onlinechanges zu behandeln.</Description>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageOutputPath>C:\Users\matthias.heisig\Documents\nuget_packages</PackageOutputPath>
<PackageProjectUrl>https://gitlab.cmblu.de/matthias.heisig/ads-wrapper</PackageProjectUrl>
<Version>1.0.0.7</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Beckhoff.TwinCAT.Ads" Version="6.1.197" />
</ItemGroup>
<ItemGroup>
<None Update="README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34525.116
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AdsManager", "AdsManager.csproj", "{4B80F068-4E6D-4D2D-831B-8150970600C7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4B80F068-4E6D-4D2D-831B-8150970600C7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4B80F068-4E6D-4D2D-831B-8150970600C7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4B80F068-4E6D-4D2D-831B-8150970600C7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4B80F068-4E6D-4D2D-831B-8150970600C7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {32AA8544-D809-4C87-81DE-505FDD964D85}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,27 @@
namespace Heisig.HMI.AdsManager;
/// <summary>
/// Struct with the settings for connecting to the ads server
/// </summary>
public class AdsSettings
{
/// <summary>
/// Ads server address
/// </summary>
public string AdsAdress { get; set; } = "127.0.0.1.1.1";
/// <summary>
/// Ads server port
/// </summary>
public int AdsPort { get; set; } = 851;
/// <summary>
/// Intervall for reconnect tries
/// </summary>
public int ReconnectIntervalMS { get; set; } = 2000;
/// <summary>
/// Variable name for which contains the online change counter
/// </summary>
public string OnlineChangeCntVar { get; set; } = "TWinCAT_SystemInfoVarList._AppInfo.OnlineChangeCnt";
}

2
ads-wrapper/README.md Normal file
View File

@@ -0,0 +1,2 @@
# Ads Manager
Ads Wrapper klasse um automatische reconnects und online changes mit einem ADS Server der Beckhoff steuerung zu behandeln.