Ejemplo n.º 1
0
        /// <summary>
        ///     Establish a link with an instrument
        ///     Handles retries for failed connections
        /// </summary>
        /// <param name="retryAttempts"></param>
        /// <returns></returns>
        public async Task Connect(int retryAttempts = MaxConnectionAttempts)
        {
            var connectionAttempts = 0;

            CancellationTokenSource = new CancellationTokenSource();
            var ct = CancellationTokenSource.Token;

            var result = Task.Run(async() =>
            {
                while (!IsConnected)
                {
                    connectionAttempts++;
                    Log.Info($"[{CommPort.Name}] Connecting to Instrument... Attempt {connectionAttempts} of {MaxConnectionAttempts}");

                    try
                    {
                        if (!CommPort.IsOpen())
                        {
                            await CommPort.Open();
                        }

                        await ConnectToInstrument();
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex.Message);
                    }

                    if (!IsConnected)
                    {
                        if (connectionAttempts < retryAttempts)
                        {
                            Thread.Sleep(ConnectionRetryDelayMs);
                        }
                        else
                        {
                            throw new Exception($"{CommPort.Name} Could not connect to instrument.");
                        }
                    }
                }
            }, ct);

            try
            {
                await result;
            }
            catch (AggregateException e)
            {
                foreach (var v in e.InnerExceptions)
                {
                    Log.Warn(e.Message + " " + v.Message);
                }
            }
            finally
            {
                CancellationTokenSource.Dispose();
            }
        }