Пример #1
0
        /// <summary>
        /// Initializes EtherCAT and returns found slaves.
        /// </summary>
        /// <param name="interfaceName">The name of the network adapter.</param>
        /// <returns>Returns found slave.</returns>
        public static SlaveInfo ScanDevices(IntPtr context, string interfaceName, SlaveInfo referenceSlave = null)
        {
            ec_slave_info_t[] refSlaveIdentifications = null;

            if (referenceSlave != null)
            {
                refSlaveIdentifications = EcUtilities.ToSlaveIdentifications(referenceSlave);
            }
            else
            {
                refSlaveIdentifications = new ec_slave_info_t[] { }
            };

            // scan devices
            var networkInterface = NetworkInterface
                                   .GetAllNetworkInterfaces()
                                   .Where(nic => nic.Name == interfaceName)
                                   .FirstOrDefault();

            if (networkInterface == null)
            {
                throw new Exception($"{ ErrorMessage.SoemWrapper_NetworkInterfaceNotFound } Interface name: '{ interfaceName }'.");
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                interfaceName = $@"rpcap://\Device\NPF_{networkInterface.Id}";
            }

            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                     RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                interfaceName = $"{interfaceName}";
            }

            else
            {
                throw new PlatformNotSupportedException();
            }

            EcUtilities.CheckErrorCode(context, EcHL.ScanDevices(context, interfaceName, out var slaveIdentifications, out var slaveCount));

            // create slaveInfo from received data
            var offset = 0;
            var newSlaveIdentifications = new ec_slave_info_t[slaveCount + 1]; // correct because EC master = slaveIdentifications[0]

            for (int i = 0; i <= newSlaveIdentifications.Count() - 1; i++)
            {
                newSlaveIdentifications[i] = Marshal.PtrToStructure <ec_slave_info_t>(IntPtr.Add(slaveIdentifications, offset));
                offset += Marshal.SizeOf(typeof(ec_slave_info_t));
            }

            // validate CSA
            while (EcUtilities.EnsureValidCsa(context, newSlaveIdentifications, refSlaveIdentifications))
            {
                //
            }

            return(EcUtilities.ToSlaveInfo(newSlaveIdentifications));
        }