Scanning for devices and boxes

When creating a new configuration it is often necessary to align the TwinCAT XAE configuration to the actually available hardware. One option to fullfill this is to start a new TwinCAT XAE configuration from scratch and process the following steps:

Procedure

The procedure to create the ITcSysManager interface (the 'systemManager' instance here) is described in the chapter Accessing TwinCAT Configurations. This interface has a LookupTreeItem method that returns a ITcSmTreeItem pointer to a specific tree item given by its pathname, in this case the shortcut "TIID" which references the I/O devices node.

Code snippet (C#):

ITcSysManager3 systemManager = null; 

public void ScanDevicesAndBoxes()
{     
  systemManager.SetTargetNetId("1.2.3.4.5.6");
  ITcSmTreeItem ioDevicesItem = systemManager.LookupTreeItem("TIID");
  string scannedXml = ioDevicesItem.ProduceXml(false);
  XmlDocument xmlDoc = newXmlDocument();     
  xmlDoc.LoadXml(scannedXml);
  XmlNodeList xmlDeviceList = xmlDoc.SelectNodes("TreeItem/DeviceGrpDef/FoundDevices/Device");     
  List<ITcSmTreeItem> devices = newList<ITcSmTreeItem>();
  int deviceCount = 0;
  foreach (XmlNode node in xmlDeviceList)     
  {
    int itemSubType = int.Parse(node.SelectSingleNode("ItemSubType").InnerText);         
    string typeName = node.SelectSingleNode("ItemSubTypeName").InnerText;
    XmlNode xmlAddress = node.SelectSingleNode("AddressInfo");     
    ITcSmTreeItem device = ioDevicesItem.CreateChild(string.Format("Device_{0}",++deviceCount),itemSubType,string.Empty,null);
    string xml = string.Format("<TreeItem><DeviceDef>{0}</DeviceDef></TreeItem>",xmlAddress.OuterXml);
    device.ConsumeXml(xml);
    devices.Add(device);     
  }
  foreach (ITcSmTreeItem device in devices)     
  {
    string xml = "<TreeItem><DeviceDef><ScanBoxes>1</ScanBoxes></DeviceDef></TreeItem>";
    try
    {
      device.ConsumeXml(xml);
    }
    catch (Exception ex)         
    {
      Console.WriteLine("Warning: {0}",ex.Message);
    }
    foreach (ITcSmTreeItem box in device)
    {
      Console.WriteLine(box.Name);
    }
  }
}