using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using TwinCAT.Ads;
using TwinCAT.Ads.TypeSystem;
namespace IOB_WIN_NEXT
{
///
/// Client comunicazioni con PLC Beckhoff TwinCat
///
public class TcAdsClient
{
#region Public Fields
public System.Collections.Concurrent.ConcurrentQueue CodaComandi;
public TwinCAT.Ads.TcAdsSymbolInfoLoader InfoLoader;
///
/// Dizionario delle variabili monitorate (gestite ad evento x modifica), chiave = nome var, valore = symbol x gestione variabile
///
public Dictionary MonitoredItems = new Dictionary();
public TwinCAT.TypeSystem.ISymbolLoader SymbolLoaderInstance;
public TcAdsSymbolInfoCollection Symbols;
#endregion Public Fields
#region Public Constructors
///
/// Inizializza un oggetto ADS x gestione classe comunicazione con TwinCat
///
///
/// Lista dei nomi delle variabili da gestire ad eventChange (es stato macchina)
///
/// indirizzo tipo AmsNetId
///
/// Porta comunicazione: Connect to local PLC - Runtime 1 - TwinCAT2 Port=801, TwinCAT3 Port=851
///
public TcAdsClient(List MonitVars, string indirizzo = "local", int porta = 851)
{
_MonitVars = MonitVars;
MonitoredItems = new Dictionary();
notifyStream = new AdsStream();
newNotificationStream = new AdsStream();
addressList = new Dictionary>();
bool ready = false;
while (!ready)
{
try
{
//LETTURA DEL VETTORE DI INIZIALIZZAZIONE
if (adsClient == null) adsClient = new TwinCAT.Ads.TcAdsClient();
// Connect to local PLC - Runtime 1 - TwinCAT2 Port=801, TwinCAT3 Port=851
if (indirizzo == "")
{
adsClient.Connect(porta);
}
else
{
if (adsClient.IsConnected == false) adsClient.Connect(indirizzo, porta);
}
SymbolLoaderInstance = SymbolLoaderFactory.Create(adsClient, SymbolLoaderSettings.Default);
InfoLoader = adsClient.CreateSymbolInfoLoader();
Symbols = InfoLoader.GetSymbols(true);
ready = true;
}
catch (Exception ex)
{
System.Threading.Thread.Sleep(100);
ready = false;
Debug.Print(ex.Message);
}
}
// inizializzo dizionario delle variabili gestite
foreach (var item in _MonitVars)
{
var currSymbol = (Symbol)SymbolLoaderInstance.Symbols[item];
currSymbol.NotificationSettings = new AdsNotificationSettings(AdsTransMode.OnChange, 100, 100);
currSymbol.ValueChanged += MonItem_ValueChanged;
// aggiungo al dict
MonitoredItems.Add(item, currSymbol);
}
StatoMacchina = (Symbol)SymbolLoaderInstance.Symbols["VarADS.StatoMacchina"];
StatoMacchina.NotificationSettings = new AdsNotificationSettings(AdsTransMode.OnChange, 100, 100);
StatoMacchina.ValueChanged += StatoMacchina_ValueChanged;
#if false
notifyposition = 0;
#endif
cts = new CancellationTokenSource();
//adsClient.AdsNotification += new AdsNotificationEventHandler(adsClient_AdsNotification);
CodaComandi = new System.Collections.Concurrent.ConcurrentQueue();
cts = new CancellationTokenSource(); //Task require CancellationToken.cancel() to stop
Action