Example #1
0
        /// <summary>
        /// Executes an instrument read settings operation.
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("ALARM EVENT DOWNLOAD");

            InstrumentAlarmEventsDownloadEvent instrumentAlarmEventsDownloadEvent = new InstrumentAlarmEventsDownloadEvent(this);

            instrumentAlarmEventsDownloadEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
            instrumentAlarmEventsDownloadEvent.DockingStation   = Master.Instance.ControllerWrapper.GetDockingStation();

            // Retrieve the events.
            using (InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                // Open the serial port connection needed to communicate with the instrument.
                instrumentController.Initialize();

                Log.Debug("ALARM EVENTS: Downloading");

                instrumentAlarmEventsDownloadEvent.AlarmEvents = instrumentController.GetAlarmEvents();

                Log.Debug("ALARM EVENTS: " + instrumentAlarmEventsDownloadEvent.AlarmEvents.Length + " events downloaded.");
            } // end-using

            // Need to fill in the instrument serial number on our own.
            // At the same time, format up details for each alarm event.
            foreach (AlarmEvent alarmEvent in instrumentAlarmEventsDownloadEvent.AlarmEvents)
            {
                alarmEvent.InstrumentSerialNumber = instrumentAlarmEventsDownloadEvent.DockedInstrument.SerialNumber;
            }

            Log.TimingEnd("ALARM EVENT DOWNLOAD", stopwatch);

            return(instrumentAlarmEventsDownloadEvent);  // Return the populated event.
        }
Example #2
0
        /// <summary>
        /// Determines current charging status of the docked instrument.
        /// </summary>
        /// <returns>
        /// The returned DockingStationEvent is always null.
        /// </returns>
        /// <exception cref="InstrumentNotDockedException">
        /// If instrument is undocked
        /// </exception>
        /// <exception cref="InstrumentPingFailedException">
        /// Failure to turn on the instrument.
        /// </exception>
        public DockingStationEvent Execute()
        {
            if (Configuration.DockingStation.Type != DeviceType.MX4 && Configuration.DockingStation.Type != DeviceType.MX6)
            {
                return(null);
            }

            if (!Controller.IsDocked())
            {
                throw new InstrumentNotDockedException();
            }

            Log.Debug(this.Name + ".Execute");

            using (InstrumentController instrumentController = SwitchService.CreateInstrumentController())
            {
                // Turn on the instrument, the ask it for it's charging status
                try
                {
                    // Note that we deliberately do NOT use batch mode.  We're only trying to read a very
                    // few number of messages.  So it's not worth the effort and time it takes to negotiate
                    // faster baud rate and establish a batched connection to the instrument. It's much
                    // quicker to just read the few registers at the slow baud rate.
                    instrumentController.Initialize(InstrumentController.Mode.NoLid /* lid not necessary */);

                    InstrumentSerialNumber = instrumentController.GetSerialNumber();

                    BatteryCode = instrumentController.GetBatteryCode();

                    InstrumentChargePhase = instrumentController.GetChargePhase();

                    Log.Warning(string.Format("{0}: BatteryCode={1}, ChargePhase=\"{2}\"",
                                              this.Name, BatteryCode, InstrumentChargePhase));
                }
                catch (InstrumentPingFailedException ipef)                   // Couldn't turn on the instrument?
                {
                    // will get a ping failure if undocked.
                    if (!Controller.IsDocked())
                    {
                        throw new InstrumentNotDockedException();
                    }

                    Log.Error(this.Name, ipef);
                    throw;
                }
                catch (CommunicationAbortedException cae)                   // thrown by driver when instrument is undocked.
                {
                    Log.Error(this.Name, cae);
                    throw new InstrumentNotDockedException();
                }
            }
            return(null);
        }
