Esempio n. 1
0
        /// <summary>
        /// Connects all items to the controller. Existing network connections will be added to where possible
        /// </summary>
        /// <param name="items"></param>
        /// <param name="controller"></param>
        /// <returns></returns>
        public static List <IControllerConnection> ConnectToController(IEnumerable <IConnectable> items, TECController controller, ConnectionProperties properties)
        {
            var connectables = items
                               .Where(x => x.GetParentConnection() == null);

            var availableIO = controller.AvailableIO + ExistingNetworkIO(controller);
            List <IControllerConnection> connections = new List <IControllerConnection>();

            if (!CanConnectToController(items, controller))
            {
                return(connections);
            }
            foreach (var connectable in connectables)
            {
                var protocols = connectable.AvailableProtocols;
                if (protocols.Count == 1)
                {
                    var connection = controller.Connect(connectable, protocols.First());
                    if (connection == null)
                    {
                        throw new Exception("Connection was Null");
                    }
                    connections.Add(connection);
                    connection.UpdateFromProperties(properties);
                }
                else
                {
                    var connected = false;
                    foreach (var protocol in connectable.AvailableProtocols
                             .Where(x => x is TECProtocol networkProtocol && availableIO.Contains(networkProtocol)))
                    {
                        connected = true;
                        var connection = controller.Connect(connectable, protocol);
                        if (connection == null)
                        {
                            throw new Exception("Connection was Null");
                        }
                        connections.Add(connection);
                        connection.UpdateFromProperties(properties);
                        break;
                    }
                    if (!connected && connectable.AvailableProtocols.Any(x => x is TECHardwiredProtocol) &&
                        availableIO.Contains(connectable.HardwiredIO))
                    {
                        var connection = controller.Connect(connectable, connectable.AvailableProtocols.First(x => x is TECHardwiredProtocol));
                        connection.UpdateFromProperties(properties);
                        connections.Add(connection);
                    }
                }
            }

            if (controller is TECProvidedController pController)
            {
                pController.OptimizeModules();
            }
            return(connections.Distinct().ToList());
        }