public void Run()
        {
            var stateMachine = new AssignmentStateMachine(new PhaseWaitingForConnection());
            CirceComConnection connection = null;

            Log.Info($"Connecting to mediator on {startupArguments.ComPortName}...");
            stateMachine.ExecuteIfInPhase<PhaseWaitingForConnection>(phase =>
            {
                connection = new CirceComConnection(startupArguments.ComPortName);
                connection.OperationReceived +=
                    (sender, eventArgs) => ConnectionOperationReceived(eventArgs, stateMachine);
                connection.Open();
                connection.Send(new LoginOperation());

                return new PhaseWaitingForLoginResponse();
            });

            Log.Info("Waiting for login response...");
            var readyForDeviceSetup = stateMachine.WaitForPhase<PhaseReadyForDeviceSetup>();
            Log.Info($"Mediator status in login response: {readyForDeviceSetup.MediatorStatus}.");

            if (!IsConfiguringMediator &&
                readyForDeviceSetup.MediatorStatus == KnownMediatorStatusCode.MediatorUnconfigured)
            {
                Log.Info("ERROR: Connected to unconfigured mediator. Please configure mediator first.");
                return;
            }

            Log.Info("Sending address assignment...");
            stateMachine.ExecuteIfInPhase<PhaseReadyForDeviceSetup>(phase1 =>
            {
                connection.Send(new DeviceSetupOperation(startupArguments.NewAddress)
                {
                    DestinationAddress = startupArguments.OldAddress,
                    Capabilities = startupArguments.Capabilities
                });

                return new PhaseWaitingForSetupResponse(startupArguments.NewAddress);
            });

            Log.Info("Waiting for response from new device...");
            var assignmentCompleted = stateMachine.WaitForPhase<PhaseAssignmentCompleted>();

            Log.Info(assignmentCompleted.MediatorStatus == KnownMediatorStatusCode.MediatorUnconfigured
                ? "ERROR: Failed to assign mediator address."
                : "Received response on new address.");

            Log.Info("Disconnecting...");
            connection.Send(new LogoutOperation());
        }
        private static CirceComConnection TryCreateOpenedConnection([NotNull] string portName,
            [CanBeNull] Action<CirceComConnection> attachHandlersCallback,
            [CanBeNull] Action<CirceComConnection> detachHandlersCallback)
        {
            CirceComConnection connection = null;
            Exception error;
            try
            {
                connection = new CirceComConnection(portName);

                attachHandlersCallback?.Invoke(connection);

                connection.Open();
                return connection;
            }
            catch (InvalidOperationException ex)
            {
                // This may happen when you unplug the serial port cable while writing to the port.
                // The exception indicates that the port has been closed, so writing fails.
                error = ex;
            }
            catch (UnauthorizedAccessException ex)
            {
                error = ex;
            }
            catch (SecurityException ex)
            {
                error = ex;
            }
            catch (IOException ex)
            {
                error = ex;
            }

            Log.Debug($"Failed to open port {portName}: {error.GetType()}: {error.Message}");
            if (connection != null)
            {
                detachHandlersCallback?.Invoke(connection);

                connection.Dispose();
            }

            return null;
        }