Example #3
0
        private void DownloadDatalog()
        {
            using ( InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                instrumentController.Initialize( InstrumentController.Mode.Batch );

                DateTime startTime = DateTime.UtcNow;

                bool corruptDatalogDetected = false;

                _returnEvent.InstrumentSessions = instrumentController.GetDatalog( out corruptDatalogDetected );

                TimeSpan elapsedTime = DateTime.UtcNow - startTime;

                int corruptSessionsCount = 0;

                // For each corrupted session, upload an error to inet.
                foreach ( DatalogSession session in _returnEvent.InstrumentSessions )
                {
                    if ( session.CorruptionException != null )
                    {
                        corruptSessionsCount++;
                        // DO NOT CHANGE THE FOLLOWING STRING. THE SERVER IS
                        // PARSING UPLOADED ERRORS LOOKING FOR THIS PHRASING....
                        string msg = string.Format( "Corrupt hygiene encountered! - Session {0}\n{1}", Log.DateTimeToString( session.Session ), session.CorruptionException );
                        Log.Warning( msg );
                        _returnEvent.Errors.Add( new DockingStationError( msg, DockingStationErrorLevel.Warning, _returnEvent.DockedInstrument.SerialNumber) );
                    }
                }

                Log.Debug( string.Format( "DATALOG: {0} sessions successful downloaded from instrument.", _returnEvent.InstrumentSessions.Count ) );
                Log.Debug( string.Format( "DATALOG: {0} of those are partial sessions due to corruption.", corruptSessionsCount ) );
                Log.Debug( string.Format( "DATALOG: Corruption detected: " + corruptDatalogDetected.ToString() ) );

                // If we have zero sessions marked as corrupted, but corruptHygieneDetected is set to true,
                // that means the datalog was so corrupted, that a session object couldn't even be created out of it.
                // Upload a error.
                if ( corruptSessionsCount == 0 && corruptDatalogDetected == true )
                {
                    Log.Debug( "DATALOG: One or more sessions were completely lost due to corruption. " );
                    // DO NOT CHANGE THE FOLLOWING STRING. THE SERVER IS
                    // PARSING UPLOADED ERRORS LOOKING FOR THIS PHRASING....
                    _returnEvent.Errors.Add( new DockingStationError( "Corrupt hygiene encountered!", DockingStationErrorLevel.Warning, _returnEvent.DockedInstrument.SerialNumber ) );
                }

                Log.Debug( string.Format( "DATALOG: Overall time to download & process: {0}.", elapsedTime ) );

            }  // end-using
        }
Example #4
0
        /// <summary>
        /// Executes an instrument discovery operation.
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            InstrumentNothingEvent instrumentNothingEvent;

            using (InstrumentController instrumentController = SwitchService.CreateInstrumentController())
            {
                // Create the return event.
                instrumentNothingEvent = new InstrumentNothingEvent(this);

                // Open the serial port connection needed to communicate with the instrument.
                instrumentController.Initialize();
            }

            return(instrumentNothingEvent);
        }
        /// <summary>
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("ALARM EVENT CLEAR");

            InstrumentAlarmEventsClearEvent clearEvent = new InstrumentAlarmEventsClearEvent(this);

            clearEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
            clearEvent.DockingStation   = Master.Instance.ControllerWrapper.GetDockingStation();

            using (InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                instrumentController.Initialize();
                Log.Debug("Clearing alarm events");
                instrumentController.ClearAlarmEvents();
            } // end-using

            Log.TimingEnd("ALARM EVENT CLEAR", stopwatch);

            return(clearEvent);
        }
Example #6
0
        /// <summary>
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("DATALOG CLEAR");

            InstrumentDatalogClearEvent datalogClearEvent = new InstrumentDatalogClearEvent(this);

            datalogClearEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
            datalogClearEvent.DockingStation   = Master.Instance.ControllerWrapper.GetDockingStation();

            using (InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                instrumentController.Initialize();
                datalogClearEvent.SessionsCleared = 0;
                datalogClearEvent.SessionsCleared = instrumentController.ClearDatalog();
            } // end-using

            Log.TimingEnd("DATALOG CLEAR", stopwatch);

            return(datalogClearEvent);
        }
        /// <summary>
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("MANUAL OPERATIONS CLEAR");

            InstrumentManualOperationsClearEvent clearEvent = new InstrumentManualOperationsClearEvent(this);

            clearEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
            clearEvent.DockingStation   = Master.Instance.ControllerWrapper.GetDockingStation();

            using (InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                instrumentController.Initialize();

                instrumentController.ClearManualGasOperations();

                Log.Debug(Name + ": Manual gas operations cleared.");
            } // end-using

            Log.TimingEnd("MANUAL OPERATIONS CLEAR", stopwatch);

            return(clearEvent);
        }
