private void DeviceRemoved(object sender, INTV.Shared.Interop.DeviceManagement.DeviceChangeEventArgs e)
 {
     if (e.Type == INTV.Core.Model.Device.ConnectionType.Serial)
     {
         var removedDevice = AvailableSerialPorts.FirstOrDefault(p => p.PortName == e.Name);
         if (DeviceChange.IsDeviceChangeFromSystem(e.State))
         {
             if ((removedDevice != null) && AvailableSerialPorts.Remove(removedDevice))
             {
                 INTV.Shared.ComponentModel.CommandManager.InvalidateRequerySuggested();
             }
         }
         else
         {
             // Removal may also indicate that the device is not valid for use by the party responsible for showing the dialog.
             // In such a case, disable the item.
             if ((removedDevice != null) && !DisabledSerialPorts.Contains(e.Name))
             {
                 removedDevice.IsSelectable = false;
                 DisabledSerialPorts.Add(e.Name);
                 INTV.Shared.ComponentModel.CommandManager.InvalidateRequerySuggested();
             }
         }
     }
 }
Example #2
0
        public static void Uncheck(Guid uidGuid)
        {
            var index = GetIndex <CheckListItem>(uidGuid);

            if (AvailableSerialPorts.Any(availableSerialPort => uidGuid == Guid.Parse(availableSerialPort.UidGuid)))
            {
                var checkItem = new CheckListItem
                {
                    ItemName  = AvailableSerialPorts[index].ItemName,
                    UidGuid   = AvailableSerialPorts[index].UidGuid,
                    Content   = AvailableSerialPorts[index].Content,
                    IsChecked = false
                };
                AvailableSerialPorts.RemoveAt(index);
                AvailableSerialPorts.Insert(index, checkItem);
            }
            else if (AvailableModbusSerialPorts.Any(
                         availableModbusSerialPort => uidGuid == Guid.Parse(availableModbusSerialPort.UidGuid)))
            {
                var checkItem = new CheckListItem
                {
                    ItemName  = AvailableModbusSerialPorts[index].ItemName,
                    UidGuid   = AvailableModbusSerialPorts[index].UidGuid,
                    Content   = AvailableModbusSerialPorts[index].Content,
                    IsChecked = false
                };
                AvailableModbusSerialPorts.RemoveAt(index);
                AvailableModbusSerialPorts.Insert(index, checkItem);
            }
            else
            {
                throw new NullReferenceException();
            }
        }
 private void DeviceAdded(object sender, INTV.Shared.Interop.DeviceManagement.DeviceChangeEventArgs e)
 {
     if ((e.Type == INTV.Core.Model.Device.ConnectionType.Serial) && DeviceChange.IsDeviceChangeFromSystem(e.State))
     {
         if (!AvailableSerialPorts.Any(p => p.PortName == e.Name) && ((InclusionFilter == null) || InclusionFilter(Connection.CreatePseudoConnection(e.Name, e.Type))))
         {
             AvailableSerialPorts.Add(new SerialPortViewModel(e.Name));
         }
         INTV.Shared.ComponentModel.CommandManager.InvalidateRequerySuggested();
     }
 }
Example #4
0
        private void Do_connect()
        {
            if (!isConnected)
            {
                string selectedPort = "";
                int    baudr        = 0;
                isConnected = true;
                if (AvailableSerialPorts.GetItemText(AvailableSerialPorts.SelectedItem) != "")
                {
                    selectedPort = AvailableSerialPorts.GetItemText(AvailableSerialPorts.SelectedItem);
                }
                if (Cmbaudr.GetItemText(Cmbaudr.SelectedItem) != "")
                {
                    baudr = Int32.Parse(Cmbaudr.GetItemText(Cmbaudr.SelectedItem));
                }

                if ((selectedPort != "") && (baudr != 0))
                {
                    if (SerialPort.GetPortNames().ToList().Contains(selectedPort))
                    {
                        Properties.Settings.Default.baurdr  = Cmbaudr.GetItemText(Cmbaudr.SelectedItem);
                        Properties.Settings.Default.ComPort = selectedPort;
                        DserialPort1.PortName = selectedPort;
                        DserialPort1.BaudRate = baudr;
                        if (DserialPort1.IsOpen == false)
                        {
                            try
                            {
                                DserialPort1.Open();
                            }
                            catch (Exception)
                            {
                                label2.Text = "Port in use!";
                            }
                        }
                    }
                }
            }
            else
            {
                isConnected = false;
                ;// well shit
                DserialPort1.Close();
            }
        }
