Example #1
0
        /// <summary>
        /// Cancel a real time data stream and clean up after it.
        /// </summary>
        /// <returns>True if the stream was canceled, False if subsribers remain.</returns>
        public bool CancelRTDStream(int instrumentID)
        {
            lock (_activeStreamsLock)
            {
                //TODO cancelrealtimedata on the client needs to be more specific than just the instrument
                //make sure there is a data stream for this instrument
                if (ActiveStreams.Collection.Any(x => x.Instrument.ID == instrumentID))
                {
                    var streamInfo = ActiveStreams.Collection.First(x => x.Instrument.ID == instrumentID);
                    var instrument = streamInfo.Instrument;

                    //if it's a continuous future we also need to cancel the actual contract
                    if (instrument.IsContinuousFuture)
                    {
                        var contractID = _continuousFuturesIDMap[instrumentID];
                        var contract   = ActiveStreams.Collection.First(x => x.Instrument.ID == contractID).Instrument;

                        //we must also clear the alias list
                        lock (_aliasLock)
                        {
                            _aliases[contractID].Remove(instrumentID);
                            if (_aliases[contractID].Count == 0)
                            {
                                _aliases.Remove(contractID);
                            }
                        }

                        //finally cancel the contract's stream
                        CancelRTDStream(contractID);
                    }

                    //log the request
                    Log(LogLevel.Info,
                        string.Format("RTD Cancelation request: {0} from {1}",
                                      instrument.Symbol,
                                      instrument.Datasource.Name));

                    lock (_subscriberCountLock)
                    {
                        StreamSubscribersCount[streamInfo]--;
                        if (StreamSubscribersCount[streamInfo] == 0)
                        {
                            //there are no clients subscribed to this stream anymore
                            //cancel it and remove it from all the places
                            StreamSubscribersCount.Remove(streamInfo);

                            ActiveStreams.TryRemove(streamInfo);

                            if (!instrument.IsContinuousFuture)
                            {
                                DataSources[streamInfo.Datasource].CancelRealTimeData(streamInfo.RequestID);
                            }
                            return(true);
                        }
                    }
                }

                return(false);
            }
        }
Example #2
0
 public void Reset()
 {
     shotIterator.Reset();
     Bullets.Clear();
     ActiveStreams.Clear();
     Score       = 0;
     TotalExited = 0;
 }
Example #3
0
        /// <summary>
        /// Updates streams.
        /// </summary>
        private void UpdateStreams(LevelTime levelTime, Vector2 playerCenter)
        {
            // TODO Refactor this old mess

            if (ActiveStreams.Count == 0)
            {
                return;
            }

            for (int i = 0; i < ActiveStreams.Count; i++)
            {
                var stream = ActiveStreams[i];

                stream.TimeSinceLastShot += (float)levelTime.ElapsedMs;
                if (stream.TimeSinceLastShot >= StreamShot.FireFrequency)
                {
                    var currStreamTime = levelTime.SongPosition - stream.Time;
                    var currSpeed      = stream.Speed0 + (currStreamTime * ((stream.Speed1 - stream.Speed0) / stream.Duration));
                    var currAngle      = stream.Angle0 + (currStreamTime * ((stream.Angle1 - stream.Angle0) / stream.Duration));
                    var currOffset     = stream.Offset0 + (currStreamTime * ((stream.Offset1 - stream.Offset0) / stream.Duration));

                    bool lastShot = levelTime.SongPosition + StreamShot.FireFrequency > stream.Time + stream.Duration;

                    foreach (int enemy in stream.Enemies)
                    {
                        var spawner = Util.GetSpawnerFromShotIndex(spawners, enemy);
                        var wave    = new Wave()
                        {
                            BulletType     = stream.BulletType,
                            Amount         = stream.Amount0,
                            Speed          = currSpeed,
                            Angle          = currAngle,
                            Offset         = currOffset,
                            Aim            = stream.Aim,
                            HomingLifespan = stream.HomingLifespan,
                        };
                        Bullets.AddRange(wave.Create(spawner.Center, spawner.Angle,
                                                     playerCenter, level.Info.Colors));

                        if (lastShot && Config.GameSettings.DrawParticles)
                        {
                            particles.CreateShotSpawnParticles(spawner, stream.Color);
                        }
                    }

                    if (lastShot)
                    {
                        ActiveStreams.RemoveAt(i);
                        i--;
                    }
                    else
                    {
                        stream.TimeSinceLastShot -= StreamShot.FireFrequency;
                    }
                }
            }
        }
Example #4
0
        public void ConfigureChannels()
        {
            if (Running)
            {
                throw new HekaDAQException("Cannot configure channels while hardware is running.");
            }

            Device.ConfigureChannels(ActiveStreams.Cast <HekaDAQStream>());
        }