Example #8
0
        /// <summary>
        /// Executes an instrument read settings operation.
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("MANUAL OPERATIONS DOWNLOAD");

            InstrumentManualOperationsDownloadEvent downloadEvent = new InstrumentManualOperationsDownloadEvent(this);

            downloadEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
            downloadEvent.DockingStation   = Master.Instance.ControllerWrapper.GetDockingStation();

            using (InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                instrumentController.Initialize(InstrumentController.Mode.Batch);

                Log.Debug("MANUAL GAS OPERATIONS: Downloading");

                // INS-3145 - Due to a bug in GBPro, a manual gas operation is sometimes logged
                // with an invalid sensor resolution (decimal places = 255).  When this happens,
                // the instrument driver will throw an ArgumentOutOfRangeException.  If we
                // catch one, we need to tell iNet.  We don't rethrow the exception, to prevent
                // the docking station from going "unavailable" and instead just treat it
                // as if the log was empty.  This allows the corrupt log to be cleared.
                try
                {
                    downloadEvent.GasResponses = new List <SensorGasResponse>(instrumentController.GetManualGasOperations());
                }
                catch (ArgumentOutOfRangeException aoore)
                {
                    Log.Error(aoore);
                    downloadEvent.Errors.Add(new DockingStationError("Corrupt manual gas operations log encountered.", DockingStationErrorLevel.Warning, downloadEvent.DockedInstrument.SerialNumber));
                }

                Log.Debug("MANUAL GAS OPERATIONS: " + downloadEvent.GasResponses.Count + " downloaded.");
            } // end-using

            Log.TimingEnd("MANUAL OPERATIONS DOWNLOAD", stopwatch);

            return(downloadEvent);  // Return the populated event.
        }