Example #5
0
        public static void ChangeCheck(Guid uidGuid)
        {
            var cboCheckListItem = OppositeCheck(uidGuid);
            var index            = GetIndex <CheckListItem>(uidGuid);

            if (cboCheckListItem == null)
            {
                return;
            }
            var cbo = (CheckListItem)cboCheckListItem;

            cbo.IsChecked = false;
            CheckListItem item;

            switch (CheckType(uidGuid))
            {
            case 1:
                //disables Modbus COM Port
                item = AvailableSerialPorts.First(
                    availableSerialPorts => Guid.Parse(availableSerialPorts.UidGuid) == uidGuid);
                item.IsChecked = false;
                AvailableModbusSerialPorts.RemoveAt(index);
                AvailableModbusSerialPorts.Insert(index, cbo);
                break;

            case 2:

                //disables Serial COM Port
                item = AvailableModbusSerialPorts.First(
                    availableModbusSerialPorts => Guid.Parse(availableModbusSerialPorts.UidGuid) == uidGuid);
                item.IsChecked = false;

                AvailableSerialPorts.RemoveAt(index);
                AvailableSerialPorts.Insert(index, cbo);
                break;

            case null:
                return;

            default:
                return;
            }
        }
        /// <summary>
        /// Proivdes a threadsafe way to close the serial ports
        /// </summary>
        /// <param name="index">
        /// Index for Dynamic Server Allocation
        /// </param>
        public static void CloseSerialPortUnexpectedly(int index, Dispatcher uiDispatcher)
        {
            if (!SerialPorts[index].IsOpen)
            {
                return;
            }
            while (SerialPorts[index].IsOpen)
            {
                SerialPorts[index].Close();
            }

            uiDispatcher.Invoke((MethodInvoker) delegate
            {
                ;
                var i = 0;
                i    += AvailableSerialPorts.TakeWhile(e => Guid.Parse(e.UidGuid) == SerialCommunications[index].UidGuid)
                        .Count();

                if (i > (AvailableSerialPorts.Count - 1))
                {
                    i  = 0;
                    i += AvailableModbusSerialPorts
                         .TakeWhile(e => Guid.Parse(e.UidGuid) == SerialCommunications[index].UidGuid)
                         .Count();
                    if (i > (AvailableModbusSerialPorts.Count - 1))
                    {
                        throw new NullReferenceException();
                    }

                    var checklistItem = new CheckListItem
                    {
                        IsChecked = false,
                        Content   = AvailableModbusSerialPorts[i].Content,
                        ItemName  = AvailableModbusSerialPorts[i].ItemName,
                        UidGuid   = AvailableModbusSerialPorts[i].UidGuid
                    };

                    AvailableModbusSerialPorts.RemoveAt(i);
                    AvailableModbusSerialPorts.Insert(i, checklistItem);
                }
                else
                {
                    var checkListItem = new CheckListItem
                    {
                        Content   = AvailableSerialPorts[i].Content,
                        IsChecked = false,
                        ItemName  = AvailableSerialPorts[i].ItemName,
                        UidGuid   = AvailableSerialPorts[i].UidGuid
                    };

                    AvailableSerialPorts.RemoveAt(i);
                    AvailableSerialPorts.Insert(i, checkListItem);
                }

                MessageBox.Show(
                    @"Error with Serial Port. Closing connection. Please check settings and connection and try again.",
                    @"Serial Port Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            });
            SerialPorts          = RemoveAtIndex <SerialPort>(index, SerialPorts);
            SerialCommunications = RemoveAtIndex <SerialCommunication>(index, SerialCommunications);
            StatsGroupings       = RemoveAtIndex <int>(index, StatsGroupings);
            ServerInformation    = RemoveAtIndex <RabbitServerInformation>(index, ServerInformation);
            Lineseries           = RemoveAtIndex <LineSeries>(index, Lineseries);

            while (FactoryChannel[index].IsOpen)
            {
                FactoryChannel[index].Close();
            }
            while (FactoryConnection[index].IsOpen)
            {
                FactoryConnection[index].Close();
            }

            FactoryChannel    = RemoveAtIndex <IModel>(index, FactoryChannel);
            FactoryConnection = RemoveAtIndex <IConnection>(index, FactoryConnection);
            Factory           = RemoveAtIndex <IConnectionFactory>(index, Factory);
        }
        private bool ThoroughScan()
        {
            Log(1, "Performing thorough scan.");

            // Then try if last stored connection can be opened
            if (PersistentSettings && TryConnection(_serialConnectionManagerSettings.Port, _serialConnectionManagerSettings.BaudRate) == DeviceStatus.Available)
            {
                return(true);
            }

            // Slowly walk through
            foreach (var portName in AvailableSerialPorts)
            {
                // Get baud rates collection
                var baudRateCollection = DeviceScanBaudRateSelection
                    ? SerialUtils.GetSupportedBaudRates(portName)
                    : new[] { _serialTransport.CurrentSerialSettings.BaudRate };

                //  Now loop through baud rate collection
                if (baudRateCollection.Any())
                {
                    Log(1, "Trying serial port " + portName + " using " + baudRateCollection.Length + " baud rate(s).");

                    foreach (var baudRate in baudRateCollection)
                    {
                        // Stop scanning if state was changed
                        if (ConnectionManagerMode != Mode.Scan)
                        {
                            return(false);
                        }

                        DeviceStatus status = TryConnection(portName, baudRate);
                        if (status == DeviceStatus.Available)
                        {
                            return(true);
                        }
                        if (status == DeviceStatus.IdentityMismatch)
                        {
                            break;                                          // break the loop and continue to next port.
                        }
                    }
                }

                // If port list has changed, interrupt scan and test new ports first
                if (NewPortScan())
                {
                    return(true);
                }
            }

            if (!AvailableSerialPorts.Any())
            {
                // Need to check for new ports if current ports list is empty
                if (NewPortScan())
                {
                    return(true);
                }

                // Add small delay to reduce of Quick->Thorough->Quick->Thorough scan attempts - 400ms here + 100ms in main loop = ~500ms
                Thread.Sleep(400);
            }

            return(false);
        }
        /// <summary>
        /// Initializes a new instances of SerialPortSelectorViewModel.
        /// </summary>
        /// <param name="prompt">The prompt to display in the port selection area.</param>
        /// <param name="availablePorts">The available ports.</param>
        /// <param name="disabledPorts">Non-selectable ports.</param>
        /// <param name="selectedSerialPort">The currently selected port.</param>
        /// <param name="baudRates">Available baud rates to choose from.</param>
        /// <param name="defaultBaudRate">The default baud rate.</param>
        /// <param name="checkPortAvailability">If <c>true</c>, check the port to see if it is already in use before adding it to the selection list.</param>
        /// <param name="inclusionFilter">If <c>null</c> or it returns <c>true</c>, ports from all available ports are included.</param>
        public SerialPortSelectorViewModel(string prompt, IEnumerable <string> availablePorts, IEnumerable <string> disabledPorts, string selectedSerialPort, IEnumerable <int> baudRates, int defaultBaudRate, bool checkPortAvailability, Predicate <IConnection> inclusionFilter)
        {
            InclusionFilter = inclusionFilter;
            if (!string.IsNullOrWhiteSpace(prompt))
            {
                Prompt = prompt;
            }
            else
            {
                Prompt = Resources.Strings.SelectSerialPortDialog_Message;
            }
            if (baudRates == null)
            {
                BaudRates = new ObservableCollection <BaudRateViewModel>(new[] { new BaudRateViewModel(defaultBaudRate) });
            }
            else
            {
                BaudRates = new ObservableCollection <BaudRateViewModel>(baudRates.Select(r => new BaudRateViewModel(r)));
            }
            var ports = availablePorts;

            if ((ports == null) || !ports.Any())
            {
                ports = inclusionFilter == null ? SerialPortConnection.AvailablePorts : SerialPortConnection.GetAvailablePorts(inclusionFilter);
            }
            if (ports != null)
            {
                AvailableSerialPorts = new ObservableCollection <SerialPortViewModel>(ports.OrderBy(p => p).Select(p => new SerialPortViewModel(p)));
            }
            else
            {
                AvailableSerialPorts = new ObservableCollection <SerialPortViewModel>();
            }
            if (disabledPorts == null)
            {
                DisabledSerialPorts = new ObservableCollection <string>();
            }
            else
            {
                DisabledSerialPorts = new ObservableCollection <string>(disabledPorts);
            }
            if (checkPortAvailability)
            {
                var portsInUse = INTV.Shared.Model.Device.SerialPortConnection.PortsInUse;
                foreach (var portInUse in portsInUse.Where(p => (InclusionFilter == null) || InclusionFilter(Connection.CreatePseudoConnection(p, ConnectionType.Serial))))
                {
                    DisabledSerialPorts.Add(portInUse);
                }
            }
            foreach (var disabledPort in DisabledSerialPorts.Where(p => (InclusionFilter == null) || InclusionFilter(Connection.CreatePseudoConnection(p, ConnectionType.Serial))).OrderBy(p => p).Reverse())
            {
                var viewModel = AvailableSerialPorts.FirstOrDefault(p => p.PortName == disabledPort);
                if (viewModel == null)
                {
                    viewModel = new SerialPortViewModel(disabledPort, false);
                }
                else
                {
                    viewModel.IsSelectable = false;
                    AvailableSerialPorts.Remove(viewModel);
                }
                if (AvailableSerialPorts.Count == 0)
                {
                    AvailableSerialPorts.Add(viewModel);
                }
                else
                {
                    AvailableSerialPorts.Insert(0, viewModel);
                }
            }
            _selectedSerialPort          = selectedSerialPort;
            _selectedSerialPortViewModel = AvailableSerialPorts.FirstOrDefault(p => p.PortName == _selectedSerialPort);
            DefaultBaudRate            = defaultBaudRate;
            _selectedBaudRate          = defaultBaudRate;
            _selectedBaudRateViewModel = BaudRates.FirstOrDefault(b => b.BaudRate == defaultBaudRate);
            INTV.Shared.Interop.DeviceManagement.DeviceChange.DeviceAdded   += DeviceAdded;
            INTV.Shared.Interop.DeviceManagement.DeviceChange.DeviceRemoved += DeviceRemoved;
        }