Example #5
0
        public Http2Session(SecureSocket sessionSocket, ConnectionEnd end, 
                            bool usePriorities, bool useFlowControl,
                            IDictionary<string, object> handshakeResult = null)
        {
            _ourEnd = end;
            _usePriorities = usePriorities;
            _useFlowControl = useFlowControl;
            _handshakeHeaders = new Dictionary<string, string>(16);
            ApplyHandshakeResults(handshakeResult);

            if (_ourEnd == ConnectionEnd.Client)
            {
                _remoteEnd = ConnectionEnd.Server;
                _lastId = -1; // Streams opened by client are odd
            }
            else
            {
                _remoteEnd = ConnectionEnd.Client;
                _lastId = 0; // Streams opened by server are even
            }

            _goAwayReceived = false;
            _settingsManager = new SettingsManager();
            _comprProc = new CompressionProcessor(_ourEnd);
            _sessionSocket = sessionSocket;

            _frameReader = new FrameReader(_sessionSocket);

            ActiveStreams = new ActiveStreams();

            _writeQueue = new WriteQueue(_sessionSocket, ActiveStreams, _usePriorities);

            if (_sessionSocket != null && sessionSocket.SecureProtocol == SecureProtocol.None)
            {
                OurMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
                RemoteMaxConcurrentStreams = int.Parse(_handshakeHeaders[":max_concurrent_streams"]);
                InitialWindowSize = int.Parse(_handshakeHeaders[":initial_window_size"]);
            }
            else
            {
                OurMaxConcurrentStreams = 100; //Spec recommends value 100 by default
                RemoteMaxConcurrentStreams = 100;
                InitialWindowSize = 2000000;
            }
            _flowControlManager = new FlowControlManager(this);

            if (!_useFlowControl)
            {
                _flowControlManager.Options = (byte) FlowControlOptions.DontUseFlowControl;
            }

            SessionWindowSize = 0;
            _toBeContinuedHeaders = new HeadersList();
        }
        public FlowControlManager(Http2Session flowControlledSession)
        {
            SessionInitialWindowSize = Constants.DefaultFlowControlCredit;
            StreamsInitialWindowSize = Constants.DefaultFlowControlCredit;

            _flowControlledSession = flowControlledSession;
            _streamCollection = _flowControlledSession.ActiveStreams;

            Options = Constants.InitialFlowControlOptionsValue;

            IsSessionBlocked = false;
        }
        public FlowControlManager(Http2Session flowControlledSession)
        {
            SessionInitialWindowSize = Constants.DefaultFlowControlCredit;
            StreamsInitialWindowSize = Constants.DefaultFlowControlCredit;

            _flowControlledSession = flowControlledSession;
            _streamCollection      = _flowControlledSession.ActiveStreams;

            Options = Constants.InitialFlowControlOptionsValue;

            IsSessionBlocked = false;
        }
Example #8
0
 public WriteQueue(SecureSocket socket, ActiveStreams streams, bool isPriorityTurnedOn)
 {
     IsPriorityTurnedOn = isPriorityTurnedOn;
     _streams = streams;
     if (isPriorityTurnedOn)
     {
         _messageQueue = new PriorityQueue();
     }
     else
     {
         _messageQueue = new QueueWrapper();
     }
     _socket = socket;
     _disposed = false;
 }
Example #9
0
        /// <summary>
        /// Cancel a real time data stream and clean up after it.
        /// </summary>
        /// <returns>True if the stream was canceled, False if subsribers remain.</returns>
        public bool CancelRTDStream(int instrumentID, BarSize frequency)
        {
            lock (_activeStreamsLock)
            {
                //make sure there is a data stream for this instrument
                if (ActiveStreams.Collection.Any(x => x.Instrument.ID == instrumentID && x.Frequency == frequency))
                {
                    var streamInfo = ActiveStreams.Collection.First(x => x.Instrument.ID == instrumentID && x.Frequency == frequency);
                    var instrument = streamInfo.Instrument;

                    //if it's a continuous future we also need to cancel the actual contract
                    if (instrument.IsContinuousFuture)
                    {
                        CancelContinuousFutureRTD(instrumentID, frequency, instrument);
                    }

                    //log the request
                    Log(LogLevel.Info,
                        string.Format("RTD Cancelation request: {0} from {1}",
                                      instrument.Symbol,
                                      instrument.Datasource.Name));

                    lock (_subscriberCountLock)
                    {
                        StreamSubscribersCount[streamInfo]--;
                        if (StreamSubscribersCount[streamInfo] == 0)
                        {
                            //there are no clients subscribed to this stream anymore
                            //cancel it and remove it from all the places
                            StreamSubscribersCount.Remove(streamInfo);

                            ActiveStreams.TryRemove(streamInfo);

                            if (!instrument.IsContinuousFuture)
                            {
                                DataSources[streamInfo.Datasource].CancelRealTimeData(streamInfo.RequestID);
                            }
                            return(true);
                        }
                    }
                }

                return(false);
            }
        }
        public FlowControlManager(Http2Session flowControlledSession)
        {
            if (flowControlledSession == null)
                throw new ArgumentNullException("flowControlledSession is null");

            //06
            //When a HTTP/2.0 connection is first established, new streams are
            //created with an initial flow control window size of 65535 bytes.  The
            //connection flow control window is 65535 bytes.
            SessionInitialWindowSize = Constants.InitialFlowControlWindowSize;
            StreamsInitialWindowSize = Constants.InitialFlowControlWindowSize;

            _flowControlledSession = flowControlledSession;
            _streamCollection = _flowControlledSession.ActiveStreams;

            Options = Constants.InitialFlowControlOptionsValue;
            _wasFlowControlSet = false;
            IsSessionBlocked = false;
        }
