Esempio n. 1
0
        public void Configure(SlaveInfo rootSlaveInfo = null)
        {
            SlaveInfo         actualSlaveInfo;
            IList <SlaveInfo> slaveInfoSet;
            IList <SlaveInfo> actualSlaveInfoSet;
            NetworkInterface  networkInterface;

            networkInterface = NetworkInterface.GetAllNetworkInterfaces().Where(nic => nic.Name == _settings.InterfaceName).FirstOrDefault();

            if (networkInterface?.OperationalStatus != OperationalStatus.Up)
            {
                throw new Exception($"Network interface '{_settings.InterfaceName}' is not linked. Aborting action.");
            }

            #region "PreOp"

            actualSlaveInfo = EcUtilities.ScanDevices(this.Context, _settings.InterfaceName, null);

            if (rootSlaveInfo == null)
            {
                rootSlaveInfo = actualSlaveInfo;

                rootSlaveInfo.Descendants().ToList().ForEach(current =>
                {
                    ExtensibilityHelper.CreateDynamicData(_settings.EsiDirectoryPath, _extensionFactory, current);
                });
            }

            slaveInfoSet       = rootSlaveInfo.Descendants().ToList();
            actualSlaveInfoSet = actualSlaveInfo.Descendants().ToList();

            this.ValidateSlaves(slaveInfoSet, actualSlaveInfoSet);
            this.ConfigureSlaves(slaveInfoSet);
            this.ConfigureIoMap(slaveInfoSet);
            this.ConfigureDc();
            this.ConfigureSync01(slaveInfoSet);

            #endregion

            #region "SafeOp"

            EcUtilities.CheckErrorCode(this.Context, EcHL.CheckSafeOpState(this.Context), nameof(EcHL.CheckSafeOpState));

            #endregion

            #region "Op"

            EcUtilities.CheckErrorCode(this.Context, EcHL.RequestOpState(this.Context), nameof(EcHL.RequestOpState));

            #endregion

            if (_watchdogTask == null)
            {
                _watchdogTask = Task.Run(() => this.WatchdogRoutine(), _cts.Token);
            }
        }
Esempio n. 2
0
        static async Task Main(string[] args)
        {
            /* Set interface name. Edit this to suit your needs. */
            var interfaceName = "eth0";

            /* Set ESI location. Make sure it contains ESI files! The default path is /home/{user}/.local/share/ESI */
            var localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            var esiDirectoryPath = Path.Combine(localAppDataPath, "ESI");

            Directory.CreateDirectory(esiDirectoryPath);

            /* Copy native file. NOT required in end user scenarios, where EtherCAT.NET package is installed via NuGet! */
            var codeBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            Directory.EnumerateFiles(Path.Combine(codeBase, "runtimes"), "*soem_wrapper.*", SearchOption.AllDirectories).ToList().ForEach(filePath =>
            {
                if (filePath.Contains(RuntimeEnvironment.RuntimeArchitecture))
                {
                    File.Copy(filePath, Path.Combine(codeBase, Path.GetFileName(filePath)), true);
                }
            });

            /* prepare dependency injection */
            var services = new ServiceCollection();

            ConfigureServices(services);

            /* create types */
            var provider         = services.BuildServiceProvider();
            var extensionFactory = provider.GetRequiredService <IExtensionFactory>();
            var loggerFactory    = provider.GetRequiredService <ILoggerFactory>();
            var logger           = loggerFactory.CreateLogger("EtherCAT Master");

            /* create EtherCAT master settings (with 10 Hz cycle frequency) */
            var cycleFrequency = 10U;
            var settings       = new EcSettings(cycleFrequency, esiDirectoryPath, interfaceName);

            /* create root slave info by scanning available slaves */
            var rootSlaveInfo = EcUtilities.ScanDevices(settings.InterfaceName);

            rootSlaveInfo.Descendants().ToList().ForEach(current =>
            {
                ExtensibilityHelper.CreateDynamicData(settings.EsiDirectoryPath, extensionFactory, current);
            });

            /* print list of slaves */
            var message = new StringBuilder();
            var slaves  = rootSlaveInfo.Descendants().ToList();

            message.AppendLine($"Found {slaves.Count()} slaves:");

            slaves.ForEach(current =>
            {
                message.AppendLine($"{current.DynamicData.Name} (PDOs: {current.DynamicData.PdoSet.Count} - CSA: { current.Csa })");
            });

            logger.LogInformation(message.ToString().TrimEnd());

            /* create variable references for later use */
            var variables = slaves.SelectMany(child => child.GetVariableSet()).ToList();

            /* create EC Master */
            using (var master = new EcMaster(settings, extensionFactory, logger))
            {
                try
                {
                    master.Configure(rootSlaveInfo);
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.Message);
                    throw;
                }

                /* start master */
                var random = new Random();
                var cts    = new CancellationTokenSource();

                var task = Task.Run(() =>
                {
                    var sleepTime = 1000 / (int)cycleFrequency;

                    while (!cts.IsCancellationRequested)
                    {
                        master.UpdateIO(DateTime.UtcNow);

                        unsafe
                        {
                            if (variables.Any())
                            {
                                var myVariableSpan = new Span <int>(variables.First().DataPtr.ToPointer(), 1);
                                myVariableSpan[0]  = random.Next(0, 100);
                            }
                        }

                        Thread.Sleep(sleepTime);
                    }
                }, cts.Token);

                /* wait for stop signal */
                Console.ReadKey(true);

                cts.Cancel();
                await task;
            }
        }