protected override async Task <bool> DeactivateCore()
        {
            AcquisitionActionResult result = null;

            if (this.ProviderState >= ProviderState.StartingRecord)
            {
                result = await this.StopRecord(new StopRecordParameter()
                {
                    SequenceId = this.SequenceId, TriggerMode = AcquisitionTriggerMode.Unknown
                }).ConfigureAwait(false);
            }

            if ((result == null || result.IsSuccessful) && (this.ProviderState >= ProviderState.InitializingRecord))
            {
                result = await this.UninitializeRecord(new UninitializeRecordParameter()
                {
                    SequenceId = this.SequenceId
                }).ConfigureAwait(false);
            }

            return(await base.DeactivateCore().ConfigureAwait(false) && (result == null || result.IsSuccessful));
        }
        protected override async Task <bool> DeactivateCore()
        {
            AcquisitionActionResult result = null;

            if (this.ProviderState >= ProviderState.Starting)
            {
                result = await this.Stop(new StopAcquisitionParameter()).ConfigureAwait(false);
            }

            if ((result == null || result.IsSuccessful) && (this.ProviderState >= ProviderState.Initializing))
            {
                result = await this.Uninitialize(new UninitializeAcquisitionParameter()).ConfigureAwait(false);
            }

            // stop all observers no matter the current AcquisitionStep since the agent is becoming inactive
            foreach (var observer in _observers)
            {
                observer.Item1.Dispose();
            }
            _observers.Clear();

            return(await base.DeactivateCore().ConfigureAwait(false) && (result == null || result.IsSuccessful));
        }
        protected async override Task <AcquisitionActionResult> StartRecordCore(StartRecordParameter parameters, AcquisitionActionResult result)
        {
            result = await base.StartRecordCore(parameters, result).ConfigureAwait(false);

            if (!result.IsSuccessful)
            {
                return(result);
            }

            _roadEventSequence = 0;

            // we stop recording at UninitializeReocrd, not StopRecord
            // to allow operators to add comments before they validate the acquisition
            this.RegisterObserver(
                this.DataSource.Subscribe(
                    data =>
            {
                if (data.IsJournalised)
                {
                    AddEventJournalEntry(CreateEjxJournalEntry(data));
                }
            }), AcquisitionStep.UninitializeRecord);

            return(result);
        }
Пример #4
0
        protected async override Task <AcquisitionActionResult> StartRecordCore(StartRecordParameter parameters, AcquisitionActionResult result)
        {
            result = await base.StartRecordCore(parameters, result).ConfigureAwait(false);

            if (!result.IsSuccessful)
            {
                return(result);
            }

            this.RegisterObserver(
                this.DataSource
                .Where((data, i) => i % this.LogGap == 0)
                .Subscribe(data => LogGpsData(data)), AcquisitionStep.StopRecord);

            return(result);
        }
