Exemple #1
0
        public async Task <IObservable <RealTimeMeasurement> > SubscribeHome(Guid homeId, CancellationToken cancellationToken)
        {
            CheckObjectNotDisposed();

            int  subscriptionId;
            bool shouldInitialize;
            HomeRealTimeMeasurementObservable observable;

            lock (_homeObservables)
            {
                shouldInitialize = !_homeObservables.Any();

                if (_homeObservables.TryGetValue(homeId, out var collection))
                {
                    throw new InvalidOperationException($"Home '{homeId}' is already subscribed. ");
                }

                subscriptionId = Interlocked.Increment(ref _streamId);
                _homeObservables.Add(
                    homeId,
                    collection = new HomeStreamObserverCollection {
                    Observable = new HomeRealTimeMeasurementObservable(this, homeId, subscriptionId)
                });

                observable = collection.Observable;
            }

            try
            {
                if (shouldInitialize)
                {
                    await Initialize(cancellationToken);

                    StartListening();
                    _streamRestartTimer.Change(StreamReSubscriptionCheckPeriodMs, 5000);
                }

                await SubscribeStream(homeId, subscriptionId, cancellationToken);

                if (!observable.IsInitialized)
                {
                    throw new InvalidOperationException($"real-time measurement subscription initialization failed{(observable.ErrorMessage == null ? null : $": {observable.ErrorMessage}")}");
                }
            }
            catch
            {
                lock (_homeObservables)
                    _homeObservables.Remove(homeId);

                throw;
            }

            return(observable);
        }
Exemple #2
0
 private void UnsubscribeObserver(HomeStreamObserverCollection collection, IObserver <RealTimeMeasurement> observer)
 {
     lock (_homeObservables)
         collection.Observers.Remove(observer);
 }