Example #9
0
        private InstrumentNothingEvent DiscoverInstrument()
        {
            // Create the return event.
            InstrumentNothingEvent instrumentNothingEvent = new InstrumentNothingEvent(this);

            InstrumentController instrumentController = SwitchService.CreateInstrumentController();

            try
            {
                // Open the serial port connection needed to communicate with the instrument.
                instrumentController.Initialize(InstrumentController.Mode.Batch);

                // MX4 is the default instrument controller created for MX4 docking stations.
                if (instrumentController is MX4)
                {
                    // VPRO instrument controller may need created instead depending on type of docked instrument.
                    if (instrumentController.GetInstrumentType() == DeviceType.VPRO)
                    {
                        // Clean up MX4 controller.
                        instrumentController.Dispose();

                        // Create and initialize VPRO controller.
                        instrumentController = new VPRO();
                        instrumentController.Initialize(InstrumentController.Mode.Batch);
                    }
                }

                // If we make it through InstrumentController.Initialize without throwing, then
                // we assume the instrument is now on, or at least it's IrDA is.
                InstrumentOff = false;

                Stopwatch sw = new Stopwatch();
                sw.Start();

                // TxRxRetries value is returned by modbuslibrary.dll. It continally increments the value and never resets it back to zero.
                // So, before reading data from the instrument, we get the current value. Farther below, when we're finished reading, we get
                // the value again, and subtract this starting value to determine how many retries occurred during this particular discovery.
                // Getting this starting value also lets us subtract out any of the retries occurring during initializing above.
                int startTxRxRetries = instrumentController.Driver.TxRxRetries;

                // Retrieve the docked instrument.
                instrumentNothingEvent.DockedInstrument = instrumentController.DiscoverDockedInstrument(true);

                // INS-8228 RHP v7.6,  Service accounts need to perform auto-upgrade on instruments even in error/fail state
                Master.Instance.SwitchService.IsInstrumentInSystemAlarm = instrumentController.IsInstrumentInSystemAlarm;

                sw.Stop();
                int    txRxCount          = instrumentController.Driver.TxRxCount;
                double txRxCountPerSecond = (double)txRxCount / (sw.ElapsedMilliseconds / 1000.0);
                int    txRxRetries        = instrumentController.Driver.TxRxRetries - startTxRxRetries;
                Log.Debug(string.Format("Modbus statistics:  stopwatch={0}ms, TxRx={1} ({2}/s), retries={3}",
                                        sw.ElapsedMilliseconds, txRxCount, txRxCountPerSecond.ToString("f0"), txRxRetries));
            }
            catch (InstrumentSystemAlarmException) // SGF  Nov-23-2009  DSW-355  (DS2 v7.6)
            {
                // If the user docked an instrument in system alarm, then just rethrow up to the service
                // that invoked this discovery and let it deal with it.
                throw;
            }
            catch (HardwareConfigurationException)
            {
                // If user failed to reconfigure the docking station hardware, then just rethrow up to the service
                // that invoked this discovery and let it deal with it.
                throw;
            }
            catch (Exception e)
            {
                Log.Error(this.GetType().ToString() + ".Execute.DiscoverDockedInstrument", e);

                // ********************************************************************
                // See INS-6671 and INS-6682 as to why the second discover was removed.
                // ********************************************************************

                throw;
            } // end-catch
            finally
            {
                instrumentController.Dispose();
            }

            return(instrumentNothingEvent);
        }
        /// <summary>
        /// Executes an instrument diagnostic operation.
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("INSTRUMENT DIAGNOSTICS");

            InstrumentDiagnosticEvent instrumentDiagnosticEvent = new InstrumentDiagnosticEvent(this);

            instrumentDiagnosticEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
            instrumentDiagnosticEvent.DockingStation   = Master.Instance.ControllerWrapper.GetDockingStation();
            // Open the serial port connection needed to communicate with the instrument.
            using (InstrumentController instrumentController = Master.Instance.SwitchService.InstrumentController)
            {
                instrumentController.Initialize(InstrumentController.Mode.Batch);

                // Cache the diagnostic start time and instrument serial numbers,
                // these will be used during each diagnostic object's instantiation.
                DateTime diagnosticTime = DateTime.UtcNow;
                string   instSn         = instrumentDiagnosticEvent.DockedInstrument.SerialNumber;

                // Download the "General diagnostics" from the instrument.
                // The diagnostics that are returned by the instrument will be different and based on the instrument's type.
                GeneralDiagnostic generalDiagnostic = new GeneralDiagnostic(instSn, diagnosticTime);

                generalDiagnostic.Items = instrumentController.GetGeneralDiagnosticProperties();

                foreach (GeneralDiagnosticProperty gdp in generalDiagnostic.Items)
                {
                    Log.Debug("GeneralDiagnosticProperty " + gdp.Name + "=" + gdp.Value);
                }

                instrumentDiagnosticEvent.Diagnostics.Add(generalDiagnostic);

                // Download instrument error log.

                ErrorDiagnostic[] errors = instrumentController.GetInstrumentErrors();

                List <CriticalError> criticalErrors = new List <CriticalError>();

                // we don't need to bother querying the database if there were no errors on
                // the instrument that need checked against the database.
                if (errors.Length > 0)
                {
                    // INS-4236, 9/10/2014 - only populate criticalErrors list for MX6 instruments.
                    // MX6 instruments due not have a "current error" register that can be read when it's
                    // docked to determine if it's currently in a error state.  But other instruments do.
                    // For those instruments that do have this register, we read the register during discovery
                    // and the docking station will go to "instrument error" state if it's no zero.
                    // Since we can't do that for MX6, the best we can do is read its error log containing
                    // historical errors.  For each error in the log, we compare to list of errors we
                    // have in our database that are considered "critical".  If we find a match,
                    // then we set a flag which will cause the docking station to go the "instrument error"
                    // state when this operation returns the event.

                    //INS-7715- Need to check if the DS belongs to the Service account, if so fetch all configured errors and compare with the instrument errors.
                    //If any matches with the errors, then set instrument marked as in critical error.
                    if ((instrumentDiagnosticEvent.DockedInstrument.Type == DeviceType.MX6) || Configuration.IsRepairAccount())
                    {
                        criticalErrors = criticalErrorsList;
                        //criticalErrors = new CriticalErrorDataAccess().FindAll();

                        Log.Debug(string.Format("{0} {1} critical errors loaded from database.",
                                                criticalErrors.Count, instrumentDiagnosticEvent.DockedInstrument.Type));
                    }
                }

                bool   foundCrticalErrorInInstrument = false;
                string criticalErroCodeIdentified    = string.Empty;    // INS-8446 RHP v7.6

                foreach (ErrorDiagnostic error in errors)
                {
                    // these values are needed so they can be uploaded to iNet
                    error.SerialNumber = instSn;
                    error.Time         = diagnosticTime;

                    instrumentDiagnosticEvent.Diagnostics.Add(error);

                    Log.Debug("InstrumentError " + error.Code + " on " + Log.DateTimeToString(error.ErrorTime));

                    // Errors that are logged in the instrument will be compared to the list of critical errors
                    // downloaded from iNet. If any error code matches then instrument marked as in critical error.
                    // This list will default to empty for non-MX6 instruments, so it will never find anything, on purpose.
                    // Exception to that it loads all critical errors for Service accounts for any instrument types - INS-7715.
                    if (criticalErrors.Exists(ce => ce.Code == error.Code))
                    {
                        foundCrticalErrorInInstrument = true;
                        criticalErroCodeIdentified    = error.Code.ToString();
                        Log.Warning(string.Format("CRITICAL ERROR {0} LOGGED BY INSTRUMENT ON {1}", error.Code, Log.DateTimeToString(error.ErrorTime)));
                    }
                }

                if (foundCrticalErrorInInstrument)
                {
                    //if critical errors found then errors will NOT be cleared from the instrument. Setting the "InstrumentInCriticalError"
                    //property to TRUE will make the docking station to set to "Instrument Error" state.
                    instrumentDiagnosticEvent.InstrumentInCriticalError = true;
                    // Setting the "InstrumentCriticalErrorCode" property to hold the Error Code will make the docking station
                    // display the Error Code on its LCD during "Instrument Error" state. INS-8446 RHP v7.6
                    instrumentDiagnosticEvent.InstrumentCriticalErrorCode = criticalErroCodeIdentified;
                }
                else
                {
                    //if no crtical error found then we will clear the errors from the instrument.
                    instrumentController.ClearInstrumentErrors();
                }
            } // end-using instrumentController

            Log.TimingEnd("INSTRUMENT DIAGNOSTICS", stopwatch);

            return(instrumentDiagnosticEvent);
        }
        /// <summary>
        /// Executes a turn off instrument operation.
        /// </summary>
        /// <returns>A InstrumentTurnOffEvent, which contains the TurnOffAction
        /// indicating what exactly the Execute() decided to do.
        /// </returns>
        /// <exception cref="InstrumentNotDockedException">If an instrument is not docked.</exception>
        public DockingStationEvent Execute()
        {
            string funcName = Name + ".Execute";

            Log.Debug(funcName + ", Reason=" + _reason);

            InstrumentTurnOffEvent _returnEvent = new InstrumentTurnOffEvent(this);

#if DEBUG
            // When debugging, don't turn off the GBPROs since they annoyingly take too long to turn back on.
            if (Configuration.DockingStation.Type == DeviceType.GBPRO)
            {
                _returnEvent.TurnOffAction = TurnOffAction.None;
                Log.Info(string.Format("{0}.Execute doing nothing due to DEBUG directive", Name));
                return(_returnEvent);
            }
#endif
            _returnEvent.TurnOffAction = GetTurnOffAction();

            if (_returnEvent.TurnOffAction == TurnOffAction.NotSupported)
            {
                Log.Warning(string.Format("{0}: Docked {1}'s cannot be turned off.", funcName, Configuration.DockingStation.Type));
                return(_returnEvent);
            }
            else if (_returnEvent.TurnOffAction == TurnOffAction.None)
            {
                Log.Warning(string.Format("{0}: Docked {1} should already be off.", funcName, Configuration.DockingStation.Type));
                return(_returnEvent);
            }
            else
            {
                if (!Controller.IsDocked())
                {
                    throw new InstrumentNotDockedException();
                }

                using (InstrumentController instrumentController = SwitchService.CreateInstrumentController())
                {
                    // Note that we specify NoPing.  This causes the instrument controller to *not* call the
                    // driver's connect method.
                    instrumentController.Initialize(InstrumentController.Mode.NoPing);
                    try
                    {
                        if (_returnEvent.TurnOffAction == TurnOffAction.Shutdown)
                        {
                            // Even the instruments which cannot shutdown will have this called
                            // so their sensors get turned off.
                            instrumentController.TurnOff();
                        }
                        else if (_returnEvent.TurnOffAction == TurnOffAction.TurnOffSensors)
                        {
                            if (instrumentController.GetOperatingMode() == OperatingMode.WarmingUp)
                            {
                                // MX6 instrument does not support going to Charging mode when it is currently WarmingUp.
                                // So we need to try again later after the instrument has transitioned to Running.
                                _returnEvent.TurnOffAction = TurnOffAction.Postponed;
                                Log.Debug(funcName + ", WAITING FOR WARM UP TO COMPLETE.  TURN OFF POSTPONED.");
                            }
                            else
                            {
                                // This should only need to be called for MX6 rechargeable instruments.
                                instrumentController.TurnOnSensors(false, false);
                            }
                        }
                    }
                    catch (CommunicationException ce)
                    {
                        Log.Debug(funcName + " caught CommunicationException: " + (Log.Level >= LogLevel.Trace ? ce.ToString() : ce.Message));
                        Log.Debug(funcName + " FAILED. Instrument might already be in OFF state.");
                    }
                }
            }

            return(_returnEvent);
        }
        /// <summary>
        /// Executes an instrument bump test operation.
        /// </summary>
        /// <returns>The completed event for this bump test.</returns>
        /// <exception cref="FailedBumpTestException">
        /// If anything extraordinary happened during the bump test.
        /// </exception>
        public DockingStationEvent Execute()
        {
            //Clear if any flags before initiating calibration once again
            Pump.IsBadPumpTubing = false;                                           // iNetDS
            Master.Instance.SwitchService.BadPumpTubingDetectedDuringCal  = false;  // iNetDS
            Master.Instance.SwitchService.BadPumpTubingDetectedDuringBump = false;  // iNetDS

            Stopwatch operationStopwatch = Log.TimingBegin("INSTRUMENT BUMP TEST"); // iNetDS

            _returnEvent = new InstrumentBumpTestEvent(this);
            _returnEvent.DockedInstrument = this.Instrument;       // TODO
            _returnEvent.DockingStation   = this.DockingStation;   // TODO
            //_detailsBuilder = new DetailsBuilder(EventDetails);    // _detailsBuilder = new DetailsBuilder(InstrumentHelper.EventDetails);    // IDS

            //Throw Exception if Instrument is undocked
            if (!Master.Instance.ControllerWrapper.IsDocked())
            {
                throw new InstrumentNotDockedException();
            }

            _returnEvent.Trigger = Trigger;
            _returnEvent.IsSensorFailureModeEnabled   = IsSensorFailureModeEnabled;   // DSW-1034 RHP Tango     TODO    IDS
            _returnEvent.IsSCSensorFailureModeEnabled = IsSCSensorFailureModeEnabled; // DSW-1068 RHP v9.5      TODO    IDS

            Log.Debug(string.Format("{0}.Execute {1}", Name, _returnEvent.DockedInstrument.SerialNumber));

            // Add the detail header.
            //_detailsBuilder.Add("", "DETAILS_BUMP_TEST_HEADER", string.Empty);  // IDS
            //_detailsBuilder.AddNewLine();                                       // IDS
            //_detailsBuilder.Add("    ", "DETAILS_INSTRUMENT_BUMPTHRESHOLD", this.BumpThreshold);    // IDS
            //_detailsBuilder.Add("    ", "DETAILS_INSTRUMENT_BUMPTIMEOUT", this.BumpTimeout);        // IDS

            _returnEvent.DockedInstrument.InstalledComponents
                = InstrumentController.SortSensorsByBumpOrder(_returnEvent.DockedInstrument.InstalledComponents);       //

            #region LogDebug
            Log.Debug("Candidate gases...");
            int pointCount = 0;
            foreach (GasEndPoint gasEndPoint in GasEndPoints)
            {
                string msg = "GasEndPoint #" + ++pointCount;
                Log.Debug(msg);
                Cylinder cyl = gasEndPoint.Cylinder;
                msg = "...Pos " + gasEndPoint.Position
                      + ", FactID=" + cyl.FactoryId
                      + ", Part=" + cyl.PartNumber
                      + ", Fresh=" + cyl.IsFreshAir
                      + ", ZeroAir=" + cyl.IsZeroAir
                      + ", Pressure=" + cyl.Pressure.ToString();
                if (gasEndPoint.Cylinder.Volume != DomainModelConstant.NullInt)
                {
                    msg += ", Vol=" + gasEndPoint.Cylinder.Volume;
                }

                Log.Debug(msg);
                msg = "......";
                foreach (GasConcentration gasCon in cyl.GasConcentrations)
                {
                    msg += "[" + gasCon.Type.Code + " ";
                    msg += (gasCon.Concentration == DomainModelConstant.NullDouble) ? "fresh" : gasCon.Concentration.ToString();
                    msg += "]";
                }
                Log.Debug(msg);
            }

            Log.Debug("Going to BUMP sensors in following ORDER...");
            int bumpOrder = 1;
            foreach (InstalledComponent ic in _returnEvent.DockedInstrument.InstalledComponents)
            {
                if (!(ic.Component is Sensor))
                {
                    continue; // It its not a sensor, ignore it.
                }
                Log.Debug("...#" + bumpOrder++ + ", Position " + ic.Position + ", UID=" + ic.Component.Uid + ", " + ic.Component.Type.Code);
            }
            #endregion


            // Open the serial port connection needed to communicate with the instrument.
            try
            {
                Stopwatch pingStopwatch = Log.TimingBegin("BUMP - PING");
                _instrumentController.Initialize();

                // Add a new line and section to the details.
                //_detailsBuilder.AddNewLine();

                Log.TimingEnd("BUMP - PING", pingStopwatch);

                // See if there are any already failed sensors - go to calibration if there are.
                // TODO move this section for IDS prior to initiating Bump Test, probably something similar to iNetDS Scheduler

                // Load the BumpTimout and BumpThreshold from the database needed to perform the bump.
                LoadBumpLimits();   // TODO update for IDS, LOAD THESE INTO INSTRUMETN ACTION BEFORE BUMP TEST

                BumpInstrument();

                // Need to determine the next time this instrument will be bumped.
                // Put this date into the event so it can be uploaded to iNet, and also
                // update the global next date that's held in the switch service.
                _returnEvent.NextUtcScheduledDate             = Master.Instance.SwitchService.NextUtcBumpDate
                                                              = Master.Instance.Scheduler.GetNextGasOperationDate(_returnEvent);
            }
            finally
            {
                _instrumentController.Dispose();
            }

            Log.TimingEnd("INSTRUMENT BUMP TEST", operationStopwatch);

            // IDS Updates Sensor's Bump Test Status on Cached Instrument - TODO TO BE HANDLED IN EVENT PROCESSOR FOR IDS.

            // Send back the results.
            return(_returnEvent);
        }
