/// <summary> /// Bubble up power meter errors /// </summary> private void Meter_OnPowerMeterError(NewportMeter <BaseSerialPort> PowerMeter, string ErrorMessage, int ErrorCode) { if (ErrorHandler != null) { ErrorHandler.Invoke(this, ErrorMessage, ErrorCode); } }
/// <summary> /// Open a connection to the power meter and start taking readings. /// </summary> /// <param name="COMPort">System COM port to open, must be a valid system serial port</param> public async void StartReadingAsync(String COMPort = null) { StopReading(); if (String.IsNullOrEmpty(COMPort)) { MeterUnableToConnect?.Invoke(null); } else { // Wait a bit to let connection settle System.Threading.Thread.Sleep(250); try { Meter = await System.Threading.Tasks.Task.Run(() => { Meter = new NewportMeter <BaseSerialPort>(COMPort); Meter.OnPowerMeterError += Meter_OnPowerMeterError; MeterConnecting?.Invoke(Meter); StartBackgroundReadingThread(); return(Meter); }); } catch (System.UnauthorizedAccessException e) { MeterUnableToConnect?.Invoke(e.Message); } } }
/// <summary> /// Check a COM port for the presence of a power meter. /// </summary> /// <param name="ComPort">COM port name to check</param> /// <param name="FailedToOpen">On return, this is TRUE if the COM port failed to open (i.e., if another process had it open), FALSE if COM port opened but doesn't appear to be a power meter</param> /// <returns>TRUE if an appropriate meter was found on the COM port specified, FALSE otherwise (FALSE if another process has COM port open)</returns> public static Boolean CheckForMeter(String ComPort, out Boolean FailedToOpen) { FailedToOpen = true; try { if (!String.IsNullOrEmpty(ComPort)) { using (NewportMeter <Port> Newport = new NewportMeter <Port>(ComPort)) { FailedToOpen = false; Newport.SendCommand("", true); Newport.GetDeviceID(); if (Newport.Make.Equals("NEWPORT")) { return(true); } } } } catch { // An exception probably means somebody else has this COM port open, or it is not a // power meter. In either case, we can't use it. } finally { } return(false); }
/// <summary> /// Stop taking readings from any connected power meter. The Reading property will still contain the /// last reading from the meter. /// </summary> public void StopReading() { if (Meter != null) { StopBackgroundReadingThread(); MeterDisconneting?.Invoke(Meter); Meter.Dispose(); Meter = null; } }