public RedNavPort() { portSettings = new SerialPortSettings("COM1", BaudRate.baudRate115200, Parity.None, DataBits.dataBits8, StopBits.One, Handshake.None); #region timers timer = new PrecisionTimer(); timer.Mode = Mode.Periodic; timer.Period = 5000; timer.Tick += new EventHandler(timer_Tick); #endregion #region Handlers port_NewNMEAMessage_Handler = new EventHandler <NewNMEAMessageEventArgs>(port_NewNMEAMessage); port_PortError_Handler = new EventHandler <SerialErrorReceivedEventArgs>(port_PortError); #endregion #region NMEA NMEAInit(); #endregion }
public VerticalPropagationPlot() { InitializeComponent(); timer = new PrecisionTimer(); timer.Period = 10; timer.Mode = Mode.Periodic; timer.Tick += new EventHandler(timer_Tick); timer.Stopped += (o, e) => { if (this.InvokeRequired) { this.Invoke((MethodInvoker) delegate { SimulationFinishedEvent.Rise(o, e); }); } else { SimulationFinishedEvent.Rise(o, e); } }; timer.Started += (o, e) => { if (this.InvokeRequired) { this.Invoke((MethodInvoker) delegate { SimulationStartedEvent.Rise(o, e); }); } else { SimulationStartedEvent.Rise(o, e); } }; }
public APLEmulator() { timer = new PrecisionTimer(); timer.Period = 10; timer.Mode = Mode.Periodic; timer.Tick += (o, e) => { sec += 0.01; if (sec > data[idx][0]) { var msg = NMEAParser.BuildProprietarySentence(ManufacturerCodes.APL, "A", new object[] { Convert.ToInt32(data[idx][1]), data[idx][2], data[idx][3], data[idx][4], 1, data[idx][5] }); EmulatorOutputEvent.Rise(this, new NewNMEAMessageEventArgs(msg)); idx++; if (idx >= data.Count) { sec = 0; idx = 0; } } }; }
/// <summary> /// Create a new <see cref="PrecisionInputTimer"/> class. /// </summary> /// <param name="framesPerSecond">Desired frame rate for <see cref="PrecisionTimer"/>.</param> internal PrecisionInputTimer(int framesPerSecond) { // Create synchronization objects m_timerTickLock = new object(); m_frameWaitHandleA = new ManualResetEventSlim(false); m_frameWaitHandleB = new ManualResetEventSlim(false); m_useWaitHandleA = true; m_framesPerSecond = framesPerSecond; // Create a new precision timer for this timer state m_timer = new PrecisionTimer(); m_timer.Resolution = 1; m_timer.Period = 1; m_timer.AutoReset = true; // Attach handler for timer ticks m_timer.Tick += m_timer_Tick; m_frameWindowSize = (int)Math.Round(1000.0D / framesPerSecond) * 2; m_frameMilliseconds = Ticks.MillisecondDistribution(framesPerSecond); // Start high resolution timer on a separate thread so the start // time can synchronized to the top of the millisecond ThreadPool.QueueUserWorkItem(SynchronizeInputTimer); }
/// <summary> /// Create a new <see cref="PrecisionInputTimer"/> class. /// </summary> /// <param name="framesPerSecond">Desired frame rate for <see cref="PrecisionTimer"/>.</param> internal PrecisionInputTimer(int framesPerSecond) { // Create synchronization objects m_timerTickLock = new SpinLock(); m_frameWaitHandleA = new ManualResetEventSlim(false); m_frameWaitHandleB = new ManualResetEventSlim(false); m_useWaitHandleA = true; m_framesPerSecond = framesPerSecond; // Create a new precision timer for this timer state m_timer = new PrecisionTimer(); m_timer.Resolution = 1; m_timer.Period = 1; m_timer.AutoReset = true; // Attach handler for timer ticks m_timer.Tick += m_timer_Tick; m_frameWindowSize = (int)Math.Round(1000.0D / framesPerSecond) * 2; m_frameMilliseconds = new int[framesPerSecond]; for (int frameIndex = 0; frameIndex < framesPerSecond; frameIndex++) { m_frameMilliseconds[frameIndex] = (int)(1.0D / framesPerSecond * (frameIndex * 1000.0D)); } // Start high resolution timer on a separate thread so the start // time can synchronized to the top of the millisecond ThreadPool.QueueUserWorkItem(SynchronizeInputTimer); }
public MainForm() { InitializeComponent(); var portNames = SerialPort.GetPortNames(); if (portNames.Length > 0) { #region Other buoyAddrCbx.Items.AddRange(Enum.GetNames(typeof(RedBASE_Addr))); BuoyAddr = RedBASE_Addr.REDBASE_ADDR_INVALID; #endregion #region NMEA NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.TNT); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "0", "x"); // ACK $PTNT0,errCode NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "4", "x,x"); // LOC_DATA_GET $PTNT4,dataID,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "5", "x,x"); // LOC_DATA_VAL $PTNT5,dataID,dataVal NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "!", "c--c,x,c--c,x,x,c--c"); // DEV_INFO $PTNT!,sys_moniker,sys_ver,dev_type,core_moniker,core_ver,dev_serial_num NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "7", "x"); // SETTINGS_GET $PTNT7,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "8", "x,x"); // SETTINGS_SET $PTNT8,buoyAddr,isInverted NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "9", "x,x"); // SETTINGS_VAL $PTNT9,buoyAddr,isInverted #endregion #region timer timer = new PrecisionTimer(); timer.Period = 1000; timer.Mode = Mode.Periodic; timer.Tick += new EventHandler(timer_Tick); timer.Started += new EventHandler(timer_Started); timer.Stopped += new EventHandler(timer_Stopped); #endregion #region port port = new NMEASerialPort(new SerialPortSettings("COM1", BaudRate.baudRate9600, Parity.None, DataBits.dataBits8, StopBits.One, Handshake.None)); port.NewNMEAMessage += new EventHandler <NewNMEAMessageEventArgs>(port_NewNMEAMessage); port.PortError += new EventHandler <SerialErrorReceivedEventArgs>(port_Error); port.IsRawModeOnly = false; #endregion portNameCbx.Items.AddRange(portNames); portNameCbx.SelectedIndex = 0; State = AppState.PORT_CLOSED; } else { State = AppState.PORT_ABSENT; } }
public override uint GetPrecisionTime() { #if USE_DOTNET return PrecisionTimer.GetCurrentTime(); #elif (UNITY_ANDROID || UNITY_IPHONE) && !UNITY_EDITOR lock (timeLock) { return NativePInvoke.GetPrecisionTime(); } #endif }
// Detaches from events, stops, and disposes of the dump timer. Timers created // through the CreateDumpTimer method should be released through this method. private void ReleaseDumpTimer(PrecisionTimer dumpTimer) { if (dumpTimer != null) { dumpTimer.Tick -= DumpTimer_Tick; dumpTimer.Stop(); dumpTimer.Dispose(); } }
// Creates the dump timer. Timers created through this method // should be released through the ReleaseDumpTimer method. private PrecisionTimer CreateDumpTimer() { PrecisionTimer dumpTimer = new PrecisionTimer(); dumpTimer.AutoReset = true; dumpTimer.Period = 100; dumpTimer.Tick += DumpTimer_Tick; return(dumpTimer); }
public TimedDispatcher(double intervalSeconds, TimedDispatch dispatch, Object[] dispatchParams) { fDispatch = dispatch; fParams = dispatchParams; fInterval = intervalSeconds; fLatency = 0.103; // Initial latency, 3 milliseconds fLatencyReports = 1; fStopWatch = new PrecisionTimer(); }
/// <summary> /// Initializes a new instance of the <see cref="CsvInputAdapter"/> class. /// </summary> public CsvInputAdapter() { m_fileName = "measurements.csv"; m_columns = new Dictionary <string, int>(StringComparer.CurrentCultureIgnoreCase); m_columnMappings = new Dictionary <int, IMeasurement>(); m_inputInterval = 33.333333; m_measurementsPerInterval = 5; // Set minimum timer resolution to one millisecond to improve timer accuracy PrecisionTimer.SetMinimumTimerResolution(1); }
/// <summary> /// Releases the unmanaged resources used by the <see cref="FileImporter"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if ((object)m_fileSystemWatcher != null) { m_fileSystemWatcher.Created -= m_fileSystemWatcher_Created; m_fileSystemWatcher.Renamed -= m_fileSystemWatcher_Renamed; m_fileSystemWatcher.Dispose(); } m_fileSystemWatcher = null; if (UseHighResolutionInputTimer) { PrecisionInputTimer.Detach(ref m_precisionTimer); } else if ((object)m_looseTimer != null) { m_looseTimer.Stop(); m_looseTimer.Dispose(); } m_looseTimer = null; if ((object)m_fileStream != null) { m_fileStream.Close(); m_fileStream.Dispose(); } m_fileStream = null; if ((object)m_fileProcessQueue != null) { m_fileProcessQueue.ProcessException -= m_fileProcessQueue_ProcessException; } m_fileProcessQueue = null; // Clear minimum timer resolution. PrecisionTimer.ClearMinimumTimerResolution(1); } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } }
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(); }
/// <summary> /// Initializes a new instance of the <see cref="FileImporter"/> class. /// </summary> public FileImporter() { m_fileProcessQueue = new AsyncQueue <string>(); m_fileProcessQueue.ProcessItemFunction = ProcessFile; m_fileProcessQueue.ProcessException += m_fileProcessQueue_ProcessException; m_columns = new Dictionary <string, int>(StringComparer.CurrentCultureIgnoreCase); m_columnMappings = new Dictionary <int, IMeasurement>(); m_inputInterval = 5.0D; m_measurementsPerInterval = 13; m_skipRows = 2; m_timestampFormat = "dd-MMM-yyyy HH:mm:ss.fff"; // Set minimum timer resolution to one millisecond to improve timer accuracy PrecisionTimer.SetMinimumTimerResolution(1); }
/// <summary> /// Stops playback and releases resources, but does not close the stream. /// </summary> public void Stop() { PrecisionTimer dumpTimer = m_dumpTimer; IWavePlayer player = m_wavePlayer; Timer statTimer = m_statTimer; m_dumpTimer = null; m_wavePlayer = null; m_statTimer = null; ReleaseDumpTimer(dumpTimer); ReleaseWavePlayer(player); ReleaseStatTimer(statTimer); m_dataSubscriber?.Unsubscribe(); OnStateChanged(PlaybackState.Stopped); }
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 SnapperWindow(int x, int y, int width, int height) : base("Pixel Share", 10, 10, 640, 480) { // Show a form so we can capture the desired group IP and port number ServerForm groupForm = new ServerForm(); //IPAddress randomAddress = NewTOAPIA.Net.Utility.GetRandomMulticastAddress(); //groupForm.groupAddressField.Text = randomAddress.ToString(); groupForm.ShowDialog(); // Get the address and port from the form fUseGray = groupForm.checkBox1.Checked; string groupIP = groupForm.groupAddressField.Text; int groupPort = int.Parse(groupForm.groupPortField.Text); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(groupIP), groupPort); // Set our title to the address specified so the user // can easily identify their session. Title = "SnapNShare - " + ipep.ToString(); fSnapper = new ScreenSnapper(); fClientOrigin = new POINT(); int pwidth = ClientRectangle.Width; int pheight = ClientRectangle.Height; fScreenImage = new GDIDIBSection(width, height, BitCount.Bits24); fGrayImage = new PixelArray<Lumb>(width, height,fScreenImage.Orientation, new Lumb()); BackgroundColor = RGBColor.White; this.Opacity = 0.5; // Add the channel for graphics commands CommChannel graphicsChannel = new CommChannel(ipep, true, false); fCommandDispatcher = new GraphPortChunkEncoder(graphicsChannel); // Start the thread that will take snapshots of the screen fGlobalTimer = new PrecisionTimer(); fFrameRate = 2; // Frames per second fSnapperRunning = true; snapperThread = new Thread(RunSnaps); snapperThread.Start(); }
public RWLT_Emulator(double origin_lat, double origin_lon, double dpt, double tmp, double bat) { GeoPoint origin = new GeoPoint(Algorithms.Deg2Rad(origin_lat), Algorithms.Deg2Rad(origin_lon)); baseLocations = new Dictionary <BaseIDs, GeoPoint>(); baseSpeeds = new Dictionary <BaseIDs, double>(); baseCourses = new Dictionary <BaseIDs, double>(); TOAs = new Dictionary <BaseIDs, double>(); baseBats = new Dictionary <BaseIDs, double>(); targetBat = bat; targetSpeed = rnd.NextDouble() * 2; targetCourse = rnd.NextDouble() * Math.PI * 2; targetDpt = dpt; targetTemp = tmp; targetLocation = MoveGeoPoint(origin, 10 + rnd.NextDouble() * 50, targetCourse); auxSpeed = rnd.NextDouble() * 2; auxCourse = rnd.NextDouble() * Math.PI * 2; auxLocation = MoveGeoPoint(origin, 100 + rnd.NextDouble() * 50, auxCourse); timer = new PrecisionTimer(); timer.Period = 1000; timer.Tick += new EventHandler(timer_Tick); double az_step = Math.PI / 2.0; double az = rnd.NextDouble() * Math.PI * 2.0; foreach (BaseIDs baseID in baseIDs) { if (baseID != BaseIDs.BASE_INVALID) { baseCourses.Add(baseID, rnd.NextDouble() * Math.PI * 2); baseSpeeds.Add(baseID, rnd.NextDouble() * 0.5); baseLocations.Add(baseID, MoveGeoPoint(origin, 100 + rnd.NextDouble() * 20, az)); baseBats.Add(baseID, 12.0); az += az_step; } } }
GraphPortChunkEncoder fCommandDispatcher; // Used to do PixBlt to the net #endregion public DesktopCapture(ConferenceAttendee attendee) { fAttendee = attendee; fContext = GDIContext.CreateForDefaultDisplay(); //fCommandDispatcher = new GraphPortChunkEncoder(attendee); int width = 800; int height = 600; fResolution = new Resolution(width, height); fScreenImage = new GDIDIBSection(width, height); fGrayImage = new PixelArray<Lumb>(width, height, fScreenImage.Orientation, new Lumb()); // Start the thread that will take snapshots of the screen fGlobalTimer = new PrecisionTimer(); fFrameRate = 10; // Frames per second fSnapperRunning = true; fSnapperThread = new Thread(RunSnaps); // WAA //fSnapperThread.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(); }
/// <summary> /// Releases the unmanaged resources used by the <see cref="CsvInputAdapter"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if (UseHighResolutionInputTimer) { PrecisionInputTimer.Detach(ref m_precisionTimer); } else if ((object)m_looseTimer != null) { m_looseTimer.Stop(); m_looseTimer.Dispose(); } m_looseTimer = null; if ((object)m_inStream != null) { m_inStream.Close(); m_inStream.Dispose(); } m_inStream = null; // Clear minimum timer resolution. PrecisionTimer.ClearMinimumTimerResolution(1); } } finally { m_disposed = true; // Prevent duplicate dispose. base.Dispose(disposing); // Call base class Dispose(). } } }
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(); }
/// <summary> /// Releases the unmanaged resources used by the <see cref="PrecisionInputTimer"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> private void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if ((object)m_timer != null) { m_timer.Tick -= m_timer_Tick; m_timer.Dispose(); } m_timer = null; if ((object)m_frameWaitHandleA != null) { m_frameWaitHandleA.Set(); m_frameWaitHandleA.Dispose(); } m_frameWaitHandleA = null; if ((object)m_frameWaitHandleB != null) { m_frameWaitHandleB.Set(); m_frameWaitHandleB.Dispose(); } m_frameWaitHandleB = null; } } finally { m_disposed = true; // Prevent duplicate dispose. } } }
private void gameLoop() { _soccerPitch = new SoccerPitch(pictureBox1.ClientRectangle.Width, pictureBox1.ClientRectangle.Height); _simulationStarted = true; PrecisionTimer timer = new PrecisionTimer(ParameterManager.Instance.FrameRate); while (!_stopEvent.WaitOne(0, true)) { if (timer.ReadyForNextFrame() && !_simulationPaused) { _soccerPitch.Update(); } pictureBox1.Invalidate(); Thread.Sleep(1); } _soccerPitch = null; _simulationStarted = false; // a final call to repaint our current state pictureBox1.Invalidate(); }
public uMCPNMEAPort(SerialPortSettings portSettings) { #region Parsers parsers = new Dictionary <string, parserDelegate>() { { "0", new parserDelegate(LACK_Parse) }, { "2", new parserDelegate(RACK_Parse) }, { "3", new parserDelegate(RPKT_Parse) }, { "5", new parserDelegate(STAT_Parse) } }; #endregion #region port port = new NMEASerialPort(portSettings); port.PortError += (o, e) => { PortErrorEventHandler.Rise(this, e); }; port.NewNMEAMessage += new EventHandler <NewNMEAMessageEventArgs>(port_MessageReceived); #endregion #region nmea if (!nmeaSingleton) { NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.MCP); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.MCP, "0", "c--c,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.MCP, "1", "x,x,x,x,x"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.MCP, "2", "h--h"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.MCP, "3", "h--h"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.MCP, "4", "h--h"); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.MCP, "5", "x,x"); //#define IC_D2H_LACK '0' // $PMCP0,sentenceID,errCode - local command ACK //#define IC_H2D_STRT '1' // $PMCP1,senderID,targetID,selectDefState,selIntMs,toutIntMs - restart protocol with specified params //#define IC_D2H_RACK '2' // $PMCP2,h--h // sent packet acknowledged //#define IC_D2H_RPKT '3' // $PMCP3,h--h // packet received //#define IC_H2D_SPKT '4' // $PMCP4,h--h // send packet //#define IC_D2H_STAT '5' // $PMCP5,state,select // protocol state changed } #endregion #region timer timer = new PrecisionTimer(); timer.Period = 1000; timer.Mode = Mode.OneShot; timer.Tick += (o, e) => { PortTimeoutEventHandler.Rise(this, new EventArgs()); IsWaiting = false; }; #endregion #region other dataToSend = new TSQueue <byte[]>(128, 128); dataToSend.ItemEnqueued += (o, e) => { if (!isWaiting) { OnPortFree(); } }; #endregion }
public SnapperWindow(int x, int y, int width, int height) : base("Snap N Share", 10, 10, 640, 480) { // Show a form so we can capture the desired group IP and port number ServerForm groupForm = new ServerForm(); //IPAddress randomAddress = NewTOAPIA.Net.Utility.GetRandomMulticastAddress(); //groupForm.groupAddressField.Text = randomAddress.ToString(); groupForm.ShowDialog(); // Get the address and port from the form fUseGray = groupForm.checkBox1.Checked; string groupIP = groupForm.groupAddressField.Text; int groupPort = int.Parse(groupForm.groupPortField.Text); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(groupIP), groupPort); // Set our title to the address specified so the user // can easily identify their session. Title = "SnapNShare - " + ipep.ToString(); fSnapper = new ScreenSnapper(); fClientOrigin = new POINT(); int pwidth = ClientRectangle.Width; int pheight = ClientRectangle.Height; fScreenImage = new GDIDIBSection(width, height, BitCount.Bits24); fGrayImage = new PixelArray<Lumb>(width, height,fScreenImage.Orientation, new Lumb()); BackgroundColor = RGBColor.White; this.Opacity = 0.5; // Create the MultiSession object so we can send stuff out to a group //fSession = new MultiSession(Guid.NewGuid().ToString(), ipep); fSession = new MultiSession(ipep, Guid.NewGuid().ToString(), "William", true, true, null); // Add the channel for graphics commands PayloadChannel payloadChannel = fSession.CreateChannel(PayloadType.dynamicPresentation); fCommandDispatcher = new GraphPortChunkEncoder(payloadChannel); fUserIOChannel = fSession.CreateChannel(PayloadType.xApplication2); //fUserIOEncoder = new UserIOChannelEncoder(fUserIOChannel); //fUserIODecoder = new UserIOChannelDecoder(fUserIOChannel); //fUserIODecoder.MouseActivityEvent += new MouseActivityEventHandler(fUserIODecoder_MouseActivityEvent); //fUserIODecoder.KeyboardActivityEvent += new KeyboardActivityEventHandler(fUserIODecoder_KeyboardActivityEvent); // Start the thread that will take snapshots of the screen fGlobalTimer = new PrecisionTimer(); fFrameRate = 2; // Frames per second fSnapperRunning = true; snapperThread = new Thread(RunSnaps); snapperThread.Start(); }
/// <summary> /// This thread routine takes snapshots of the screen periodically. The frame /// rate is governed by the FrameRate property of the window. /// The frame rate is governed by taking time stamps after each frame is captured /// and sent to the network. If there is more than 10 ms before the next frame /// is to be captured, the thread will sleep for that amount of time before /// performing the next capture. /// </summary> void RunSnaps() { int frameCounter = 0; double frameIncrement = 1.0 / fFrameRate; PrecisionTimer timer = new PrecisionTimer(); // Use to monitor frame rate timer.Reset(); double lastTime = timer.GetElapsedSeconds(); double nextTime = lastTime; double captureStart; double captureDuration; while (fSnapperRunning) { // Figure out when the next frame should be displayed nextTime += frameIncrement; // Capture and display the current frame captureStart = timer.GetElapsedSeconds(); SendSnapshot(); captureDuration = timer.GetElapsedSeconds() - captureStart; lastTime = timer.GetElapsedSeconds(); // Increment the frame count just so we know // what frame we're on. frameCounter++; // We know when the next frame is to be displayed. // Calculate the amount to sleep by looking at the current time, and // the amount of time it takes to make the snapshot. double diffTime = nextTime - lastTime - captureDuration; // Turn it into milliseconds int millis = (int)(diffTime * 1000); // We don't bother sleeping if the difference is less // than 10 milliseconds as we can't really guaranteed // the accuracy of the Sleep() method, so we get as close // as we can. if (millis > 10) Thread.Sleep(millis); } }
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(); }
public DotNetPlatform() { PrecisionTimer.GetCurrentTime(); }
/// <summary> /// Stops playback and releases resources, but does not close the stream. /// </summary> public void Stop() { PrecisionTimer dumpTimer = m_dumpTimer; IWavePlayer player = m_wavePlayer; Timer statTimer = m_statTimer; m_dumpTimer = null; m_wavePlayer = null; m_statTimer = null; ReleaseDumpTimer(dumpTimer); ReleaseWavePlayer(player); ReleaseStatTimer(statTimer); if (m_dataSubscriber != null) { m_dataSubscriber.Unsubscribe(); } OnStateChanged(PlaybackState.Stopped); }
public MainForm() { InitializeComponent(); #region Paths DateTime startTime = DateTime.Now; settingsFilePath = Path.ChangeExtension(Application.ExecutablePath, "settings"); logPath = Utils.GetDateDirTree(Application.ExecutablePath, "LOG", startTime); logFilePath = Path.Combine(logPath, Utils.GetTimeFileName(startTime, "log")); if (!Directory.Exists(logPath)) { Directory.CreateDirectory(logPath); } #endregion #region logger logger = new TSLogProvider(logFilePath); logger.WriteStart(); #endregion #region settings bool settingsOk = false; settingsProvider = new SettingsProviderXML <SettingsContainer>(); settingsProvider.isSwallowExceptions = false; try { settingsProvider.Load(settingsFilePath); logger.Write(settingsProvider.Data.ToString()); } catch (Exception ex) { logger.Write(ex); MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } if (!settingsOk) { try { settingsProvider.Save(settingsFilePath); } catch (Exception ex) { logger.Write(ex); MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } #endregion #region UI testMessageTxb.Text = GenerateTestString(); locDataIdCbx.Items.AddRange(Enum.GetNames(typeof(LOC_DATA_IDs))); locDataIdCbx.SelectedIndex = 0; List <string> subIDs = new List <string>(); for (int i = 0; i < Utils.MAX_SUBSCRIBERS; i++) { subIDs.Add(i.ToString()); } txChIdCbx.Items.AddRange(subIDs.ToArray()); rxChIdCbx.Items.AddRange(subIDs.ToArray()); txChId = 0; rxChId = 0; mainSplit.Enabled = false; #endregion #region port port = new NMEASerialPort(new SerialPortSettings(settingsProvider.Data.RedLINEPortName, BaudRate.baudRate9600, Parity.None, DataBits.dataBits8, StopBits.One, Handshake.None)); port.NewNMEAMessage += new EventHandler <NewNMEAMessageEventArgs>(port_NewNMEAMessage); port.PortError += new EventHandler <SerialErrorReceivedEventArgs>(port_Error); port.RawDataReceived += new EventHandler <RawDataReceivedEventArgs>(port_RawData); #endregion #region timer timer = new PrecisionTimer(); timer.Tick += new EventHandler(timer_Tick); timer.Period = 1000; #endregion #region NMEA NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.TNT); NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "!", "c--c,x,c--c,x,x,c--c"); // IC_D2H_DEV_INFO_VAL $PTNT!,sys_moniker,sys_ver,dev_type,core_moniker,core_ver,dev_serial_num NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "0", "x"); // IC_D2H_ACK $PTNT0,errCode NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "1", "x,x"); // IC_H2D_FLD_GET $PTNT1,fldID,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "2", "x,x"); // IC_H2D_FLD_SET $PTNT2,fldID,fldNewValue NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "3", "x,x"); // IC_D2H_FLD_VAL $PTNT3,fldID,fldValue NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "4", "x,x"); // IC_H2D_LOC_DATA_GET $PTNT4,locDataID,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "5", "x,x.x"); // IC_D2H_LOC_DATA_VAL $PTNT5,locDataID,locDataValue NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "6", "x,x"); // IC_H2D_ACT_INVOKE $PTNT6,actionID,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "7", "x,x,x,x"); // IC_H2D_SETTINGS_WRITE $PTNT7,rxChID,txChID,isRTX,isRvrs NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "8", "x"); // IC_H2D_SETTINGS_READ $PTNT8,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "9", "x,x,x,x"); // IC_D2H_SETTINGS $PTNT9,rxChID,txChID,isRTX,isRvrs NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.TNT, "P", "x,x.x"); // IC_H2D_SETVAL $PTNTP,valueID,value #endregion }
public uWAVEPort(string portName, BaudRate portBaudrate) { #region NMEA init if (!singleton) { NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.UWV); #region Common sentences // IC_D2H_ACK $PUWV0,cmdID,errCode NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "0", "c--c,x"); // IC_H2D_SETTINGS_WRITE $PUWV1,rxChID,txChID,styPSU,isCmdMode,isACKOnTXFinished,gravityAcc NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "1", "x,x,x.x,x,x,x.x"); #endregion #region Short code messages management sentences // IC_H2D_RC_REQUEST $PUWV2,txChID,rxChID,rcCmdID NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "2", "x,x,x"); // IC_D2H_RC_RESPONSE $PUWV3,txChID,rcCmdID,propTime_seс,snr,[value],[azimuth] NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "3", "x,x,x.x,x.x,x.x,x.x"); // IC_D2H_RC_TIMEOUT $PUWV4,txChID,rcCmdID NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "4", "x,x"); // IC_D2H_RC_ASYNC_IN $PUWV5,rcCmdID,snr,[azimuth] NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "5", "x,x.x,x.x"); #endregion #region Ambient data management sentences // IC_H2D_AMB_DTA_CFG $PUWV6,isWriteInFlash,periodMs,isPrs,isTemp,isDpt,isBatV NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "6", "x,x,x,x,x,x"); // IC_D2H_AMB_DTA $PUWV7,prs_mBar,temp_C,dpt_m,batVoltage_V NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "7", "x.x,x.x,x.x,x.x"); #endregion #region Device info // IC_H2D_DINFO_GET $PUWV?,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "?", "x"); // IC_D2H_DINFO $PUWV!,serial_number,sys_moniker,sys_version,core_moniker [release],core_version,acBaudrate,rxChID,txChID,totalCh,styPSU,isPTS,isCmdModeDefault NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "!", "c--c,c--c,x,c--c,x,x.x,x,x,x,x.x,x,x"); #endregion #region Packet mode // IC_H2D_PT_SETTINGS_READ $PUWVD,reserved NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "D", "x"); // IC_D2H_PT_SETTINGS $PUWVE,isPTMode,ptAddress NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "E", "x,x"); // IC_H2H_PT_SETTINGS_WRITE $PUWVF,isSaveInFlash,isPTMode,ptAddress NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "F", "x,x,x"); // IC_H2D_PT_SEND $PUWVG,tareget_ptAddress,[maxTries],data NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "G", "x,x,h--h"); // IC_D2H_PT_FAILED $PUWVH,tareget_ptAddress,triesTaken,data NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "H", "x,x,h--h"); // IC_D2H_PT_DLVRD $PUWVI,tareget_ptAddress,triesTaken,data NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "I", "x,x,h--h"); // IC_D2H_PT_RCVD $PUWVJ,sender_ptAddress,data NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "J", "x,h--h"); #endregion #region LBL-related // IC_D2H_PT_HEARD $PUWVK,b_id,b_lat,b_lon,b_toa_s,sender_pt_Address,dataPacket NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "K", "x,x.x,x.x,x.x,x,h--h"); //IC_D2H_CM_HEARD $PUWVL,b_id,b_lat,b_lon,b_toa_s,data_ID,dataValue,msr_dB NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "L", "x,x.x,x.x,x.x,x,x.x,x.x"); #endregion singleton = true; } #endregion #region Parsers parsers = new Dictionary <ICs, parserDelegate>() { { ICs.IC_D2H_ACK, new parserDelegate(ACK_Parse) }, { ICs.IC_D2H_AMB_DTA, new parserDelegate(AMB_DTA_Parse) }, { ICs.IC_D2H_DINFO, new parserDelegate(DINFO_Parse) }, { ICs.IC_D2H_RC_ASYNC_IN, new parserDelegate(RC_ASYNC_IN_Parse) }, { ICs.IC_D2H_RC_RESPONSE, new parserDelegate(RC_RESPONSE_Parse) }, { ICs.IC_D2H_RC_TIMEOUT, new parserDelegate(RC_TIMEOUT_Parse) }, { ICs.IC_D2H_PT_SETTINGS, new parserDelegate(PT_SETTINGS_Parse) }, { ICs.IC_D2H_PT_FAILED, new parserDelegate(PT_FAILED_Parse) }, { ICs.IC_D2H_PT_DLVRD, new parserDelegate(PT_DLVRD_Parse) }, { ICs.IC_D2H_PT_RCVD, new parserDelegate(PT_RCVD_Parse) }, { ICs.IC_D2H_CM_HEARD, new parserDelegate(CM_HEARD) }, { ICs.IC_D2H_PT_HEARD, new parserDelegate(PT_HEARD) }, }; #endregion #region port port = new NMEASerialPort(new SerialPortSettings(portName, portBaudrate, System.IO.Ports.Parity.None, DataBits.dataBits8, System.IO.Ports.StopBits.One, System.IO.Ports.Handshake.None)); port.NewNMEAMessage += new EventHandler <NewNMEAMessageEventArgs>(port_NewNMEAMessageReceived); port.PortError += new EventHandler <SerialErrorReceivedEventArgs>(port_ErrorReceived); port.RawDataReceived = new EventHandler <RawDataReceivedEventArgs>(port_RawDataReceived); #endregion #region timer timer = new PrecisionTimer(); timer.Mode = Mode.Periodic; timer.Period = 1000; timer.Tick += new EventHandler(timer_Tick); #endregion #region Misc. InitDeviceInformation(); #endregion }
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(); }
/// <summary> /// Releases the unmanaged resources used by the <see cref="FrameRateTimer"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> private void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if (m_timer != null) { if (m_processingInterval == -1) m_timer.Tick -= SetTimerPeriod; m_timer.Dispose(); } m_timer = null; } } finally { m_disposed = true; // Prevent duplicate dispose. } } }
/// <summary> /// Opens the stream and starts playback. /// </summary> /// <param name="songName">The name of the song to be played.</param> public void Play(string songName) { if (m_dataSubscriber != null && m_metadata != null) { UnsynchronizedSubscriptionInfo info; StringBuilder filterExpression = new StringBuilder(); DataTable deviceTable = m_metadata.Tables["DeviceDetail"]; DataTable measurementTable = m_metadata.Tables["MeasurementDetail"]; Dictionary<string, string> uriSettings; string dataChannel = null; int uriIndex = ConnectionUri.IndexOf(URI_SEPARATOR); m_channelIndexes = new ConcurrentDictionary<Guid, int>(); m_sampleRate = DEFAULT_SAMPLE_RATE; m_numChannels = DEFAULT_NUM_CHANNELS; // Get sample rate from metadata. if (deviceTable != null) { string sampleRate = deviceTable.Rows.Cast<DataRow>() .Single(row => row["Acronym"].ToNonNullString() == songName)["FramesPerSecond"].ToNonNullString(); if (!string.IsNullOrEmpty(sampleRate)) m_sampleRate = int.Parse(sampleRate); } // Get measurements from metadata. if (measurementTable != null) { IEnumerable<DataRow> measurementRows = measurementTable.Rows.Cast<DataRow>() .Where(row => row["DeviceAcronym"].ToNonNullString() == songName) .Where(row => row["SignalAcronym"].ToNonNullString() == "ALOG" || row["SignalAcronym"].ToNonNullString() == "VPHM") .Where(row => row["Enabled"].ToNonNullString().ParseBoolean()) .OrderBy(row => row["ID"].ToNonNullString()); m_numChannels = 0; foreach (DataRow row in measurementRows) { Guid measurementID = Guid.Parse(row["SignalID"].ToNonNullString()); if (m_numChannels > 0) filterExpression.Append(';'); filterExpression.Append(measurementID); m_channelIndexes[measurementID] = m_numChannels; m_numChannels++; } } // Create UDP data channel if specified. if (uriIndex >= 0) { uriSettings = ConnectionUri.Substring(uriIndex + URI_SEPARATOR.Length).ParseKeyValuePairs('&'); if (uriSettings.ContainsKey("udp")) dataChannel = string.Format("dataChannel={{port={0}; interface={1}}}", uriSettings["udp"], IPv6Enabled ? "::0" : "0.0.0.0"); } m_buffer = new ConcurrentQueue<IMeasurement>(); m_dumpTimer = CreateDumpTimer(); m_statTimer = CreateStatTimer(); m_waveProvider = new BufferedWaveProvider(new WaveFormat(m_sampleRate < MINIMUM_SAMPLE_RATE ? MINIMUM_SAMPLE_RATE : m_sampleRate, m_numChannels)); m_wavePlayer = CreateWavePlayer(m_waveProvider); m_waveProvider.DiscardOnBufferOverflow = true; info = new UnsynchronizedSubscriptionInfo(false) { FilterExpression = filterExpression.ToString(), ExtraConnectionStringParameters = dataChannel }; m_statTimer.Start(); m_wavePlayer.Play(); m_dataSubscriber.UnsynchronizedSubscribe(info); m_timeoutTimer.Start(); OnStateChanged(PlaybackState.Buffering); } }
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(); }
// Creates the dump timer. Timers created through this method // should be released through the ReleaseDumpTimer method. private PrecisionTimer CreateDumpTimer() { PrecisionTimer dumpTimer = new PrecisionTimer(); dumpTimer.AutoReset = true; dumpTimer.Period = 100; dumpTimer.Tick += DumpTimer_Tick; return dumpTimer; }
/// <summary> /// Opens the stream and starts playback. /// </summary> /// <param name="songName">The name of the song to be played.</param> public void Play(string songName) { if (m_dataSubscriber != null && m_metadata != null) { UnsynchronizedSubscriptionInfo info; StringBuilder filterExpression = new StringBuilder(); DataTable deviceTable = m_metadata.Tables["DeviceDetail"]; DataTable measurementTable = m_metadata.Tables["MeasurementDetail"]; Dictionary <string, string> uriSettings; string dataChannel = null; int uriIndex = ConnectionUri.IndexOf(URI_SEPARATOR); m_channelIndexes = new ConcurrentDictionary <Guid, int>(); m_sampleRate = DEFAULT_SAMPLE_RATE; m_numChannels = DEFAULT_NUM_CHANNELS; // Get sample rate from metadata. if (deviceTable != null) { string sampleRate = deviceTable.Rows.Cast <DataRow>() .Single(row => row["Acronym"].ToNonNullString() == songName)["FramesPerSecond"].ToNonNullString(); if (!string.IsNullOrEmpty(sampleRate)) { m_sampleRate = int.Parse(sampleRate); } } // Get measurements from metadata. if (measurementTable != null) { IEnumerable <DataRow> measurementRows = measurementTable.Rows.Cast <DataRow>() .Where(row => row["DeviceAcronym"].ToNonNullString() == songName) .Where(row => row["SignalAcronym"].ToNonNullString() == "ALOG" || row["SignalAcronym"].ToNonNullString() == "VPHM") .Where(row => row["Enabled"].ToNonNullString().ParseBoolean()) .OrderBy(row => row["ID"].ToNonNullString()); m_numChannels = 0; foreach (DataRow row in measurementRows) { Guid measurementID = Guid.Parse(row["SignalID"].ToNonNullString()); if (m_numChannels > 0) { filterExpression.Append(';'); } filterExpression.Append(measurementID); m_channelIndexes[measurementID] = m_numChannels; m_numChannels++; } } // Create UDP data channel if specified. if (uriIndex >= 0) { uriSettings = ConnectionUri.Substring(uriIndex + URI_SEPARATOR.Length).ParseKeyValuePairs('&'); if (uriSettings.ContainsKey("udp")) { dataChannel = string.Format("dataChannel={{port={0}; interface={1}}}", uriSettings["udp"], IPv6Enabled ? "::0" : "0.0.0.0"); } } m_buffer = new ConcurrentQueue <IMeasurement>(); m_dumpTimer = CreateDumpTimer(); m_statTimer = CreateStatTimer(); m_waveProvider = new BufferedWaveProvider(new WaveFormat(m_sampleRate < MINIMUM_SAMPLE_RATE ? MINIMUM_SAMPLE_RATE : m_sampleRate, m_numChannels)); m_wavePlayer = CreateWavePlayer(m_waveProvider); m_waveProvider.DiscardOnBufferOverflow = true; info = new UnsynchronizedSubscriptionInfo(false) { FilterExpression = filterExpression.ToString(), ExtraConnectionStringParameters = dataChannel }; m_statTimer.Start(); m_wavePlayer.Play(); m_dataSubscriber.UnsynchronizedSubscribe(info); m_timeoutTimer.Start(); OnStateChanged(PlaybackState.Buffering); } }
/// <summary> /// Releases the unmanaged resources used by the <see cref="PrecisionInputTimer"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> private void Dispose(bool disposing) { if (!m_disposed) { try { if (disposing) { if (m_timer != null) { m_timer.Tick -= m_timer_Tick; m_timer.Dispose(); } m_timer = null; if (m_frameWaitHandleA != null) { m_frameWaitHandleA.Set(); m_frameWaitHandleA.Dispose(); } m_frameWaitHandleA = null; if (m_frameWaitHandleB != null) { m_frameWaitHandleB.Set(); m_frameWaitHandleB.Dispose(); } m_frameWaitHandleB = null; } } finally { m_disposed = true; // Prevent duplicate dispose. } } }
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>(); }
// start capturing public void startCapture(ManagedPGRGuid camGuid, int vidMode,System.Windows.Forms.PictureBox displayPicture, String fileName,Boolean record2file) { int i; Flag_GravityFound_Y = false; // garvity is not known // CLEARING THE FRAME QUEUE NO MATTER WHAT... FrameQueue.clear(); RecordToFile = record2file; // creating the GPS data list GpsCaptureData = new List<GPSDataInstance>(); // creating the IMU data List IMUCapturedata = new List<IMUDataInstance>(); // resetting frame index FrameIndex = 0; // 1. connect to the camera Cam.Connect(camGuid); int fps_i = 0; if (vidMode == 0) { Cam.SetVideoModeAndFrameRate(VideoMode.VideoMode1600x1200Yuv422, FrameRate.FrameRate30); fps_i = 30; } else if (vidMode == 1) { Cam.SetVideoModeAndFrameRate(VideoMode.VideoMode1600x1200Rgb, FrameRate.FrameRate15); fps_i = 15; } else if (vidMode == 2) { Format7ImageSettings fset = new Format7ImageSettings(); fset.height = 540; fset.width = 960; fset.offsetX = 40; fset.offsetY = 118; fset.mode = Mode.Mode4; fset.pixelFormat = PixelFormat.PixelFormatRgb8; Cam.SetFormat7Configuration(fset, 40.0f); // this equivalent to 24 fps fps_i = 24; } if (RecordToFile) { // 3. Creating the avi recorder object AviRecorder = new ManagedAVIRecorder(); MJPGOption option = new MJPGOption(); float fps = (float)fps_i; option.frameRate = fps; option.quality = 100; // 100 for superb quality AviRecorder.AVIOpen(fileName, option); } // 4. setting the frame buffering option // leave it for now... // 5. start the capturing Cam.StartCapture(); // MUST discard the first few frames! ManagedImage rawImage = new ManagedImage(); for (i = 0; i < 10; i++) { Cam.RetrieveBuffer(rawImage); } // 6. set the display bitmap DisplayPicture = displayPicture; // 7. starting sampling, recording and dumping threads // IMU sampling thread IMUSamplingTimer = new PrecisionTimer(.0075, this.IMUSamplingEvent); // sampling frequency at 150 Hz RecordingThreadActive = true; OutOfRecordingThread = true; IMUSamplingTimer.start(); RecordingThread = new Thread(this.mainLoop); //RecordingThread.Priority = ThreadPriority.Highest; RecordingThread.Start(); // creating the thread for the dumping DumpingThread = new System.Threading.Thread(this.dumpingLoop); while (OutOfRecordingThread); // must wait until the recording thread enters the loop, otherwise the dumping will never start! DumpingThread.Start(); }
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 override uint GetPrecisionTime() { return PrecisionTimer.GetCurrentTime(); }
/// <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(); }