Example #13
0
        /// <summary>
        /// Executes an instrument settings update operation.
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
        {
            Stopwatch stopwatch = Log.TimingBegin("INSTRUMENT SETTINGS UPDATE");

            // Check for a docked instrument.
            if (!Master.Instance.ControllerWrapper.IsDocked())
            {
                throw new InstrumentNotDockedException();
            }

            string     serialNumber   = Master.Instance.SwitchService.Instrument.SerialNumber;
            DeviceType instrumentType = Master.Instance.SwitchService.Instrument.Type;

            if (serialNumber == string.Empty || instrumentType == DeviceType.Unknown)
            {
                throw new InstrumentNotDockedException();
            }

            // Create the return event.
            _instrumentSettingsUpdateEvent = new InstrumentSettingsUpdateEvent(this);

            // Retrieve the docking station's information.
            _instrumentSettingsUpdateEvent.DockingStation = Master.Instance.ControllerWrapper.GetDockingStation();
            _instrumentSettingsUpdateEvent.DockedTime     = Master.Instance.SwitchService.DockedTime;

            // Get the settings from the database to update the instrument with.
            Instrument settings = new InstrumentDataAccess().FindApplicableSettings(serialNumber, instrumentType);

            // If no instrument settings found, then there's nothing more we can do.
            // since we can't update the instrument's settings if we have no settings.
            if (settings == null)
            {
                string errMsg = string.Format("Unable to find instrument settings for S/N \"{0}\"", serialNumber);
                _instrumentSettingsUpdateEvent.Errors.Add(new DockingStationError(errMsg, DockingStationErrorLevel.Warning));
                return(_instrumentSettingsUpdateEvent);
            }

            // The settings loaded only apply to the discovered instrument.
            // We don't know if the settings loaded are the defaults are not
            // so we just set the type to what we searched for above.
            settings.Type = instrumentType;

            // Merge the loaded settings with our Instrument.

            using (_instCtrlr = SwitchService.CreateInstrumentController())
            {
                // Open the serial port connection needed to communicate with the instrument.
                _instCtrlr.Initialize(InstrumentController.Mode.Batch);

                // After an instrument settings read, we need to send a command to the instrument
                // to have it clear its base unit log.  Only SafeCore needs this command.
                _instCtrlr.ClearBaseUnits();

                // Update the docked instrument.
                _instrumentSettingsUpdateEvent.DockedInstrument = UpdateInstrument(settings, serialNumber);

                // Settings RefId will contain the ID of the settings used during the Update Event.  Otherwise, will be Nullid.
                // We place it into the event's Instrument in order to upload it to iNet.
                _instrumentSettingsUpdateEvent.DockedInstrument.RefId = settings.RefId;

                if (_instrumentSettingsUpdateEvent.DockingStation.ClearPeaksUponDocking)
                {
                    _instCtrlr.ClearInstrumentSensorPeaks(_instrumentSettingsUpdateEvent.DockedInstrument.InstalledComponents);
                }
            } // end-using

            Log.TimingEnd("INSTRUMENT SETTINGS UPDATE", stopwatch);

            return(_instrumentSettingsUpdateEvent);
        }
        /// <summary>
        /// IOperating implementation. Performs an instrument calibration operation.
        /// </summary>
        /// <returns>Docking station event</returns>
        public DockingStationEvent Execute()
    {
        //Clear if any flags before initiating calibration once again 
        Pump.IsBadPumpTubing = false;
        Master.Instance.SwitchService.BadPumpTubingDetectedDuringCal = false;
        Master.Instance.SwitchService.BadPumpTubingDetectedDuringBump = false;

        Stopwatch stopwatch = Log.TimingBegin("INSTRUMENT CALIBRATION");

        _returnEvent.DockedInstrument = (ISC.iNet.DS.DomainModel.Instrument)Master.Instance.SwitchService.Instrument.Clone();
        _returnEvent.DockingStation = Master.Instance.ControllerWrapper.GetDockingStation();

        Log.Debug( string.Format( "{0}.Execute {1}", Name, _returnEvent.DockedInstrument.SerialNumber ) );

        // Sort sensors by calibration order.
        _returnEvent.DockedInstrument.InstalledComponents = InstrumentController.SortSensorsByCalibrationOrder( _returnEvent.DockedInstrument.InstalledComponents );

        #region LogDebug
        Log.Debug( "Candidate gases..." );
        int pointCount = 0;
		foreach ( GasEndPoint gasEndPoint in GasEndPoints )
        {
            string msg = "GasEndPoint #" + ++pointCount;
            Log.Debug(msg);
            Cylinder cyl = gasEndPoint.Cylinder;
            msg = "...Pos: " + gasEndPoint.Position
                //+ ", ID: " + cyl.ID
                + ", FactID: " + cyl.FactoryId
                + ", Part: " + cyl.PartNumber
                + ", Fresh: " + cyl.IsFreshAir
                + ", ZeroAir: " + cyl.IsZeroAir
                + ", Pressure: " + cyl.Pressure.ToString();

            Log.Debug( msg );
            msg = "......";
            foreach ( GasConcentration gasCon in cyl.GasConcentrations )
            {
                msg += "[" + gasCon.Type.Code + " ";
                msg += ( gasCon.Concentration == DomainModelConstant.NullDouble ) ? "fresh" : gasCon.Concentration.ToString();
                msg += "]";
            }
            Log.Debug( msg );
        }

        Log.Debug( "Going to CALIBRATE sensors in following ORDER..." );
        int calOrder = 1;
        foreach ( InstalledComponent ic in _returnEvent.DockedInstrument.InstalledComponents )
        {
            if ( !( ic.Component is Sensor ) )
                continue; // Skip non-sensors.
            Log.Debug( "...#" + calOrder++ + ", Position " + ic.Position + ", UID=" + ic.Component.Uid + ", " + ic.Component.Type.Code );

        }
        #endregion

        try
        {
            _instrumentController.Initialize();

            CalibrateInstrument();

                // Need to determine the next time this instrument will be calibrated.  
                // Put this date into the event so it can be uploaded to iNet, and also 
                // update the global next date that's held in the switch service.
                _returnEvent.NextUtcScheduledDate = Master.Instance.SwitchService.NextUtcCalibrationDate
                 = Master.Instance.Scheduler.GetNextGasOperationDate( _returnEvent );
            }
            finally
        {
            // Dispose of the operation utility.
            _instrumentController.Dispose();
        }

        Log.TimingEnd( "INSTRUMENT CALIBRATION", stopwatch );

        return _returnEvent;
    }