Пример #5
0
        protected override async Task <AcquisitionActionResult> InitializeRecordCore(InitializeRecordParameter parameters, AcquisitionActionResult result)
        {
            result = await base.InitializeRecordCore(parameters, result).ConfigureAwait(false);

            if (this.UseOnlyTrustworthyData)
            {
                try { await this.DataSource.Where(data => data.GpsStatus != GpsStatus.Initializing).Take(1).ToTask(this.Provider.CurrentStateTransitionCancellationToken).ConfigureAwait(false); }
                catch (TaskCanceledException ex)
                {
                    result.IsSuccessful = false;
                    result.Exception    = ex;
                    return(result);
                }
            }

            // create tracer & start tracing
            _tracer = new GpxTracer(this.EventJournalFileExtension, this.Append);

            var deviceType = this.CurrentData == null ? GpsDeviceType.Unknown : this.CurrentData.RawData.DeviceType;

            _tracer.StartTracing(parameters.SequenceId, this.JournalAbsoluteSavePath, deviceType);

            this.Provider.SequenceId             = parameters.SequenceId;
            this.Provider.SaveFolderAbsolutePath = this.JournalAbsoluteSavePath;

            return(result);
        }
 protected virtual Task <AcquisitionActionResult> InitializeRecordCore(InitializeRecordParameter parameters, AcquisitionActionResult result)
 {
     return(Task.FromResult(result));
 }
        protected override async Task <AcquisitionActionResult> StartRecordCore(StartRecordParameter parameters, AcquisitionActionResult result)
        {
            result = await base.StartRecordCore(parameters, result).ConfigureAwait(false);

            if (!result.IsSuccessful)
            {
                return(result);
            }

            switch (this.AcquisitionMode)
            {
            case DistanceAcquisitionMode.Time:
                this.RegisterObserver(
                    this.DataSource
                    .Sample(this.SavingInterval)
                    .Buffer(this.SavingInterval, 1)
                    .Select(buffer => buffer.Count > 0 ? buffer[0] : new SpeedData {
                    CurrentSpeed = -1, SpeedSource = SpeedActiveMode.None
                })
                    .Subscribe(data => AddEventJournalEntry(CreateEjxJournalEntry(data))), AcquisitionStep.StopRecord);
                break;

            case DistanceAcquisitionMode.Distance:
                this.RegisterObserver(this.DataSource
                                      .Where(data => data.CurrentDistance != null)
                                      .DistinctUntilChanged()           // only for new values
                                      .Subscribe(data => AddEventJournalEntry(CreateEjxJournalEntry(data))), AcquisitionStep.StopRecord);
                break;

            default:
                throw new NotSupportedException(string.Format("Acquisition mode '{0}' is not supported.", this.AcquisitionMode));
            }

            return(result);
        }
 protected virtual Task OnAfterStateTransition(AcquisitionStep step, AcquisitionParameter parameters, AcquisitionActionResult result)
 {
     Log.Debug().Message("After transition to AcquisitionStep '{0}'.", step).WithAgent(this.Id).Write(); return(Task.FromResult(0));
 }
        protected override async Task <AcquisitionActionResult> UninitializeCore(UninitializeAcquisitionParameter parameters, AcquisitionActionResult result)
        {
            await StopTransferring().ConfigureAwait(false);

            return(await base.UninitializeCore(parameters, result).ConfigureAwait(false));
        }
        protected override async Task <AcquisitionActionResult> InitializeRecordCore(InitializeRecordParameter parameters, AcquisitionActionResult result)
        {
            result = await base.InitializeRecordCore(parameters, result).ConfigureAwait(false);
            await StopTransferring().ConfigureAwait(false);

            return(result);
        }
