public class Notification
{
private TcAdsClient _tcClient = null;
private AdsStream _adsStream = null;
private BinaryReader _binRead = null;
private int _notificationHandle = 0;
public Notification()
{
System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Factory.StartNew(() => Load());
task.Start();
}
private void Load()
{
try
{
_tcClient = new TcAdsClient();
/* connect the client to the local PLC */
_tcClient.Connect(851);
_adsStream = new AdsStream(2); /* stream storing the ADS state of the PLC */
_binRead = new BinaryReader(_adsStream); /* reader to read the state data */
/* register callback to react on state changes of the local AMS router */
_tcClient.AmsRouterNotification +=
new AmsRouterNotificationEventHandler(AmsRouterNotificationCallback);
_notificationHandle = _tcClient.AddDeviceNotification(
(int)AdsReservedIndexGroups.DeviceData, /* index group of the device state*/
(int)AdsReservedIndexOffsets.DeviceDataAdsState, /*index offsset of the device state */
_adsStream, /* stream to store the state */
AdsTransMode.OnChange, /* transfer mode: transmit ste on change */
0, /* transmit changes immediately */
0,
null);
/* register callback to react on state changes of the local PLC */
_tcClient.AdsNotification += new AdsNotificationEventHandler(OnAdsNotification);
}
catch (AdsErrorException ex)
{
Console.WriteLine(ex.Message);
}
}
/* callback function called on state changes of the PLC */
void OnAdsNotification(object sender, AdsNotificationEventArgs e)
{
if (e.NotificationHandle == _notificationHandle)
{
AdsState plcState = (AdsState)_binRead.ReadInt16(); /* state was written to the stream */
Console.WriteLine(plcState.ToString());
}
}
/* callback function called on state changes of the local AMS router */
void AmsRouterNotificationCallback(object sender, AmsRouterNotificationEventArgs e)
{
Console.WriteLine(e.State.ToString());
}