Ejemplo n.º 1
0
 private void ForwardOrDelay(ByteString payload)
 {
     if (InboundThrottleMode is Blackhole)
     {
         // Do nothing
     }
     else
     {
         if (!ThrottledMessages.Any())
         {
             var tokens    = payload.Length;
             var res       = InboundThrottleMode.TryConsumeTokens(MonotonicClock.GetNanos(), tokens);
             var newBucket = res.Item1;
             var success   = res.Item2;
             if (success)
             {
                 InboundThrottleMode = newBucket;
                 UpstreamListener.Notify(new InboundPayload(payload));
             }
             else
             {
                 ThrottledMessages.Enqueue(payload);
                 ScheduleDequeue(InboundThrottleMode.TimeToAvailable(MonotonicClock.GetNanos(), tokens));
             }
         }
         else
         {
             ThrottledMessages.Enqueue(payload);
         }
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Create a new TaskClient instance to send data to connections (tcp) or to a remote host (udp)
        /// </summary>
        /// <param name="remoteEndPoint">(Default) remote endpoint to connect or send data to</param>
        /// <param name="protocol">TCP or UDP protocol for client socket supported</param>
        public Client(IPEndPoint remoteEndPoint, ProtocolType protocol, ThrottleMode mode = ThrottleMode.NoThrottle)
        {
            if (protocol == ProtocolType.Tcp)
            {
                this.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            else if (protocol == ProtocolType.Udp)
            {
                this.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            }
            else
            {
                throw new Exception("Only TCP and UDP protocol allowed");
            }

            this.RemoteEndPoint  = remoteEndPoint;
            this._disconnectLock = new Object();
            this.buffer          = new byte[8192];

            this.Download     = new Throttle(); // 100 kbsp
            this.Upload       = new Throttle();
            this.ThrottleMode = mode;

            this.OnClientConnected    = (s, e) => { };
            this.OnClientDisconnected = (s, e) => { };
            this.OnClientDataReceived = (s, e) => { };
        }
Ejemplo n.º 3
0
 public Throttle(int cost, TimeSpan per, int maximumBurst, Func <T, int> costCalculation, ThrottleMode mode)
 {
     _cost            = cost;
     _per             = per;
     _maximumBurst    = maximumBurst;
     _costCalculation = costCalculation;
     _mode            = mode;
 }
Ejemplo n.º 4
0
        private bool Throttle(ThrottleTransportAdapter.Direction direction, ThrottleMode mode)
        {
            var rootBAddress = new Address("akka", "systemB", "localhost", RootB.Address.Port.Value);
            var transport    =
                Sys.AsInstanceOf <ExtendedActorSystem>().Provider.AsInstanceOf <RemoteActorRefProvider>().Transport;
            var task = transport.ManagementCommand(new SetThrottle(rootBAddress, direction, mode));

            task.Wait(TimeSpan.FromSeconds(3));
            return(task.Result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// TBD
        /// </summary>
        /// <param name="cost">TBD</param>
        /// <param name="per">TBD</param>
        /// <param name="maximumBurst">TBD</param>
        /// <param name="costCalculation">TBD</param>
        /// <param name="mode">TBD</param>
        public Throttle(int cost, TimeSpan per, int maximumBurst, Func <T, int> costCalculation, ThrottleMode mode)
        {
            _maximumBurst    = maximumBurst;
            _costCalculation = costCalculation;
            _mode            = mode;

            // There is some loss of precision here because of rounding, but this only happens if nanosBetweenTokens is very
            // small which is usually at rates where that precision is highly unlikely anyway as the overhead of this stage
            // is likely higher than the required accuracy interval.
            _ticksBetweenTokens = per.Ticks / cost;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create a new VirtualClient instance by Activator.CreateInstance
        /// </summary>
        /// <param name="client"><see cref="System.Net.Sockets.Socket"/> of VirtualClient</param>
        /// <param name="assignedMemory">Assigned memory for overlapped IO events</param>
        /// <param name="id">Client ID</param>
        public VirtualClient(Socket client, byte[] assignedMemory, int id, ThrottleMode mode = AsyncTCPLib.ThrottleMode.NoThrottle)
        {
            this.Socket = client;
            this.buffer = assignedMemory;
            this.Id     = id;

            this._disconnectLock = new Object();
            this.IsConnected     = true;
            this.RemoteEndPoint  = (IPEndPoint)this.Socket.RemoteEndPoint;

            this.Download     = new Throttle(); // 100 kbsp
            this.Upload       = new Throttle();
            this.ThrottleMode = mode;

            this.OnClientDisconnected = (s, e) => { };
            this.OnClientDataReceived = (s, e) => { };
        }
Ejemplo n.º 7
0
    void Update()
    {
        Throttle  = Input.GetAxisRaw(ThrottleCommand) * (InvertThrottle ? -1 : 1);
        Yaw       = Input.GetAxisRaw(YawCommand) * (InvertYaw ? -1 : 1);
        Pitch     = Input.GetAxisRaw(PitchCommand) * (InvertPitch ? -1 : 1);
        Roll      = Input.GetAxisRaw(RollCommand) * (InvertRoll ? -1 : 1);
        Triggered = Input.GetAxisRaw(RightTriggerCommand) > 0;

        if ((Input.GetAxisRaw(ThrottleModeCommand) > 0) && !ThrottleModePressed)
        {
            switch (CurrentThrottleMode)
            {
            case ThrottleMode.None:
                CurrentThrottleMode = ThrottleMode.LockHeight; break;

            case ThrottleMode.LockHeight:
                CurrentThrottleMode = ThrottleMode.None; break;
            }
            ThrottleModePressed = true;
        }
        ThrottleModePressed = (Input.GetAxisRaw(ThrottleModeCommand) == 0) && (ThrottleModePressed);
    }
Ejemplo n.º 8
0
 /// <summary>
 /// Creates a new SetThrottle message.
 /// </summary>
 /// <param name="address">The address of the throttle.</param>
 /// <param name="direction">The direction of the throttle.</param>
 /// <param name="mode">The mode of the throttle.</param>
 public SetThrottle(Address address, ThrottleTransportAdapter.Direction direction, ThrottleMode mode)
 {
     _address   = address;
     _direction = direction;
     _mode      = mode;
 }
Ejemplo n.º 9
0
        private void InitializeFSM()
        {
            When(ThrottlerState.WaitExposedHandle, @event =>
            {
                if (@event.FsmEvent is ThrottlerManager.Handle && @event.StateData is Uninitialized)
                {
                    // register to downstream layer and wait for origin
                    OriginalHandle.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self));
                    return
                    (GoTo(ThrottlerState.WaitOrigin)
                     .Using(
                         new ExposedHandle(
                             @event.FsmEvent.AsInstanceOf <ThrottlerManager.Handle>().ThrottlerHandle)));
                }
                return(null);
            });

            When(ThrottlerState.WaitOrigin, @event =>
            {
                if (@event.FsmEvent is InboundPayload && @event.StateData is ExposedHandle)
                {
                    var b = @event.FsmEvent.AsInstanceOf <InboundPayload>().Payload;
                    ThrottledMessages.Enqueue(b);
                    var origin = PeekOrigin(b);
                    if (origin != null)
                    {
                        Manager.Tell(new ThrottlerManager.Checkin(origin, @event.StateData.AsInstanceOf <ExposedHandle>().Handle));
                        return(GoTo(ThrottlerState.WaitMode));
                    }
                    return(Stay());
                }
                return(null);
            });

            When(ThrottlerState.WaitMode, @event =>
            {
                if (@event.FsmEvent is InboundPayload)
                {
                    var b = @event.FsmEvent.AsInstanceOf <InboundPayload>().Payload;
                    ThrottledMessages.Enqueue(b);
                    return(Stay());
                }

                if (@event.FsmEvent is ThrottleMode && @event.StateData is ExposedHandle)
                {
                    var mode            = @event.FsmEvent.AsInstanceOf <ThrottleMode>();
                    var exposedHandle   = @event.StateData.AsInstanceOf <ExposedHandle>().Handle;
                    InboundThrottleMode = mode;
                    try
                    {
                        if (mode is Blackhole)
                        {
                            ThrottledMessages = new Queue <ByteString>();
                            exposedHandle.Disassociate();
                            return(Stop());
                        }
                        else
                        {
                            AssociationHandler.Notify(new InboundAssociation(exposedHandle));
                            var self = Self;
                            exposedHandle.ReadHandlerSource.Task.ContinueWith(
                                r => new ThrottlerManager.Listener(r.Result),
                                TaskContinuationOptions.ExecuteSynchronously)
                            .PipeTo(self);
                            return(GoTo(ThrottlerState.WaitUpstreamListener));
                        }
                    }
                    finally
                    {
                        Sender.Tell(SetThrottleAck.Instance);
                    }
                }

                return(null);
            });

            When(ThrottlerState.WaitUpstreamListener, @event =>
            {
                if (@event.FsmEvent is InboundPayload)
                {
                    var b = @event.FsmEvent.AsInstanceOf <InboundPayload>();
                    ThrottledMessages.Enqueue(b.Payload);
                    return(Stay());
                }

                if (@event.FsmEvent is ThrottlerManager.Listener)
                {
                    UpstreamListener = @event.FsmEvent.AsInstanceOf <ThrottlerManager.Listener>().HandleEventListener;
                    Self.Tell(new Dequeue());
                    return(GoTo(ThrottlerState.Throttling));
                }

                return(null);
            });

            When(ThrottlerState.WaitModeAndUpstreamListener, @event =>
            {
                if (@event.FsmEvent is ThrottlerManager.ListenerAndMode)
                {
                    var listenerAndMode = @event.FsmEvent.AsInstanceOf <ThrottlerManager.ListenerAndMode>();
                    UpstreamListener    = listenerAndMode.HandleEventListener;
                    InboundThrottleMode = listenerAndMode.Mode;
                    Self.Tell(new Dequeue());
                    return(GoTo(ThrottlerState.Throttling));
                }

                if (@event.FsmEvent is InboundPayload)
                {
                    var b = @event.FsmEvent.AsInstanceOf <InboundPayload>();
                    ThrottledMessages.Enqueue(b.Payload);
                    return(Stay());
                }

                return(null);
            });

            When(ThrottlerState.Throttling, @event =>
            {
                if (@event.FsmEvent is ThrottleMode)
                {
                    var mode            = @event.FsmEvent.AsInstanceOf <ThrottleMode>();
                    InboundThrottleMode = mode;
                    if (mode is Blackhole)
                    {
                        ThrottledMessages = new Queue <ByteString>();
                    }
                    CancelTimer(DequeueTimerName);
                    if (ThrottledMessages.Any())
                    {
                        ScheduleDequeue(InboundThrottleMode.TimeToAvailable(MonotonicClock.GetNanos(), ThrottledMessages.Peek().Length));
                    }
                    Sender.Tell(SetThrottleAck.Instance);
                    return(Stay());
                }

                if (@event.FsmEvent is InboundPayload)
                {
                    ForwardOrDelay(@event.FsmEvent.AsInstanceOf <InboundPayload>().Payload);
                    return(Stay());
                }

                if (@event.FsmEvent is Dequeue)
                {
                    if (ThrottledMessages.Any())
                    {
                        var payload = ThrottledMessages.Dequeue();
                        UpstreamListener.Notify(new InboundPayload(payload));
                        InboundThrottleMode = InboundThrottleMode.TryConsumeTokens(MonotonicClock.GetNanos(),
                                                                                   payload.Length).Item1;
                        if (ThrottledMessages.Any())
                        {
                            ScheduleDequeue(InboundThrottleMode.TimeToAvailable(MonotonicClock.GetNanos(), ThrottledMessages.Peek().Length));
                        }
                    }
                    return(Stay());
                }

                return(null);
            });

            WhenUnhandled(@event =>
            {
                // we should always set the throttling mode
                if (@event.FsmEvent is ThrottleMode)
                {
                    InboundThrottleMode = @event.FsmEvent.AsInstanceOf <ThrottleMode>();
                    Sender.Tell(SetThrottleAck.Instance);
                    return(Stay());
                }

                if (@event.FsmEvent is Disassociated)
                {
                    return(Stop()); // not notifying the upstream handler is intentional: we are relying on heartbeating
                }

                if (@event.FsmEvent is FailWith)
                {
                    var reason = @event.FsmEvent.AsInstanceOf <FailWith>().FailReason;
                    if (UpstreamListener != null)
                    {
                        UpstreamListener.Notify(new Disassociated(reason));
                    }
                    return(Stop());
                }

                return(null);
            });

            if (Inbound)
            {
                StartWith(ThrottlerState.WaitExposedHandle, Uninitialized.Instance);
            }
            else
            {
                OriginalHandle.ReadHandlerSource.SetResult(new ActorHandleEventListener(Self));
                StartWith(ThrottlerState.WaitModeAndUpstreamListener, Uninitialized.Instance);
            }
        }
Ejemplo n.º 10
0
        private void throttleModeChanged(ThrottleMode newMode, bool active, bool setTarget = true)
        {
            accelCtrl.skipDerivative = true;
            speedCtrl.skipDerivative = true;

            if (!active)
            {
                accelCtrl.Clear();
                speedCtrl.Clear();
            }
            else
            {
                switch (newMode)
                {
                    case ThrottleMode.Speed:
                        if (setTarget)
                            speedCtrl.SetPoint = vessel.srfSpeed;
                        targetSpeed = speedCtrl.SetPoint;
                        break;

                    case ThrottleMode.Autoland:
                        if (setTarget)
                            speedCtrl.SetPoint = getAutoLandSpeed();
                        targetSpeed = speedCtrl.SetPoint;
                        break;
                    case ThrottleMode.Acceleration:
                        if (setTarget)
                            accelCtrl.SetPoint = vesselData.acceleration;
                        targetSpeed = accelCtrl.SetPoint;
                        break;
                }
            }
            ThrtActive = active;
            CurrentThrottleMode = newMode;
        }
 public void SetThrottle(bool active, bool setTarget, ThrottleMode mode, double target)
 {
     if (setTarget)
     {
         switch (mode)
         {
             case ThrottleMode.Direct:
                 currentThrottlePct = Utils.Clamp(target / 100, 0, 1);
                 Vessel.ctrlState.mainThrottle = (float)currentThrottlePct;
                 if (ReferenceEquals(Vessel, FlightGlobals.ActiveVessel))
                     FlightInputHandler.state.mainThrottle = (float)currentThrottlePct;
                 break;
             case ThrottleMode.Acceleration:
                 target /= Utils.speedUnitTransform(units, Vessel.speedOfSound);
                 AsstList.Acceleration.GetAsst(this).UpdateSetpoint(target, true, vesModule.vesselData.acceleration);
                 break;
             case ThrottleMode.Speed:
                 target /= Utils.speedUnitTransform(units, Vessel.speedOfSound);
                 AsstList.Speed.GetAsst(this).UpdateSetpoint(target, true, Vessel.srfSpeed);
                 break;
         }
     }
     throttleModeChanged(mode, active, !setTarget);
 }
        private void throttleModeChanged(ThrottleMode newMode, bool active, bool setTarget = true)
        {
            AsstList.Acceleration.GetAsst(this).skipDerivative = true;
            AsstList.Speed.GetAsst(this).skipDerivative = true;

            if (!active)
            {
                AsstList.Acceleration.GetAsst(this).Clear();
                AsstList.Speed.GetAsst(this).Clear();
            }
            else
            {
                bPause = false;
                switch (newMode)
                {
                    case ThrottleMode.Speed:
                        if (setTarget)
                            AsstList.Speed.GetAsst(this).UpdateSetpoint(Vessel.srfSpeed);
                        targetSpeed = (AsstList.Speed.GetAsst(this).target_setpoint * Utils.speedUnitTransform(units, Vessel.speedOfSound)).ToString("0.00");
                        break;
                    case ThrottleMode.Acceleration:
                        if (setTarget)
                            AsstList.Acceleration.GetAsst(this).UpdateSetpoint(vesModule.vesselData.acceleration);
                        targetSpeed = (AsstList.Acceleration.GetAsst(this).target_setpoint * Utils.speedUnitTransform(units, Vessel.speedOfSound)).ToString("0.00");
                        break;
                    case ThrottleMode.Direct:
                        if (setTarget)
                            currentThrottlePct = Vessel.ctrlState.mainThrottle;
                        targetSpeed = (currentThrottlePct * 100).ToString("0.00");
                        break;
                }
            }
            ThrtActive = active;
            CurrentThrottleMode = newMode;
        }
Ejemplo n.º 13
0
 public void SetThrottle(bool active, bool setTarget, ThrottleMode mode, double target)
 {
     if (active && setTarget)
     {
         switch (mode)
         {
             case ThrottleMode.Direct:
                 currentThrottlePct = Utils.Clamp(target / 100, 0, 1);
                 vesModule.vesselRef.ctrlState.mainThrottle = (float)currentThrottlePct;
                 if (ReferenceEquals(vesModule.vesselRef, FlightGlobals.ActiveVessel))
                     FlightInputHandler.state.mainThrottle = (float)currentThrottlePct;
                 break;
             case ThrottleMode.Acceleration:
                 AsstList.Acceleration.GetAsst(this).SetPoint = vesModule.vesselData.acceleration;
                 AsstList.Acceleration.GetAsst(this).BumplessSetPoint = target;
                 break;
             case ThrottleMode.Speed:
                 AsstList.Speed.GetAsst(this).SetPoint = vesModule.vesselRef.srfSpeed;
                 AsstList.Speed.GetAsst(this).BumplessSetPoint = target;
                 break;
         }
     }
     throttleModeChanged(mode, active, !setTarget);
 }