Пример #11
0
        protected override Task <AcquisitionActionResult> InitializeRecordCore(InitializeRecordParameter parameters, AcquisitionActionResult result)
        {
            this.ItineraryLogRelativeFilePath = this.SequenceId + ".iti";

            try { File.Delete(Path.Combine(this.JournalAbsoluteSavePath, this.ItineraryLogRelativeFilePath)); }
            catch { }

            return(base.InitializeRecordCore(parameters, result));
        }
        private async Task <AcquisitionActionResult> InternalUninitializeRecord(UninitializeRecordParameter parameters, AcquisitionActionResult result)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            result = await UninitializeRecordCore(parameters, result).ConfigureAwait(false);

            var currentTransfer = this.Provider.CurrentFileTransfer;

            if (currentTransfer != null)
            {
                await currentTransfer.ConfigureAwait(false);
            }

            CloseEventJournal();

            GenerateFileJournal(parameters);

            return(result);
        }
        private async Task <AcquisitionActionResult> InternalStopRecord(StopRecordParameter parameters, AcquisitionActionResult result)
        {
            // delayed stop
            if (this.DeviceDistanceFromStopTriggerPoint > 0 && this.IsDependencyOperational <IDistanceAgent>())
            {
                var distanceData = await AgentBroker.Instance.TryExecuteOnFirst <IDistanceAgent, DistanceData>(a => a.CurrentData).GetValueOrDefault().ConfigureAwait(false);

                await AgentBroker.Instance.ObserveAny <IDistanceAgent, DistanceData>("DataSource").Where(data => data.AbsoluteDistance >= distanceData.AbsoluteDistance + this.DeviceDistanceFromStopTriggerPoint).Take(1).ToTask().ConfigureAwait(false);
            }

            result = await StopRecordCore(parameters, result).ConfigureAwait(false);

            return(result);
        }
        private async Task <AcquisitionActionResult> InternalStartRecord(StartRecordParameter parameters, AcquisitionActionResult result)
        {
            // delayed start
            if (this.DeviceDistanceFromStartTriggerPoint > 0 && this.IsDependencyOperational <IDistanceAgent>())
            {
                await AgentBroker.Instance.ObserveAny <IDistanceAgent, DistanceData>("DataSource").Where(data => data.AbsoluteDistance >= this.DeviceDistanceFromStartTriggerPoint).Take(1).ToTask().ConfigureAwait(false);
            }

            result = await StartRecordCore(parameters, result).ConfigureAwait(false);

            return(result);
        }
        private async Task <AcquisitionActionResult> InternalInitializeRecord(InitializeRecordParameter parameters, AcquisitionActionResult result)
        {
            if (string.IsNullOrEmpty(parameters.DefaultRootPath))
            {
                throw new InvalidOperationException("RootPath is mandatory.");
            }
            if (string.IsNullOrEmpty(this.AgentFolderPath))
            {
                throw new InvalidOperationException("AgentFolderPath is mandatory.");
            }
            if (string.IsNullOrEmpty(this.AgentUniversalName))
            {
                throw new InvalidOperationException("AgentUniversalName is mandatory.");
            }
            if (string.IsNullOrEmpty(this.EventJournalFileExtension))
            {
                throw new InvalidOperationException("EventJournalFileExtension is mandatory.");
            }
            if (string.IsNullOrEmpty(this.FileJournalFileExtension))
            {
                throw new InvalidOperationException("FileJournalFileExtension is mandatory.");
            }
            if (string.IsNullOrEmpty(parameters.SequenceId))
            {
                throw new InvalidOperationException("SequenceId is mandatory.");
            }

            _fileJournalEntries.Clear();

            this.JournalRootPath = string.IsNullOrEmpty(this.RootPath) ? parameters.DefaultRootPath : this.RootPath;

            this.SequenceId          = parameters.SequenceId;
            this.Provider.SequenceId = parameters.SequenceId;

            this.JournalRelativeSavePath = this.AgentFolderPath;
            this.JournalAbsoluteSavePath = Path.Combine(this.JournalRootPath, parameters.SequenceId, this.JournalRelativeSavePath);

            int    rootLength          = 1 + Path.Combine(this.JournalRootPath, parameters.SequenceId).Length;
            string filename            = string.IsNullOrWhiteSpace(this.Configuration.Agent.Journalisation.CharacterizationFileName) ? this.AgentUniversalName : string.Format("{0}.{1}", this.Configuration.Agent.Journalisation.CharacterizationFileName, this.AgentUniversalName);
            string fjxCompleteFilePath = Path.Combine(this.JournalAbsoluteSavePath, parameters.SequenceId + "." + filename + this.FileJournalFileExtension);

            this.FileJournalRelativePath = fjxCompleteFilePath.Substring(rootLength);

            string ejxCompleteFilePath = InitializeEventJournal(this.JournalAbsoluteSavePath, parameters);

            this.EventJournalRelativePath = string.IsNullOrEmpty(ejxCompleteFilePath) ? string.Empty : ejxCompleteFilePath.Substring(rootLength);

            string cjxCompleteFilePath = InitializeConfigurationJournal(this.JournalAbsoluteSavePath, parameters);

            this.ConfigurationJournalRelativePath = string.IsNullOrEmpty(cjxCompleteFilePath) ? string.Empty : cjxCompleteFilePath.Substring(rootLength);

            result.ConfigurationJournalRelativePath = this.ConfigurationJournalRelativePath;
            result.EventJournalRelativePath         = this.EventJournalRelativePath;
            result.FileJournalRelativePath          = this.FileJournalRelativePath;

            this.Provider.SaveFolderAbsolutePath = this.JournalAbsoluteSavePath;

            result = await InitializeRecordCore(parameters, result).ConfigureAwait(false);

            return(result);
        }
 protected virtual Task <AcquisitionActionResult> StopCore(StopAcquisitionParameter parameters, AcquisitionActionResult result)
 {
     return(Task.FromResult(result));
 }
 protected virtual Task <AcquisitionActionResult> UninitializeCore(UninitializeAcquisitionParameter parameters, AcquisitionActionResult result)
 {
     return(Task.FromResult(result));
 }
        protected override async Task <AcquisitionActionResult> InitializeCore(InitializeAcquisitionParameter parameters, AcquisitionActionResult result)
        {
            result = await base.InitializeCore(parameters, result).ConfigureAwait(false);

            // get initial value of IsTransferring
            await Task.WhenAll(AgentBroker.Instance.TryExecuteOnAll <IFileTransferAgent, bool>(a => a.IsTransferring).GetValueOrDefault())
            .ContinueWith(t => _isTransferringSubject.OnNext(t.Result.Any(_ => _)), TaskContinuationOptions.OnlyOnRanToCompletion)
            .ConfigureAwait(false);

            return(result);
        }
        protected async Task <AcquisitionActionResult> MakeStateTransition <TParameter>(AcquisitionStep step, Func <Func <Task <bool> >, Func <Task>, Task> moduleAction, TParameter parameters, Func <TParameter, AcquisitionActionResult, Task <AcquisitionActionResult> > agentAction)
            where TParameter : AcquisitionParameter
        {
            if (moduleAction == null)
            {
                throw new ArgumentNullException("moduleAction");
            }
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }
            if (agentAction == null)
            {
                throw new ArgumentNullException("agentAction");
            }

            var result = new AcquisitionActionResult(parameters.SequenceId, step, this.Id, this.DisplayData.Name)
            {
                MachineName = Environment.MachineName
            };

            // action to accomplish the state transition on the agent
            // if it succeeds, the module action will then be executed
            Func <Task <bool> > before =
                async() =>
            {
                try
                {
                    await OnBeforeStateTransition(step, parameters, result).ConfigureAwait(false);

                    result = await agentAction(parameters, result).ConfigureAwait(false);

                    // Il faut désabonner les observers avant de faire la transition d'état,
                    // car le code qui réagit aux événements assume que le provider n'est pas dans l'état de fin d'observation.
                    // Les observers doivent également devenir inactifs, même si la transition d'état a planté.
                    for (int i = _observers.Count - 1; i >= 0; i--)
                    {
                        if (_observers[i].Item2 == step)
                        {
                            _observers[i].Item1.Dispose();
                            _observers.RemoveAt(i);
                        }
                    }

                    return(result.IsSuccessful);
                }
                catch
                {
                    this.OperationalState |= OperationalAgentStates.InternalAgentError;
                    throw;
                }
            };

            try
            {
                if (this.OperationalState != OperationalAgentStates.None)
                {
                    throw new InvalidOperationException(string.Format("{0} -> agent is not operational.", this.DisplayData.Name));
                }

                await moduleAction(before, null).ConfigureAwait(false);
            }
            catch (InvalidStateTransitionException ex)
            {
                Log.Error().Exception(ex).WithAgent(this.Id).Write();
                result.Exception    = ex;
                result.IsSuccessful = false;
            }
            catch (Exception ex)
            {
                if (this.ProviderState == ProviderState.Failed)
                {
                    this.OperationalState |= OperationalAgentStates.ModuleError;
                }

                result.Exception    = ex;
                result.IsSuccessful = false;
            }

            result.ProviderState = this.ProviderState;
            await OnAfterStateTransition(step, parameters, result).ConfigureAwait(false);

            if (result.IsSuccessful)
            {
                Log.Debug().Message("Transition to AcquisitionStep '{0}' successful.", step).WithAgent(this.Id).Write();
            }
            else
            {
                var logBuilder = Log.Warn().Message("Transition to AcquisitionStep '{0}' failed.", step);

                if (result.Exception != null)
                {
                    logBuilder = logBuilder.Exception(result.Exception);
                }

                logBuilder.WithAgent(this.Id).Write();
            }

            return(result);
        }
        protected override async Task <AcquisitionActionResult> StartCore(StartAcquisitionParameter parameters, AcquisitionActionResult result)
        {
            result = await base.StartCore(parameters, result).ConfigureAwait(false);

            this.RegisterObserver(
                AgentBroker.Instance.ObserveAll <IFileTransferAgent, FileTransferData>("FileTransferDataSource")
                .SelectMany(t => t.Item2)
                .Subscribe(_fileTransferSubject),
                AcquisitionStep.Stop);

            var acquisitionManagerState = await AgentBroker.Instance.TryExecuteOnFirst <IAcquisitionManagerAgent, ProviderState>(a => a.ProviderState).GetValueOrDefault().ConfigureAwait(false);

#pragma warning disable 4014
            if (acquisitionManagerState <= ProviderState.Started)
            {
                StartTransferring();
            }
#pragma warning restore 4014

            // start transferring when AcquisitionManager is not recording (ProviderState <= Started)
            this.RegisterObserver(
                AgentBroker.Instance.ObserveAny <IAcquisitionManagerAgent, ProviderState>("ProviderStateDataSource")
                .Where(state => state <= ProviderState.Started && this.OperationalState == OperationalAgentStates.None)
                .Subscribe(_ => StartTransferring()),
                AcquisitionStep.Stop);

            // for each new FileTransferAgent, start transferring if applicable
            this.RegisterObserver(
                AgentBroker.Instance.ObserveAll <IFileTransferAgent, ProviderState>("ProviderStateDataSource")
                .SelectMany(t => t.Item2.Select(state => Tuple.Create(t.Item1, state)))
                .Where(t => t.Item2 == ProviderState.Started)
                .Subscribe(
                    t =>
            {
                if (this.IsTransferring)
                {
                    AgentBroker.Instance.TryExecuteOnOne <IFileTransferAgent>(t.Item1.AgentId, a => a.StartTransferring());
                }
            }),
                AcquisitionStep.Stop);

            return(result);
        }
        protected override async Task <AcquisitionActionResult> StartCore(StartAcquisitionParameter parameters, AcquisitionActionResult result)
        {
            result = await base.StartCore(parameters, result).ConfigureAwait(false);

            if (!result.IsSuccessful)
            {
                return(result);
            }

            this.RegisterObserver(AgentBroker.Instance.ObserveAny <ILocalisationAgent, LocalisationData>("DataSource").Subscribe(data => _localisationSubject.OnNext(data)));
            this.RegisterObserver(AgentBroker.Instance.ObserveAny <IDistanceAgent, DistanceData>("DataSource").Subscribe(data => _distanceSubject.OnNext(data)));

            return(result);
        }
Пример #22
0
        protected override async Task <AcquisitionActionResult> UninitializeRecordCore(UninitializeRecordParameter parameters, AcquisitionActionResult result)
        {
            if (_tracer != null)
            {
                lock (_tracer)
                {
                    _tracer.StopTracing();
                    _tracer.Dispose();
                }
            }

            return(await base.UninitializeRecordCore(parameters, result).ConfigureAwait(false));
        }