Example #11
0
 protected override void OnDisposing()
 {
     if (this.NotificationSource != null)
     {
         this.NotificationSource.Ending -= this.OnEnding;
         this.NotificationSource.Ended  -= this.OnEnded;
     }
     try
     {
         this.Provider.FreeStream(this.PlaylistItem, this.ChannelHandle);
     }
     finally
     {
         if (!ActiveStreams.TryRemove(this.PlaylistItem))
         {
             //TODO: Warn.
         }
     }
     this.ChannelHandle = 0;
 }
Example #12
0
        /// <summary>
        /// Sends a real time data request to the correct data source, logs it, and updates subscriber counts
        /// </summary>
        /// <param name="request"></param>
        private void ForwardRTDRequest(RealTimeDataRequest request)
        {
            //send the request to the correct data source
            int reqID;

            try
            {
                reqID = DataSources[request.Instrument.Datasource.Name].RequestRealTimeData(request);
            }
            catch (Exception ex)
            {
                Log(LogLevel.Error, "Error requesting real time data: " + ex.Message);
                return;
            }

            //log the request
            Log(LogLevel.Info,
                string.Format("RTD Request: {0} from {1} @ {2} ID:{3}",
                              request.Instrument.Symbol,
                              request.Instrument.Datasource.Name,
                              Enum.GetName(typeof(BarSize), request.Frequency),
                              reqID));

            //add the request to the active streams, though it's not necessarily active yet
            var streamInfo = new RealTimeStreamInfo(
                request.Instrument,
                reqID,
                request.Instrument.Datasource.Name,
                request.Frequency,
                request.RTHOnly);

            lock (_activeStreamsLock)
            {
                ActiveStreams.TryAdd(streamInfo);
            }

            lock (_subscriberCountLock)
            {
                StreamSubscribersCount.Add(streamInfo, 1);
            }
        }
Example #13
0
        public WriteQueue(Stream stream, ActiveStreams streams, bool isPriorityTurnedOn)
        {
            if (stream == null)
                throw new ArgumentNullException("io stream is null");

            if (streams == null)
                throw new ArgumentNullException("streams collection is null");

            //Priorities are turned on for debugging
            IsPriorityTurnedOn = isPriorityTurnedOn;
            _streams = streams;

            if (IsPriorityTurnedOn)
            {
                _messageQueue = new PriorityQueue();
            }
            else
            {
                _messageQueue = new QueueWrapper();
            }
            _stream = stream;
            _disposed = false;
        }
        public Http2Session(Stream stream, ConnectionEnd end, 
                            bool usePriorities, bool useFlowControl, bool isSecure,
                            CancellationToken cancel,
                            int initialWindowSize = Constants.InitialFlowControlWindowSize,
                            int maxConcurrentStreams = Constants.DefaultMaxConcurrentStreams)
        {

            if (stream == null)
                throw new ArgumentNullException("stream is null");

            if (cancel == null)
                throw new ArgumentNullException("cancellation token is null");

            if (maxConcurrentStreams <= 0)
                throw new ArgumentOutOfRangeException("maxConcurrentStreams cant be less or equal then 0");

            if (initialWindowSize <= 0 && useFlowControl)
                throw new ArgumentOutOfRangeException("initialWindowSize cant be less or equal then 0");

            _ourEnd = end;
            _usePriorities = usePriorities;
            _useFlowControl = useFlowControl;
            _isSecure = isSecure;

            _cancelSessionToken = cancel;

            if (_ourEnd == ConnectionEnd.Client)
            {
                _remoteEnd = ConnectionEnd.Server;
                _lastId = -1; // Streams opened by client are odd

                //if we got unsecure connection then server will respond with id == 1. We cant initiate 
                //new stream with id == 1.
                if (!(stream is SslStream))
                {
                    _lastId = 3;
                }
            }
            else
            {
                _remoteEnd = ConnectionEnd.Client;
                _lastId = 0; // Streams opened by server are even
            }

            _goAwayReceived = false;
            _comprProc = new CompressionProcessor(_ourEnd);
            _ioStream = stream;

            _frameReader = new FrameReader(_ioStream);

            ActiveStreams = new ActiveStreams();

            _writeQueue = new WriteQueue(_ioStream, ActiveStreams, _comprProc, _usePriorities);
            OurMaxConcurrentStreams = maxConcurrentStreams;
            RemoteMaxConcurrentStreams = maxConcurrentStreams;
            InitialWindowSize = initialWindowSize;

            _flowControlManager = new FlowControlManager(this);

            if (!_useFlowControl)
            {
                _flowControlManager.Options = (byte) FlowControlOptions.DontUseFlowControl;
            }

            SessionWindowSize = 0;
            _headersSequences = new HeadersSequenceList();
            _promisedResources = new Dictionary<int, string>();
        }
