private void ContinueEnumerate() { bool isStarted = false; if (portNames != null) { while ((!isStarted) && (curPortIdx < portNames.Length)) { isStarted = CheckNextPort(); curPortIdx++; } } timer.Start(); }
public static void Run() { PrecisionTimer timer = new PrecisionTimer(); Random rand = new Random(); int a, b, c = 0; timer.Start(); for (int i = 0; i < 100000; i++) { a = rand.Next(); b = rand.Next(); if (a > b) { c = a; b = c; } else { c = b; b = a; } } timer.Stop(); Console.WriteLine(c); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); timer.Start(); for (int i = 0; i < 100000; i++) { a = rand.Next(); b = rand.Next(); c = a > b ? a : b; b = a > b ? c : a; } timer.Stop(); Console.WriteLine(c); Console.WriteLine(timer.ElapsedSeconds); Console.ReadLine(); }
public void Open() { while (Interlocked.CompareExchange(ref portLock, 1, 0) != 0) { Thread.SpinWait(1); } port.Open(); timer.Start(); Interlocked.Decrement(ref portLock); }
private bool RequestDevInfo() { InvokeWriteStateLbl("Querying"); InvokeWriteLogString("Querying device info...\r\n"); InvokeSwitchProgressBarMode(ProgressBarStyle.Marquee); bool result = false; var cmdStr = NMEAParser.BuildProprietarySentence(ManufacturerCodes.UCN, "L", new object[] { (int)UCNL_SRV_CMD.DEV_INFO_GET, 0, "" }); try { nmeaPort.SendData(cmdStr); result = true; timer.Start(); InvokeWriteLogString(string.Format(">> {0}", cmdStr)); } catch (Exception ex) { ProcessException(ex, false); } return(result); }
public static void Run() { PrecisionTimer timer = new PrecisionTimer(); PagedArray <int> paged = new PagedArray <int>(2, 64); int[] normy = new int[2048]; normy[0] = 1; normy[15] = 1; paged[0] = 1; paged[15] = 1; for (int i = 0; i < 1; i++) { timer.Reset(); timer.Start(); Array.Copy(normy, 0, normy, 34, 16); timer.Stop(); } Console.WriteLine(timer.ElapsedSecondsF); paged[50] = 0; for (int i = 0; i < 1; i++) { timer.Reset(); timer.Start(); paged.CopyData(0, 16, 34); timer.Stop(); } Console.WriteLine(timer.ElapsedSecondsF); Console.ReadLine(); }
public void Start() { if (!timer.IsRunning) { t = 0; foreach (var item in speedFunctions) { direction = 1; zcoordinates[item.Key] = 0; zmaxPoints[item.Key] = -1; speeds[item.Key] = speedFunctions[item.Key](0); } timer.Start(); } }
public static void Run() { PrecisionTimer timer = new PrecisionTimer(); //CompleteBinarySearchTree<int> test = new CompleteBinarySearchTree<int>(10, 1); int count = 16384; //timer.Start(); //for (int i = 0; i < count; i++) // test.Add(i, i); //timer.Stop(); double time = timer.ElapsedSeconds / count; int[] testArray = new int[count]; PagedArray <int> testPaged = new PagedArray <int>(14, 1); testPaged[int.MaxValue] = 1; int a = 0; IEnumerator <int> enumer = testPaged.GetEnumerator(); timer.Reset(); //Console.ReadLine(); timer.Start(); while (enumer.MoveNext()) //foreach (int i in testArray) { //timer.Stop(); //Console.WriteLine(i); //timer.Start(); a = enumer.Current; //a = i; } timer.Stop(); //Console.WriteLine(a); //Console.WriteLine(time); //Console.WriteLine(time * count); //Console.WriteLine(time / (1.0 / 60.0) * 100); Console.WriteLine(timer.ElapsedSeconds / count); Console.WriteLine(timer.ElapsedSeconds); Console.WriteLine(timer.ElapsedSeconds / (1.0 / 60.0) * 100); Console.WriteLine(1.0 / 60.0); Console.ReadLine(); }
// Handles the subscriber's NewMeasurements event. private void DataSubscriber_NewMeasurements(object sender, EventArgs <ICollection <IMeasurement> > e) { // Gather statistics. Interlocked.Add(ref m_measurementCount, e.Argument.Count); // Queue the measurements up in the buffer. foreach (IMeasurement measurement in e.Argument) { if (m_channelIndexes.ContainsKey(measurement.ID)) { // Perform a rough per signal upsample if minimum sample rate is not met if (m_sampleRate < MINIMUM_SAMPLE_RATE) { IMeasurement upsampledMeasurement; double frequency = measurement.Value; for (int i = 0; i < MINIMUM_SAMPLE_RATE / m_sampleRate; i++) { upsampledMeasurement = Measurement.Clone(measurement); upsampledMeasurement.Value = Timbre.PureTone(frequency, i, 0, MINIMUM_SAMPLE_RATE) * Damping.Natural(i, MINIMUM_SAMPLE_RATE / m_sampleRate, MINIMUM_SAMPLE_RATE) * (Int16.MaxValue * 0.90D); m_buffer.Enqueue(upsampledMeasurement); } } else { m_buffer.Enqueue(measurement); } } } // If we've managed to buffer a full second of data, // stop the timeout timer and start the dump timer. // The dump timer is sending measurements to the sound card // so change the playback state to playing. if (m_dumpTimer != null && !m_dumpTimer.IsRunning && m_buffer.Count / 2 > m_sampleRate) { if (m_timeoutTimer != null) { m_timeoutTimer.Stop(); } m_dumpTimer.Start(); OnStateChanged(PlaybackState.Playing); } }
private void isSERModeChb_CheckedChanged(object sender, EventArgs e) { if (isSERMode) { echoerModeChb.Enabled = false; sendOnceBtn.Enabled = false; testMessageTxb.Enabled = false; timCnt = 0; timer.Start(); } else { timer.Stop(); testMessageTxb.Enabled = true; echoerModeChb.Enabled = true; sendOnceBtn.Enabled = true; } }
private void SynchronizeInputTimer(object state) { // Start timer at as close to the top of the millisecond as possible bool repeat = true; long last = 0, next; while (repeat) { next = DateTime.UtcNow.Ticks % Ticks.PerMillisecond % 1000; repeat = (next > last); last = next; } m_lastMissedWindowTime = 0; m_missedPublicationWindows = 0; if ((object)m_timer != null) { m_timer.Start(); } }
public static void Run() { int threadCount = Environment.ProcessorCount; Thread[] threads = new Thread[threadCount]; Primes = new long[threadCount]; barrier = new Barrier(threadCount); threads[0] = Thread.CurrentThread; PrecisionTimer timer = new PrecisionTimer(); for (int i = 1; i < threadCount; i++) { threads[i] = new Thread(ThreadMethodBarrier); } timer.Reset(); timer.Start(); for (int j = 1; j < threadCount; j++) { threads[j].Start(j); } for (int i = 0; i < 1000; i++) { Primes[0] = FindPrimeNumber(10000); barrier.SignalAndWait(); } Running = false; timer.Stop(); Console.WriteLine("Barrier Time: " + (timer.ElapsedSecondsF / 1000)); Console.WriteLine("Primes Found"); for (int i = 0; i < threadCount; i++) { Console.WriteLine(Primes[i]); } Console.ReadLine(); }
public void Start() { timer.Start(); }
private void OnAppStateChanged(AppState state) { switch (state) { case AppState.PORT_ABSENT: { portNameCbx.Enabled = false; openClosePortBtn.Enabled = false; deviceInfoGroup.Enabled = false; buoyAddressGroup.Enabled = false; statusLbl.Text = "No ports available"; break; } case AppState.PORT_OPENED: { portNameCbx.Enabled = false; openClosePortBtn.Text = "Close"; deviceInfoGroup.Enabled = false; buoyAddressGroup.Enabled = false; statusLbl.Text = "Port opened"; var message = NMEAParser.BuildProprietarySentence(ManufacturerCodes.TNT, "4", new object[] { LOC_DATA_INFO.LOC_DATA_DEVICE_INFO, 0 }); if (!TrySend(message)) { State = AppState.PORT_CLOSED; } else { State = AppState.DEV_INFO_QUERIED; } break; } case AppState.PORT_ERROR: { if (timer.IsRunning) { timer.Stop(); } statusLbl.Text = "Port error"; break; } case AppState.PORT_CLOSED: { if (timer.IsRunning) { timer.Stop(); } portNameCbx.Enabled = true; openClosePortBtn.Text = "Open"; openClosePortBtn.Enabled = true; deviceInfoGroup.Enabled = false; buoyAddressGroup.Enabled = false; statusLbl.Text = "Port closed"; break; } case AppState.DEV_INFO_QUERIED: { statusLbl.Text = "Device info queried..."; timer.Start(); break; } case AppState.DEV_INFO_RECEIVED: { if (timer.IsRunning) { timer.Stop(); } deviceInfoGroup.Enabled = true; statusLbl.Text = "Device info received"; string message = NMEAParser.BuildProprietarySentence(ManufacturerCodes.TNT, "7", new object[] { 0 }); if (TrySend(message)) { State = AppState.DEV_SETTINGS_QUERIED; timer.Start(); } else { State = AppState.PORT_ERROR; } break; } case AppState.DEV_TIMEOUT: { statusLbl.Text = "Device timeout"; break; } case AppState.WRONG_DEVICE: { if (timer.IsRunning) { timer.Stop(); } buoyAddressGroup.Enabled = false; statusLbl.Text = "Connected device is not a RedBASE"; break; } case AppState.DEV_SETTINGS_QUERIED: { statusLbl.Text = "Settings queried..."; break; } case AppState.DEV_SETTINGS_RECEIVED: { if (timer.IsRunning) { timer.Stop(); } buoyAddressGroup.Enabled = true; statusLbl.Text = "Settings received"; break; } case AppState.DEV_SETTINGS_APPLY_QUERIED: { statusLbl.Text = "Settings apply queried..."; timer.Start(); break; } case AppState.DEV_SETTINGS_UPDATED: { if (timer.IsRunning) { timer.Stop(); } statusLbl.Text = "Settings updated"; break; } default: { break; } } }
public RWLT_Core(SerialPortSettings rwltPortSettings, double radialErrorThreshold, double simplexSize, int courseEstimatorFIFOSize, int trkFilterFIFOSize) { #region parameters var basesIDs = Enum.GetValues(typeof(BaseIDs)); foreach (BaseIDs baseID in basesIDs) { if (baseID != BaseIDs.BASE_INVALID) { BaseBatVoltages.Add(baseID, new AgingValue <double>(4, 10, svoltageFormatter)); BaseMSRs.Add(baseID, new AgingValue <double>(4, 10, msrFormatter)); } } HDOPState = new AgingValue <DOPState>(4, 10, x => x.ToString().ToUpperInvariant()); TBAState = new AgingValue <TBAQuality>(4, 10, x => x.ToString().Replace('_', ' ').ToUpperInvariant()); TargetLatitude = new AgingValue <double>(4, 10, latlonFormatter); TargetLongitude = new AgingValue <double>(4, 10, latlonFormatter); TargetLocationRadialError = new AgingValue <double>(4, 10, rerrFormatter); TargetPressure = new AgingValue <double>(6, 10, prsFormatter); TargetTemperature = new AgingValue <double>(60, 120, tempFormatter); TargetBatVoltage = new AgingValue <double>(30, 120, svoltageFormatter); TargetDepth = new AgingValue <double>(6, 10, dptdstFormatter); TargetAlarm = new AgingValue <PingerCodeIDs>(600, 6000, pAlmFormatter); DistanceToTarget = new AgingValue <double>(4, 10, dptdstFormatter); ForwardAzimuthToTarget = new AgingValue <double>(4, 10, courseFormatter); ReverseAzimuthToTarget = new AgingValue <double>(4, 10, courseFormatter); TargetCourse = new AgingValue <double>(4, 10, courseFormatter); AUXLatitude = new AgingValue <double>(4, 10, latlonFormatter); AUXLongitude = new AgingValue <double>(4, 10, latlonFormatter); AUXTrack = new AgingValue <double>(4, 10, courseFormatter); AUXSpeed = new AgingValue <double>(4, 10, speedFormatter); CEP = new AgingValue <double>(4, 300, x => string.Format(CultureInfo.InvariantCulture, "{0:F03} m", x)); DRMS = new AgingValue <double>(4, 300, x => string.Format(CultureInfo.InvariantCulture, "{0:F03} m", x)); DRMS2 = new AgingValue <double>(4, 300, x => string.Format(CultureInfo.InvariantCulture, "{0:F03} m", x)); DRMS3 = new AgingValue <double>(4, 300, x => string.Format(CultureInfo.InvariantCulture, "{0:F03} m", x)); #endregion #region trkFilter trkFilter = new TrackFilter(trkFilterFIFOSize); #endregion #region pCore pCore = new PCore2D <GeoPoint3DT>(radialErrorThreshold, simplexSize, Algorithms.WGS84Ellipsoid, courseEstimatorFIFOSize); pCore.RadialErrorExeedsThrehsoldEventHandler += new EventHandler(pCore_RadialErrorExeedsThresholdEventHandler); pCore.TargetLocationUpdatedExHandler += new EventHandler <TargetLocationUpdatedExEventArgs>(pCore_TargetLocationUpdatedExEventHandler); pCore.BaseQualityUpdatedHandler += new EventHandler <BaseQualityUpdatedEventArgs>(pCore_BaseQualityUpdatedEventHandler); #endregion #region basesProcessor baseProcessor = new RWLT_BaseProcessor(4, 2.0); #endregion #region NMEA if (!nmeaSingleton) { NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.RWL); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.RWL, "A", "x,x.x,x.x,x.x,x.x,x,x.x,x.x,x.x"); } #endregion #region inPort inPort = new NMEASerialPort(rwltPortSettings); inPort.NewNMEAMessage += (o, e) => { LogEvent.Rise(o, new LogEventArgs(LogLineType.INFO, string.Format("{0} (IN) >> {1}", inPort.PortName, e.Message))); NMEAListener.ProcessIncoming(0, e.Message); }; inPort.PortError += (o, e) => LogEvent.Rise(o, new LogEventArgs(LogLineType.ERROR, string.Format("{0} (IN) >> {1}", inPort.PortName, e.EventType.ToString()))); #endregion #region NMEAListener NMEAListener = new NMEAMultipleListener(); NMEAListener.NMEAProprietaryUnsupportedSentenceParsed += new EventHandler <NMEAUnsupportedProprietaryEventArgs>(NMEAPSentenceReceived); NMEAListener.RMCSentenceReceived += new EventHandler <RMCMessageEventArgs>(GNSS_RMCSentenceReceived); #endregion #region timer timer = new PrecisionTimer(); timer.Period = 100; timer.Tick += (o, e) => { if (++systemUpdateTS > systemUpdateLimit) { systemUpdateTS = 0; SystemUpdateEvent.Rise(this, new EventArgs()); } if (inPort.IsOpen && (++inPortTimeoutTS > inPortTimeoutLimit)) { inPortTimeoutTS = 0; InPortTimeout = true; LogEvent.Rise(this, new LogEventArgs(LogLineType.ERROR, string.Format("{0} (IN) >> TIMEOUT", inPort.PortName))); } if (AUXGNSSUsed && auxGNSSPort.IsOpen && (++AUXGNSSTimeoutTS > AUXGNSSTimeoutLimit)) { AUXGNSSTimeoutTS = 0; AUXGNSSTimeout = true; LogEvent.Rise(this, new LogEventArgs(LogLineType.ERROR, string.Format("{0} (AUX) >> TIMEOUT", auxGNSSPort.PortName))); } }; timer.Start(); #endregion statHelper = new List <GeoPoint>(); }
public static void Run(int entityCount, int componentCount) { PrecisionTimer timer = new PrecisionTimer(); List <int>[] componentLists = new List <int> [componentCount]; int[] requiredComponents = new int[componentCount]; Random rand = new Random(); for (int i = 0; i < componentCount; i++) { componentLists[i] = new List <int>(entityCount); requiredComponents[i] = i; } for (int i = 0; i < entityCount; i++) { for (int j = 0; j < componentCount; j++) { if (rand.Next(10) > 5) { componentLists[j].Add(i); } } } Console.WriteLine("Time to Create Entity : " + timer.ElapsedSeconds); timer.Reset(); List <int[]> components = new List <int[]>(); timer.Reset(); timer.Start(); int[] place = new int[requiredComponents.Length]; bool done = false; for (place[0] = 0; place[0] < componentLists[0].Count; place[0]++) { int count = 1; int val = componentLists[0][place[0]]; for (int i = 1; i < place.Length; i++) { while (componentLists[i][place[i]] < val) { place[i]++; if (place[i] == componentLists[i].Count) { done = true; break; } } if (done) { break; } if (componentLists[i][place[i]] > val) { break; } count++; } if (done) { break; } if (count == place.Length) { components.Add(place); } } timer.Stop(); Console.WriteLine("Time for Component Worst Case: " + timer.ElapsedSeconds); Console.ReadLine(); }
public static void Run() { PrecisionTimer timer = new PrecisionTimer(); Random rand = new Random(); int[] ID1 = new int[100000]; int[] ID2 = new int[1000]; Console.WriteLine("Set Equivalence Test"); for (int i = 0; i < ID1.Length; i++) { ID1[i] = rand.Next(); if (i < ID2.Length) { ID2[i] = ID1[i]; } } bool found = false; timer.Start(); for (int i = 0; i < ID1.Length; i++) { found = false; for (int j = 0; j < ID2.Length; j++) { if (ID1[i] == ID2[j]) { found = true; break; } } if (!found) { break; } } timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); timer.Start(); found = ID1.All((i) => { return(ID2.Contains(i)); }); timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); timer.Start(); found = ID1.All((i) => { return(ID2.Any((j) => { return i == j; })); }); timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); timer.Start(); //Fastest in worst case found = !ID1.Any((i) => { return(!ID2.Contains(i)); }); timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); for (int i = 0; i < ID2.Length; i++) { ID2[i] = rand.Next(); } timer.Start(); //fastest in best case for (int i = 0; i < ID1.Length; i++) { found = false; for (int j = 0; j < ID2.Length; j++) { if (ID1[i] == ID2[j]) { found = true; break; } } if (!found) { break; } } timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); timer.Start(); found = ID1.All((i) => { return(ID2.Contains(i)); }); timer.Stop(); double temp = timer.ElapsedSeconds; Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); timer.Start(); found = ID1.All((i) => { return(ID2.Any((j) => { return i == j; })); }); timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); timer.Reset(); // // // Best in Worst Case and Close 2nd in Best Case // // timer.Start(); found = !ID1.Any((i) => { return(!ID2.Contains(i)); }); timer.Stop(); Console.WriteLine(found); Console.WriteLine(timer.ElapsedSeconds); Console.WriteLine(timer.ElapsedSeconds / temp * 100); timer.Reset(); Console.ReadLine(); }
public void Open() { InitDeviceInformation(); port.Open(); timer.Start(); }
public MainForm() { InitializeComponent(); #region filenames DateTime startTime = DateTime.Now; settingsFileName = Path.ChangeExtension(Application.ExecutablePath, "settings"); loggerFileName = StrUtils.GetTimeDirTreeFileName(startTime, Application.ExecutablePath, "LOG", "log", true); snapshotsPath = StrUtils.GetTimeDirTree(startTime, Application.ExecutablePath, "SNAPSHOTS", false); #endregion #region logger logger = new TSLogProvider(loggerFileName); logger.WriteStart(); logger.TextAddedEvent += (o, e) => { if (geoPlotCartesian.InvokeRequired) { geoPlotCartesian.Invoke((MethodInvoker) delegate { geoPlotCartesian.AppendHistoryLine(e.Text); geoPlotCartesian.Invalidate(); }); } else { geoPlotCartesian.AppendHistoryLine(e.Text); geoPlotCartesian.Invalidate(); } }; #endregion #region settingsProvider settingsProvider = new SimpeSettingsProviderXML <SettingsContainer>(); settingsProvider.isSwallowExceptions = false; try { settingsProvider.Load(settingsFileName); } catch (Exception ex) { ProcessException(ex, true); } settingsProvider.isSwallowExceptions = true; logger.Write(settingsProvider.Data.ToString()); #endregion #region NMEA NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.VLB); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.VLB, "L", "x.x,x.x,x.x,x.x,x,x.x,x.x,x.x"); #endregion #region agingValues targetLatitude = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "LAT: {0:F06}°", x)); targetLongitude = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "LON: {0:F06}°", x)); targetRadialError = new AgingValue <double>(3, 300, (x) => string.Format(CultureInfo.InvariantCulture, "RER: {0:F03} m", x)); targetTemperature = new AgingValue <double>(3, 600, (x) => string.Format(CultureInfo.InvariantCulture, "TMP: {0:F01} °C", x)); targetDepth = new AgingValue <double>(3, 60, (x) => string.Format(CultureInfo.InvariantCulture, "DPT: {0:F03} m", x)); targetBatVoltage = new AgingValue <double>(3, 300, (x) => string.Format(CultureInfo.InvariantCulture, "BAT: {0:F01} V", x)); targetMSR = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "MSR: {0:F01} dB", x)); targetPTime = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "TIM: {0:F04} sec", x)); ownLatitude = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "LAT: {0:F06}°", x)); ownLongitude = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "LON: {0:F06}°", x)); ownDepth = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "DPT: {0:F03} m", x)); ownBatteryVoltage = new AgingValue <double>(3, 20, (x) => string.Format(CultureInfo.InvariantCulture, "BAT: {0:F01} V", x)); #endregion #region geoPlotCartesian geoPlotCartesian.AddTrack("Rover", Color.Gray, 2, 2, settingsProvider.Data.MeasurementsFIFOSize, true); geoPlotCartesian.AddTrack("Measurements", Color.Blue, 2, 2, settingsProvider.Data.MeasurementsFIFOSize, true); geoPlotCartesian.AddTrack("Reference point", Color.Magenta, 4, 4, 1, false); geoPlotCartesian.AddTrack("Base", Color.Green, 4, 4, settingsProvider.Data.BaseSize, false); geoPlotCartesian.AddTrack("Target", Color.Red, 6, 6, settingsProvider.Data.TargetLocationFIFOSize, true); #endregion #region vlblCore vlblCore = new VLBLCore <VLBLTOAMeasurement>(settingsProvider.Data.MeasurementsFIFOSize, settingsProvider.Data.BaseSize, settingsProvider.Data.RadialErrorThreshold, settingsProvider.Data.SimplexSize, UCNLNav.Algorithms.WGS84Ellipsoid); vlblCore.BaseUpdatedEventHandler += (o, e) => { UpdateTrack("Base", e.BasePoints); }; vlblCore.ReferencePointUpdatedEventHandler += (o, e) => { UpdateTrack("Reference point", vlblCore.ReferencePoint); }; vlblCore.TargetPositionUpdatedEventHandler += (o, e) => { UpdateTrack("Target", e.TargetPosition); if (InvokeRequired) { Invoke((MethodInvoker) delegate { targetLatitude.Value = e.TargetPosition.Latitude; targetLongitude.Value = e.TargetPosition.Longitude; targetRadialError.Value = e.RadialError; }); } else { targetLatitude.Value = e.TargetPosition.Latitude; targetLongitude.Value = e.TargetPosition.Longitude; targetRadialError.Value = e.RadialError; } }; #endregion #region tracks tracks = new Dictionary <string, List <GeoPoint3D> >(); #endregion #region InPort inPort = new NMEASerialPort(new SerialPortSettings(settingsProvider.Data.InPortName, settingsProvider.Data.InPortBaudrate, System.IO.Ports.Parity.None, DataBits.dataBits8, System.IO.Ports.StopBits.One, System.IO.Ports.Handshake.None)); inPort.NewNMEAMessage += new EventHandler <NewNMEAMessageEventArgs>(inPort_NewNMEAMessage); #endregion #region OutPort if (settingsProvider.Data.IsUseOutPort) { outPort = new SerialPort(settingsProvider.Data.OutPortName, (int)settingsProvider.Data.OutPortBaudrate); } #endregion #region timer timer = new PrecisionTimer(); timer.Period = 1000; timer.Mode = Mode.Periodic; timer.Tick += new EventHandler(timer_Tick); timer.Start(); #endregion }
public bool StartImageStream() { bool retVal = false; if (imageStream != null && imageStream.IsEnabled) { tbFramePosition.Minimum = 0; imageStream.CurrentFrame = 0; tbFramePosition.Maximum = imageStream.FrameCount; if (tbFramePosition.Maximum > 0) { tbFramePosition.Value = 0; } cmdPlay.Enabled = true; cmdPause.Enabled = true; cmdStop.Enabled = true; cmdRecord.Enabled = true; if (imageStream.FrameRate > 0) { targetfps = (int)imageStream.FrameRate; spf = 1000 / (int)imageStream.FrameRate; } else { targetfps = FRAME_RATE; spf = 1000 / FRAME_RATE; } udFrameRate.TextBoxText = targetfps.ToString("0"); lblHeight.Text = "Image Height: " + imageStream.FrameHeight.ToString("0"); lblWidth.Text = "Image Width: " + imageStream.FrameWidth.ToString("0"); imageStream.StartReading(); //wait until the reader buffer fills up while (imageStream.ReadBufferFullness < 99) //start with a 100% full buffer { Thread.Sleep(100); } if(imageStream.FrameCount <= 0) { lblMovieProgress.Text = "Live streaming"; lblMovieProgress.Enabled = false; tbFramePosition.Enabled = false; } else { lblMovieProgress.Enabled = true; tbFramePosition.Enabled = true; } lblMovieProgress.Invalidate(); isStopped = false; cmdPause.Checked = false; cmdRecord.Checked = false; isRecording = false; tbFramePosition.Left = gbTrainingSet.Left; renderTimer = new PrecisionTimer(spf, this); renderTimer.Start(); videoStart = DateTime.Now; retVal = imageStream.IsEnabled; } else { isStopped = true; cmdPause.Checked = false; cmdRecord.Checked = false; isRecording = true; cmdPlay.Enabled = false; cmdPause.Enabled = false; cmdStop.Enabled = false; cmdRecord.Enabled = false; } return retVal; }
public void Start() { Reset(); timer.Start(); }
public MainForm() { InitializeComponent(); this.Text = string.Format("{0}", Application.ProductName); #region file names & paths DateTime startTime = DateTime.Now; settingsFileName = Path.ChangeExtension(Application.ExecutablePath, "settings"); logPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "LOG"); logFileName = StrUtils.GetTimeDirTreeFileName(startTime, Application.ExecutablePath, "LOG", "log", true); snapshotsPath = StrUtils.GetTimeDirTree(startTime, Application.ExecutablePath, "SNAPSHOTS", false); #endregion #region logger loggerTextAddedEventHandler = new EventHandler <TextAddedEventArgs>(logger_TextAdded); logger = new TSLogProvider(logFileName); logger.TextAddedEvent += loggerTextAddedEventHandler; logger.WriteStart(); #endregion #region settings logger.Write("Loading settings..."); settingsProvider = new SettingsProviderXML <SettingsContainer>(); settingsProvider.isSwallowExceptions = false; try { settingsProvider.Load(settingsFileName); } catch (Exception ex) { ProcessException(ex, true); } logger.Write(settingsProvider.Data.ToString()); gtr_RemoteTimeout_S = Convert.ToInt32((GTR.MIN_REM_TOUT_MS / 1000) + 2 * (double)settingsProvider.Data.MaxDistance / 1500) + 1; #endregion #region NMEA NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.TNT); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "0", "x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "1", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "2", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "3", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "4", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "5", "x,x.x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "6", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "7", "x,x.x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "8", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "9", "x,x.x,x.x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "A", "x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "B", "x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "C", "x,x.x,x.x,x.x,x.x,x.x,x.x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "D", "x,x,x.x,x.x,x.x,x.x,x.x,x.x,x.x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "E", "x,x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "!", "c--c,x,c--c,x,x,c--c"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "O", "x.x,x.x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "P", "x,x.x"); /* #define IC_D2H_ACK '0' // $PTNT0,errCode #define IC_H2D_FLD_GET '1' // $PTNT1,fldID,reserved #define IC_H2D_FLD_SET '2' // $PTNT2,fldID,fldNewValue #define IC_D2H_FLD_VAL '3' // $PTNT3,fldID,fldValue #define IC_H2D_LOC_DATA_GET '4' // $PTNT4,locDataID,reserved #define IC_D2H_LOC_DATA_VAL '5' // $PTNT5,locDataID,locDataValue #define IC_H2D_ACT_INVOKE '6' // $PTNT6,actionID,reserved #define IC_H2D_LOC_DATA_SET '7' // $PTNT7,locDataID,locDataValue #define IC_H2D_REM_SEND '8' // $PTNT8,targetAddr,codeMsg #define IC_D2H_REM_RECEIVED '9' // $PTNT9,codeMsg,snrd,dpl #define IC_H2D_REM_PING 'A' // $PTNTA,targetAddr,timeoutMs #define IC_D2H_REM_TOUT 'B' // $PTNTB,targetAddr #define IC_D2H_REM_PONG 'C' // $PTNTC,requestedAddr,snrd,dpl,pTime,[dst],[dpt],[tmp] #define IC_D2H_REM_PONGEX 'D' // $PTNTD,requestedAddr,requestedCmd,receivedValue_decoded,snrd,dpl,pTime,[dst],[dpt],[tmp] #define IC_H2D_REM_PINGEX 'E' // $PTNTE,targetAddr,requestedCmd,timeoutMs #define IC_D2H_DEV_INFO_VAL '!' // $PTNT!,sys_moniker,sys_ver,dev_type,core_moniker,core_ver,dev_serial_num #define IC_D2H_PRETMP_VAL 'O' // $PTNTO,pressure_mbar,temp_deg_c #define IC_H2D_SETVAL 'P' // $PTNTP,valueID,value */ #endregion #region other gtrPortErrorEventHandler = new EventHandler <SerialErrorReceivedEventArgs>(gtrPort_Error); gtrPortNewNMEAMessageEventHandler = new EventHandler <NewNMEAMessageEventArgs>(gtrPort_NewNMEAMessage); gtrPort = new NMEASerialPort(new SerialPortSettings(settingsProvider.Data.GTRPortName, BaudRate.baudRate9600, System.IO.Ports.Parity.None, DataBits.dataBits8, System.IO.Ports.StopBits.One, System.IO.Ports.Handshake.None)); gtrPort.IsRawModeOnly = false; timerTickHandler = new EventHandler(timer_Tick); timer = new PrecisionTimer(); timer.Mode = Mode.Periodic; timer.Period = 1000; timer.Tick += timerTickHandler; timer.Start(); if (settingsProvider.Data.IsGNSSEmulator) { gnssEmulatorPort = new NMEASerialPort(new SerialPortSettings(settingsProvider.Data.GNSSEmulatorPortName, BaudRate.baudRate9600, Parity.None, DataBits.dataBits8, StopBits.One, Handshake.None)); } measurements = new Measurements(settingsProvider.Data.MeasurementsFIFOSize, settingsProvider.Data.BaseSize); bLatitude = new AgingDouble("F06", "°"); bLongitude = new AgingDouble("F06", "°"); bTemperature = new AgingDouble("F01", "°C"); bDepth = new AgingDouble("F03", " m"); tTemperature = new AgingDouble("F01", "°C"); tDepth = new AgingDouble("F02", " m"); tLatitude = new AgingDouble("F06", "°"); tLongitude = new AgingDouble("F06", "°"); tRadialError = new AgingDouble("F03", " m"); tLocation = new List <GeoPoint3DWE>(); bLocation = new List <GeoPoint>(); tBestLocation = new GeoPoint3DWE(); tBestLocation.Latitude = double.NaN; tBestLocation.Longitude = double.NaN; tBestLocation.RadialError = double.NaN; marinePlot.InitTracks(settingsProvider.Data.MeasurementsFIFOSize); marinePlot.AddTrack("BOAT GNSS", Color.Blue, 2.0f, 2, settingsProvider.Data.MeasurementsFIFOSize, true); marinePlot.AddTrack("BASE", Color.Salmon, 2.0f, 8, settingsProvider.Data.BaseSize, false); marinePlot.AddTrack("MEASUREMENTS", Color.Green, 2.0f, 4, settingsProvider.Data.MeasurementsFIFOSize, false); marinePlot.AddTrack("TARGET", Color.Black, 2.0f, 4, settingsProvider.Data.MeasurementsFIFOSize, false); marinePlot.AddTrack("BEST", Color.Red, 2.0f, 8, 1, false); #endregion }
void Run(SystemInfo[] systems, SystemType type, double time, int laneCount) { int typeCount = 0; double averageTime = 0; PrecisionTimer processTimer = new PrecisionTimer(); PrecisionTimer unitTimer = new PrecisionTimer(); Console.WriteLine("Test 1 - Adding All Systems at Once"); for (int i = 0; i < systems.Length; i++) { if (systems[i].Type == type) { typeCount++; } } SafeSystemSchedule schedule = new SafeSystemSchedule(SystemType.Logic, laneCount, typeCount); processTimer.Start(); for (int i = 0; i < systems.Length; i++) { unitTimer.Start(); SystemInfo sysInf = systems[i]; if (!sysInf.Active || sysInf.Type != type) { unitTimer.Stop(); averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1); unitTimer.Reset(); continue; } schedule.Add(sysInf); unitTimer.Stop(); processTimer.Stop(); averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1); unitTimer.Reset(); processTimer.Start(); } processTimer.Stop(); Console.WriteLine("Total Time to Register : " + processTimer.ElapsedSeconds); Console.WriteLine("Average Time to Register : " + averageTime); Console.WriteLine("Extrapolated Time to Register : " + (averageTime * systems.Length)); Console.WriteLine("Extrapolated Time without nonTypes : " + (averageTime * typeCount)); processTimer.Reset(); Console.ReadLine(); Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("Test 2 - Adding Each System One at a Time"); averageTime = 0; schedule.Clear(); processTimer.Start(); for (int i = 0; i < systems.Length; i++) { unitTimer.Start(); SystemInfo sysInf = systems[i]; if (!sysInf.Active || sysInf.Type != type) { unitTimer.Stop(); averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1); unitTimer.Reset(); continue; } schedule.Add(sysInf); unitTimer.Stop(); processTimer.Stop(); averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1); unitTimer.Reset(); while (schedule.NextSystem(0, out SystemInfo sysInfo) != ScheduleResult.Finished) { sysInfo.Age = 1; } processTimer.Start(); } processTimer.Stop(); Console.WriteLine("Total Time to Register : " + processTimer.ElapsedSeconds); Console.WriteLine("Average Time to Register : " + averageTime); Console.WriteLine("Extrapolated Time to Register : " + (averageTime * systems.Length)); Console.WriteLine("Extrapolated Time without nonTypes : " + (averageTime * typeCount)); processTimer.Reset(); Console.ReadLine(); Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("Test 3 - Clear List and Readd"); SafeSystemSchedule copy = new SafeSystemSchedule(schedule); foreach (SystemInfo sysinf in systems) { SystemUpdate(sysinf); } processTimer.Start(); schedule.Clear(); for (int i = 0; i < systems.Length; i++) { SystemInfo sysInf = systems[i]; if (!sysInf.Active || sysInf.Type != type) { continue; } schedule.Add(sysInf); } processTimer.Stop(); while (schedule.NextSystem(0, out SystemInfo sysInfo) != ScheduleResult.Finished) { Console.WriteLine(sysInfo); } Console.WriteLine("Total Time to clear then readd : " + processTimer.ElapsedSeconds); Console.ReadLine(); Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("Test 4 - Remove Individually and Register One at a time"); processTimer.Start(); copy.Reset(); for (int i = 0; i < systems.Length; i++) { SystemInfo sysInf = systems[i]; if (!sysInf.Active || sysInf.Type != type) { continue; } copy.Remove(sysInf); copy.Add(sysInf); } processTimer.Stop(); while (copy.NextSystem(0, out SystemInfo sysInfo) != ScheduleResult.Finished) { Console.WriteLine(sysInfo); } Console.WriteLine("Total Time to remove then readd : " + processTimer.ElapsedSeconds); Console.ReadLine(); Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-="); Console.WriteLine("Test 5 - System Run"); schedule.Clear(); for (int i = 0; i < systems.Length; i++) { SystemInfo sysInf = systems[i]; if (!sysInf.Active || sysInf.Type != type) { continue; } schedule.Add(sysInf); } double currentTime = 0; int finishCount = 0; double[] endTimes = new double[laneCount]; bool[] finished = new bool[laneCount]; averageTime = 0; processTimer.Start(); while (!schedule.Finished && currentTime < time && finishCount < laneCount) { for (int i = 0; i < laneCount; i++) { if (endTimes[i] <= currentTime && !finished[i]) { unitTimer.Start(); schedule.FinishLane(i); ScheduleResult result = schedule.NextSystem(i, out SystemInfo sysInf); if (result == ScheduleResult.Supplied) { sysInf.Age = 0; if (sysInf.AverageRunTime + currentTime > time) { finished[i] = true; finishCount++; unitTimer.Stop(); continue; } endTimes[i] = currentTime + sysInf.AverageRunTime; } else if (result == ScheduleResult.Finished) { finished[i] = true; finishCount++; } unitTimer.Stop(); processTimer.Stop(); averageTime = MathHelper.MovingAverage(averageTime, unitTimer.ElapsedSeconds, i + 1); unitTimer.Reset(); processTimer.Start(); } } processTimer.Stop(); double nextTime = double.PositiveInfinity; for (int i = 0; i < laneCount; i++) { if (endTimes[i] > currentTime && endTimes[i] < nextTime) { nextTime = endTimes[i]; } } if (nextTime != double.PositiveInfinity) { currentTime = nextTime; } processTimer.Start(); } processTimer.Stop(); Console.WriteLine("Total Time to decide : " + processTimer.ElapsedSeconds); Console.WriteLine("Average Time to decide : " + averageTime); Console.WriteLine("Extrapolated Time to decide : " + (averageTime * typeCount)); Console.WriteLine("Total Time Used : " + (currentTime) + "/" + time); processTimer.Reset(); Console.ReadLine(); }
/// <summary> /// Create a new <see cref="FrameRateTimer"/> class. /// </summary> /// <param name="framesPerSecond">Desired frame rate for <see cref="PrecisionTimer"/>.</param> /// <param name="processingInterval">Desired processing interval, if applicable.</param> /// <remarks> /// When the <paramref name="processingInterval"/> is set to -1, the frame rate timer interval will be calculated as a distribution /// of whole milliseonds over the specified number of <paramref name="framesPerSecond"/>. Otherwise the specified /// <paramref name="processingInterval"/> will be used as the timer interval. /// </remarks> public FrameRateTimer(int framesPerSecond, int processingInterval) { if (processingInterval == 0) throw new InvalidOperationException("A frame rate timer should not be created when using a processing interval of zero, i.e., processing data as fast as possible."); m_framesPerSecond = framesPerSecond; m_processingInterval = processingInterval; // Create a new precision timer for this timer state m_timer = new PrecisionTimer(); m_timer.AutoReset = true; if (processingInterval > 0) { // Establish fixed timer period m_timer.Period = processingInterval; } else { // Attach handler for timer period assignments m_timer.Tick += SetTimerPeriod; // Calculate distributed wait time periods over specified number of frames per second m_framePeriods = new int[framesPerSecond]; for (int frameIndex = 0; frameIndex < framesPerSecond; frameIndex++) { m_framePeriods[frameIndex] = CalcWaitTimeForFrameIndex(frameIndex); } // Establish initial timer period m_lastFramePeriod = m_framePeriods[0]; m_timer.Period = m_lastFramePeriod; } // Start timer m_timer.Start(); }
public APLLBLCore(Dictionary <string, SerialPortSettings> inPortSettings, double radialErrorThreshold, double simplexSize, int courseEstimatorFifoSize, int trackFilterSize) { #region misc. initialization primaryGNSSFixRMC = new AgingValue <RMCMessageEventArgs>(2, 10, x => string.Format(CultureInfo.InvariantCulture, "LAT: {0:F06}°\r\nLON: {1:F06}°\r\nSPD: {2:F01} m/s (3:F01 km/h)\r\nTRK: {4:F01}°", x.Latitude, x.Longitude, x.SpeedKmh / 3.6, x.SpeedKmh, x.TrackTrue)); meanWaterTemperatureC = new AgingValue <double>(10, 30, x => string.Format(CultureInfo.InvariantCulture, "MTW: {0:F01} °C", x)); targetFix = new AgingValue <GeoPoint3DETm>(3, 60, x => string.Format(CultureInfo.InvariantCulture, "LAT: {0:F06}°\r\nLON: {1:F06}°\r\nRER: {2:F03} m", x.Latitude, x.Longitude, x.RadialError)); targetFixFlt = new AgingValue <GeoPoint3DETm>(3, 60, x => string.Format(CultureInfo.InvariantCulture, "LAT: {0:F06}°\r\nLON: {1:F06}°", x.Latitude, x.Longitude)); targetCourse = new AgingValue <double>(4, 8, x => string.Format(CultureInfo.InvariantCulture, "CRS: {0:F01}°", x)); distanceToTarget = new AgingValue <double>(4, 8, x => string.Format(CultureInfo.InvariantCulture, "D2T: {0:F01} m", x)); forwardAzimuthToTarget = new AgingValue <double>(4, 8, x => string.Format(CultureInfo.InvariantCulture, "FAZ: {0:F01}°", x)); reverseAzimuthToTarget = new AgingValue <double>(4, 8, x => string.Format(CultureInfo.InvariantCulture, "RAZ: {0:F01}°", x)); BaseBatStates = new Dictionary <BaseIDs, AgingValue <bool> >(); BaseBatStates.Add(BaseIDs.BASE_1, new AgingValue <bool>(30, 60, x => !x ? string.Format("{0} BAT LOW!", BaseIDs.BASE_1) : string.Empty)); BaseBatStates.Add(BaseIDs.BASE_2, new AgingValue <bool>(30, 60, x => !x ? string.Format("{0} BAT LOW!", BaseIDs.BASE_1) : string.Empty)); BaseBatStates.Add(BaseIDs.BASE_3, new AgingValue <bool>(30, 60, x => !x ? string.Format("{0} BAT LOW!", BaseIDs.BASE_1) : string.Empty)); BaseBatStates.Add(BaseIDs.BASE_4, new AgingValue <bool>(30, 60, x => !x ? string.Format("{0} BAT LOW!", BaseIDs.BASE_1) : string.Empty)); dopState = new AgingValue <DOPState>(4, 10, x => x.ToString().Replace('_', ' ').ToUpperInvariant()); tbaQuality = new AgingValue <TBAQuality>(4, 10, x => x.ToString().Replace('_', ' ').ToUpperInvariant()); #endregion #region pCore trkFilter = new TrackFilter(trackFilterSize); pCore = new PCore2D <GeoPoint3DT>(radialErrorThreshold, simplexSize, Algorithms.WGS84Ellipsoid, courseEstimatorFifoSize); pCore.RadialErrorExeedsThrehsoldEventHandler += (o, e) => InfoEventHandler.Rise(this, new LogEventArgs(LogLineType.INFO, "WAYU Pinger location failed: radial error exeeds threshold")); pCore.TargetLocationUpdatedExHandler += (o, e) => { targetFix.Value = new GeoPoint3DETm(e.Location.Latitude, e.Location.Longitude, e.Location.Depth, e.Location.RadialError, e.TimeStamp); targetCourse.Value = e.Course; var fltTrk = trkFilter.Filter(e.Location.Latitude, e.Location.Longitude); targetFixFlt.Value = new GeoPoint3DETm(fltTrk.Latitude, fltTrk.Longitude, e.Location.Depth, e.Location.RadialError, e.TimeStamp); if (primaryGNSSFixRMC.IsInitializedAndNotObsolete) { UpdateTargetRelativeData(); } InfoEventHandler.Rise(this, new LogEventArgs(LogLineType.INFO, string.Format(CultureInfo.InvariantCulture, "WAYU Pinger located: {0}, Course: {1:F01}°", targetFixFlt, e.Course))); TrackUpdateHandler.Rise(this, new TrackUpdateEventArgs("WAYU (RAW)", targetFix.Value, e.Course)); TrackUpdateHandler.Rise(this, new TrackUpdateEventArgs("WAYU (FLT)", targetFixFlt.Value, e.Course)); if ((outPort != null) && (outPort.IsOpen)) { WriteOutData(targetFixFlt.Value.Latitude, targetFixFlt.Value.Longitude, 0.0, targetFix.Value.RadialError, targetCourse.Value, targetFix.Value.RadialError <= pCore.RadialErrorThreshold); } SystemUpdate(); }; pCore.BaseQualityUpdatedHandler += (o, e) => { dopState.Value = e.DopState; tbaQuality.Value = e.TBAState; }; #endregion #region basesProcessor basesProcessor = new APLBaseProcessor(4, 2.0); #endregion #region NMEA if (!nmeaSingleton) { NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.APL); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.APL, "A", "x,x.x,x.x,x.x,x,x.x"); nmeaSingleton = true; } #endregion #region Port dictionaries portDescrByHash = new Dictionary <int, string>(); portNameByHash = new Dictionary <int, string>(); portHashByDescr = new Dictionary <string, int>(); portTimoutFlags = new Dictionary <int, bool>(); portTSByHash = new Dictionary <int, int>(); portDescrByHash.Add(emuID, emuIDstr); portNameByHash.Add(emuID, emuIDstr); portHashByDescr.Add(emuIDstr, emuID); #endregion #region nmeaListener nmeaListener = new NMEAMultipleListener(); nmeaListener.LogEventHandler += (o, e) => InfoEventHandler.Rise(o, e); nmeaListener.NMEAIncomingMessageReceived += (o, e) => InfoEventHandler.Rise(o, new LogEventArgs(LogLineType.INFO, string.Format("{0} ({1}) >> {2}", portNameByHash[e.SourceID], portDescrByHash[e.SourceID], e.Message))); nmeaListener.RMCSentenceReceived += new EventHandler <RMCMessageEventArgs>(nmeaListener_RMCSentenceReceivedHandler); nmeaListener.MTWSentenceReceived += new EventHandler <MTWMessageEventArgs>(nmeaListener_MTWSentenceReceivedHandler); nmeaListener.NMEAProprietaryUnsupportedSentenceParsed += new EventHandler <NMEAUnsupportedProprietaryEventArgs>(nmeaListener_NMEAUnsupportedProprietaryReceivedHander); #endregion #region inPorts List <SerialPortSettings> portsList = new List <SerialPortSettings>(); foreach (var inPort in inPortSettings) { int portHash = inPort.Value.PortName.GetHashCode(); portDescrByHash.Add(portHash, inPort.Key); portNameByHash.Add(portHash, inPort.Value.PortName); portHashByDescr.Add(inPort.Key, portHash); portTimoutFlags.Add(portHash, false); portTSByHash.Add(portHash, 0); portsList.Add(inPort.Value); } inPorts = new SerialPortsPool(portsList.ToArray()); inPorts.DataReceived += (o, e) => { int portKey = e.PortName.GetHashCode(); portTSByHash[portKey] = 0; if (portTimoutFlags[portKey]) { portTimoutFlags[portKey] = false; PortStateChangedHandler.Rise(this, new EventArgs()); } nmeaListener.ProcessIncoming(portKey, e.Data); }; inPorts.ErrorReceived += (o, e) => InfoEventHandler.Rise(o, new LogEventArgs(LogLineType.ERROR, string.Format("{0} ({1}) >> {2}", e.PortName, portDescrByHash[e.PortName.GetHashCode()], e.EventType.ToString()))); #endregion #region timer timer = new PrecisionTimer(); timer.Mode = Mode.Periodic; timer.Period = 100; timer.Tick += (o, e) => { if (IsOpen) { int[] keys = new int[portTSByHash.Count]; portTSByHash.Keys.CopyTo(keys, 0); for (int i = 0; i < keys.Length; i++) { portTSByHash[keys[i]] += timerPeriodMS; if (portTSByHash[keys[i]] > portsTimeoutMS) { portTSByHash[keys[i]] = 0; if (!portTimoutFlags[keys[i]]) { portTimoutFlags[keys[i]] = true; PortStateChangedHandler.Rise(this, new EventArgs()); } } } } systemUpdateTS += timerPeriodMS; if (systemUpdateTS > systemUpdateTimeoutMS) { SystemUpdate(); } }; timer.Start(); #endregion }