Example #15
0
        /// <summary>
        /// This method is called when the continuous futures broker returns the results of a request for the "front"
        /// contract of a continuous futures instrument.
        /// </summary>
        private void _cfBroker_FoundFrontContract(object sender, FoundFrontContractEventArgs e)
        {
            RealTimeDataRequest request;

            if (!e.Instrument.ID.HasValue)
            {
                Log(LogLevel.Error, "CF Broker returned front contract with no ID");
                return;
            }

            Log(LogLevel.Info, string.Format("Front contract received on request ID {0}, is: {1}", e.ID, e.Instrument.Symbol));

            //grab the original request
            lock (_cfRequestLock)
            {
                request = _pendingCFRealTimeRequests[e.ID];
                _pendingCFRealTimeRequests.Remove(e.ID);
            }

            //add the contract to the ID map
            if (request.Instrument.ID.HasValue &&
                !_continuousFuturesIDMap.ContainsKey(request.Instrument.ID.Value))
            {
                _continuousFuturesIDMap.Add(request.Instrument.ID.Value, e.Instrument.ID.Value);
            }

            //add the alias
            lock (_aliasLock)
            {
                int contractID = e.Instrument.ID.Value;
                if (!_aliases.ContainsKey(contractID))
                {
                    _aliases.Add(contractID, new List <int>());
                }

                if (request.Instrument.ID.HasValue)
                {
                    _aliases[contractID].Add(request.Instrument.ID.Value);
                }
            }

            //need to check if there's already a stream of the contract....
            bool streamExists;

            lock (_activeStreamsLock)
            {
                streamExists = ActiveStreams.Collection.Any(x => x.Instrument.ID == e.Instrument.ID);
            }

            if (streamExists)
            {
                //all we need to do in this case is increment the number of subscribers to this stream
                IncrementSubscriberCount(e.Instrument);

                //log it
                Log(LogLevel.Info,
                    string.Format("RTD Request for CF {0} @ {1} {2}, filled by existing stream of symbol {3}.",
                                  request.Instrument.Symbol,
                                  request.Instrument.Datasource.Name,
                                  Enum.GetName(typeof(BarSize), request.Frequency),
                                  e.Instrument.Symbol));
            }
            else //no current stream of this contract, add it
            {
                //make the request
                var contractRequest = (RealTimeDataRequest)request.Clone();
                contractRequest.Instrument = e.Instrument; //we take the original request, and substitute the CF for the front contract
                ForwardRTDRequest(contractRequest);

                //add the request to the active streams, though it's not necessarily active yet
                var streamInfo = new RealTimeStreamInfo(
                    request.Instrument,
                    -1,
                    request.Instrument.Datasource.Name,
                    request.Frequency,
                    request.RTHOnly);

                lock (_activeStreamsLock)
                {
                    ActiveStreams.TryAdd(streamInfo);
                }

                lock (_subscriberCountLock)
                {
                    StreamSubscribersCount.Add(streamInfo, 1);
                }

                //log it
                Log(LogLevel.Info,
                    string.Format("RTD Request for CF: {0} from {1} @ {2}, filled by contract: {3}",
                                  request.Instrument.Symbol,
                                  request.Instrument.Datasource.Name,
                                  Enum.GetName(typeof(BarSize), request.Frequency),
                                  e.Instrument.Symbol));
            }
        }