Esempio n. 1
0
        private void SendByte(byte data)
        {
            // Send one bit at a time, starting with the MSB
            for (byte i = 0; i < 8; i++)
            {
                // If MSB is 1, write one and clock it, else write 0 and clock
                if ((data & 0x80) != 0)
                {
                    dataPin.Write(true);
                }
                else
                {
                    dataPin.Write(false);
                }

                // clk():
                clockPin.Write(false);
                HighResolutionTimer.Sleep(0.02m);
                clockPin.Write(true);
                HighResolutionTimer.Sleep(0.02m);

                // Advance to the next bit to send
                data <<= 1;
            }
        }
Esempio n. 2
0
 /// <summary>
 ///     Dibuja el contador de FPS si esta activo
 /// </summary>
 protected void RenderFPS()
 {
     if (FPS)
     {
         DrawText.drawText(HighResolutionTimer.FramesPerSecondText(), 0, 0, Color.Yellow);
     }
 }
Esempio n. 3
0
        public void MultipleSamples()
        {
            HighResolutionTimer timer = new HighResolutionTimer();

            TimerSample sample1      = HighResolutionTimer.Sample();
            double      elapsedTime1 = Wait();
            TimerSample sample2      = HighResolutionTimer.Sample();
            double      elapsedTime2 = Wait();
            TimerSample sample3      = HighResolutionTimer.Sample();

            double duration1 = HighResolutionTimer.Duration(sample1, sample2) * TimeToMilliseconds;

            Console.WriteLine("1 -> DateTime time: {0:N3}, Timer time: {1:N3}", elapsedTime1, duration1);

            Assert.Between(
                duration1,
                elapsedTime1 * (1.0 - Variation),
                elapsedTime1 * (1.0 + Variation)
                );

            double duration2 = HighResolutionTimer.Duration(sample2, sample3) * TimeToMilliseconds;

            Console.WriteLine("2 -> DateTime time: {0:N3}, Timer time: {1:N3}", elapsedTime2, duration2);

            Assert.Between(
                duration2,
                elapsedTime1 * (1.0 - Variation),
                elapsedTime1 * (1.0 + Variation)
                );
        }
Esempio n. 4
0
        public void ConvertTime()
        {
            HighResolutionTimer timer = new HighResolutionTimer();

            timer.Start();
            Wait();
            timer.Stop();

            double duration = timer.Duration(1);

            Assert.Between(
                HighResolutionTimer.TimeToMilliseconds(duration),
                duration * TimeToMilliseconds * (1.0 - Variation),
                duration * TimeToMilliseconds * (1.0 + Variation)
                );
            Assert.Between(
                HighResolutionTimer.TimeToSeconds(duration),
                duration * TimeToSeconds * (1.0 - Variation),
                duration * TimeToSeconds * (1.0 + Variation)
                );
            Assert.Between(
                HighResolutionTimer.TimeToTimeSpan(duration).TotalSeconds,
                duration * TimeToSeconds * (1.0 - Variation),
                duration * TimeToSeconds * (1.0 + Variation)
                );
        }
Esempio n. 5
0
 public SequenceExecutor()
 {
     _endCheckTimer = new HighResolutionTimer(10f);
     _endCheckTimer.UseHighPriorityThread = false;
     _endCheckTimer.Elapsed += _EndCheckTimerElapsed;
     _syncContext            = AsyncOperationManager.SynchronizationContext;
 }
Esempio n. 6
0
        private ushort GetRawTemperature()
        {
            WriteByte(Interop.CONTROL, Interop.READTEMPCMD);
            HighResolutionTimer.Sleep(lowDelay);

            return(ReadUInt16(Interop.TEMPDATA));
        }
Esempio n. 7
0
        private uint GetRawPressure()
        {
            WriteByte(Interop.CONTROL, (byte)(Interop.READPRESSURECMD + ((int)precision << 6)));

            switch (precision)
            {
            case Bmp085Precision.Low:
                HighResolutionTimer.Sleep(lowDelay);
                break;

            case Bmp085Precision.High:
                HighResolutionTimer.Sleep(highDelay);
                break;

            case Bmp085Precision.Highest:
                HighResolutionTimer.Sleep(highestDelay);
                break;

            default:
                HighResolutionTimer.Sleep(defaultDelay);
                break;
            }

            var msb  = ReadByte(Interop.PRESSUREDATA);
            var lsb  = ReadByte(Interop.PRESSUREDATA + 1);
            var xlsb = ReadByte(Interop.PRESSUREDATA + 2);
            var raw  = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - (int)precision);

            return((uint)raw);
        }
Esempio n. 8
0
        public Sender(Log log, Statistics statistics, ProgramConfiguration programConfiguration)
            : base(log, programConfiguration)
        {
            var destinationEndPoint =
                new IPEndPoint(_programConfiguration.DestinationIpAddress, programConfiguration.DestinationPort);

            _networkProtocol =
                new UdpNetworkProtocol(
                    log, statistics, destinationEndPoint, UdpNetworkProtocolType.Udp, _programConfiguration.PacketSize,
                    _programConfiguration.VerifyOrder);

            _sendDataTask =
                new HighResolutionTimer
            {
                Mode       = TimerMode.Periodic,
                Period     = 1000,
                Resolution = 0,
                IsAsync    = true
            };

            _sendDataTask.Tick += (sender, args) => SendData();

            var bindedIp =
                MachineAddress.FirstOrDefault(i => i.Equals(_programConfiguration.SourceIpAddress)) ?? IPAddress.Any;

            var bindedPort = programConfiguration.SourcePort ?? 0;

            _networkProtocol.Bind(new IPEndPoint(bindedIp, bindedPort));

            if (programConfiguration.NetworkBufferSize.HasValue)
            {
                _networkProtocol.SetSendBufferSize(programConfiguration.NetworkBufferSize.Value);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        private void Run()
        {
            var timer           = new HighResolutionTimer();
            var lastElapsedTime = TimeSpan.FromSeconds(0);

            while (IsRunning)
            {
                if (lastElapsedTime < ReadTime)
                {
                    Thread.Sleep(ReadTime - lastElapsedTime);
                }

                timer.Start();

                var sensorData = RetrieveSensorData();
                lastElapsedTime = timer.Elapsed;

                if (IsRunning)
                {
                    DataAvailable?.Invoke(this, sensorData);
                }

                timer.Reset();
            }

            SetSleepMode(true);
        }
Esempio n. 10
0
 public static void GameLoop()
 {
     m_timer     = new HighResolutionTimer(1);
     m_stopwatch = new Stopwatch();
     m_stopwatch.Start();
     m_timer.Elapsed += OnTick;
     m_timer.Start();
 }
Esempio n. 11
0
        /// <summary>
        /// Starts sensor reading.
        /// </summary>
        public void Start()
        {
            TriggerPin.PinMode = GpioPinDriveMode.Output;
            EchoPin.PinMode    = GpioPinDriveMode.Input;

            measurementTimer = new HighResolutionTimer();
            IsRunning        = true;
            ReadWorker.Start();
        }
Esempio n. 12
0
        private void PlayGif(FFGifDrawable gifDrawable, CancellationTokenSource tokenSource)
        {
            var token          = tokenSource.Token;
            var animatedImages = gifDrawable.AnimatedImages;

            _animationTimer?.Stop();
            _animationTimer = new HighResolutionTimer <Android.Graphics.Bitmap>(gifDrawable.AnimatedImages, async(image) =>
            {
                if (_animationFrameSetting)
                {
                    return;
                }

                _animationFrameSetting = true;

                try
                {
                    var bitmap = image.Image;

                    if (_isDisposed || !_animationTimer.Enabled)
                    {
                        return;
                    }

                    if (bitmap != null && bitmap.Handle != IntPtr.Zero && !bitmap.IsRecycled)
                    {
                        if (_isDisposed || !_animationTimer.Enabled)
                        {
                            return;
                        }

                        await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() =>
                        {
                            if (_isDisposed || !_animationTimer.Enabled)
                            {
                                return;
                            }

                            base.SetImageBitmap(bitmap);
                            ;
                        }).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    ImageService.Instance.Config.Logger.Error("GIF", ex);
                }
                finally
                {
                    _animationFrameSetting = false;
                }
            })
            {
                DelayOffset = -2
            };
            _animationTimer.Start();
        }
Esempio n. 13
0
 private void LatchData()
 {
     dataPin.Write(false);
     HighResolutionTimer.Sleep(delay);
     for (int i = 0; i < 4; i++)
     {
         dataPin.Write(true);
         dataPin.Write(false);
     }
 }
        /// <summary>
        /// Senses the distance.
        /// </summary>
        public void SenseDistance()
        {
            var timer = new HighResolutionTimer();
            this.EnsureReady();

            _timer = new Stopwatch();
            _trigPin.Write(GpioPinValue.High);
            timer.Sleep(0.01d);
            _trigPin.Write(GpioPinValue.Low);
        }
Esempio n. 15
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_endCheckTimer != null)
         {
             _endCheckTimer.Elapsed -= _EndCheckTimerElapsed;
             _endCheckTimer          = null;
         }
     }
     _endCheckTimer = null;
     _syncContext   = null;
 }
Esempio n. 16
0
 private void InitializeTimer()
 {
     //Console.WriteLine($"IsHighResolution = {HighResolutionTimer.IsHighResolution}");
     //Console.WriteLine($"Tick time length = {HighResolutionTimer.TickLength} [ms]");
     // UseHighPriorityThread = true, sets the execution thread to ThreadPriority.Highest.
     // It doesn't provide any precision gain in most of the cases and may do things worse for other threads.
     // It is suggested to do some studies before setting it true
     _Timer = new HighResolutionTimer(30.0f) // in msec
     {
         UseHighPriorityThread = false
     };
     _Timer.Elapsed += Timer_Elapsed;
 }
Esempio n. 17
0
        private static void PlayAnimation(ImageView control, ISelfDisposingAnimatedBitmapDrawable drawable)
        {
            lock (_runningAnimations)
            {
                var hashCode = control.GetHashCode();

                var timer = new HighResolutionTimer <ISelfDisposingAnimatedBitmapDrawable>(drawable, async(t, bitmap) =>
                {
                    try
                    {
                        try
                        {
                            if (control == null || control.Handle == IntPtr.Zero ||
                                !drawable.IsValidAndHasValidBitmap())
                            {
                                StopAnimation(control);
                                return;
                            }

                            await ImageService.Instance.Config.MainThreadDispatcher.PostAsync(() =>
                            {
                                if (control == null || control.Handle == IntPtr.Zero ||
                                    !drawable.IsValidAndHasValidBitmap())
                                {
                                    StopAnimation(control);
                                    return;
                                }

                                control.SetImageBitmap(bitmap);
                            });
                        }
                        catch (ObjectDisposedException)
                        {
                            StopAnimation(control);
                        }
                    }
                    catch (Exception ex)
                    {
                        ImageService.Instance.Config.Logger.Error("GIF", ex);
                    }
                })
                {
                    DelayOffset = -2
                };

                _runningAnimations.Add(control, timer);

                timer.Start();
            }
        }
Esempio n. 18
0
        public VariableViewForm()
        {
            InitializeComponent();
            RefreshComPorts();

            valuesUpdater = new SerialPortUpdater();

            displayTimer = new HighResolutionTimer(200.0f);
            displayTimer.UseHighPriorityThread = false;
            displayTimer.Elapsed += displayTimer_Elapsed;

            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            DoubleBuffered = true;
        }
        /// <summary>
        /// Sets the pin resistor.
        /// </summary>
        /// <param name="pin">The pin.</param>
        /// <param name="resistor">The resistor.</param>
        public void SetPinResistor(ProcessorPin pin, PinResistor resistor)
        {
            // Set the pullup/down resistor for a pin
            //
            // The GPIO Pull-up/down Clock Registers control the actuation of internal pull-downs on
            // the respective GPIO pins. These registers must be used in conjunction with the GPPUD
            // register to effect GPIO Pull-up/down changes. The following sequence of events is
            // required:
            // 1. Write to GPPUD to set the required control signal (i.e. Pull-up or Pull-Down or neither
            // to remove the current Pull-up/down)
            // 2. Wait 150 cycles ? this provides the required set-up time for the control signal
            // 3. Write to GPPUDCLK0/1 to clock the control signal into the GPIO pads you wish to
            // modify ? NOTE only the pads which receive a clock will be modified, all others will
            // retain their previous state.
            // 4. Wait 150 cycles ? this provides the required hold time for the control signal
            // 5. Write to GPPUD to remove the control signal
            // 6. Write to GPPUDCLK0/1 to remove the clock
            //
            // RPi has P1-03 and P1-05 with 1k8 pullup resistor

            uint pud;

            switch (resistor)
            {
            case PinResistor.None:
                pud = Interop.BCM2835_GPIO_PUD_OFF;
                break;

            case PinResistor.PullDown:
                pud = Interop.BCM2835_GPIO_PUD_DOWN;
                break;

            case PinResistor.PullUp:
                pud = Interop.BCM2835_GPIO_PUD_UP;
                break;

            default:
                throw new ArgumentOutOfRangeException("resistor", resistor, string.Format(CultureInfo.InvariantCulture, "{0} is not a valid value for pin resistor", resistor));
            }

            WriteResistor(pud);
            HighResolutionTimer.Sleep(resistorSetDelay);
            SetPinResistorClock(pin, true);
            HighResolutionTimer.Sleep(resistorSetDelay);
            WriteResistor(Interop.BCM2835_GPIO_PUD_OFF);
            SetPinResistorClock(pin, false);

            pinResistors[pin] = PinResistor.None;
        }
Esempio n. 20
0
        public SinglePrecisionDataChannel(int samplesPerSecond, int bufferSize)
        {
            HighResolutionTimer hrt = new HighResolutionTimer();

            this.ChannelId = (int)(hrt.Value % Int32.MaxValue);
            System.Threading.Thread.Sleep(1);

            this.SamplesPerSecond = samplesPerSecond;
            this.BufferSize       = bufferSize;

            this.Data       = new float[bufferSize];
            this.Labels     = new string[bufferSize];
            this.TimeStamps = new DateTime[bufferSize];
            this.Quality    = new float[bufferSize];
        }
Esempio n. 21
0
        /// <summary>
        /// Performs the continuous reads of the sensor.
        /// This method represents the body of the worker.
        /// </summary>
        private void PerformContinuousReads()
        {
            var stopwatch       = new HighResolutionTimer();
            var lastElapsedTime = TimeSpan.FromSeconds(0);

            while (IsRunning)
            {
                try
                {
                    // Start to comunicate with sensor
                    // Inform sensor that must finish last execution and put it's state in idle
                    DataPin.PinMode = GpioPinDriveMode.Output;

                    // Waiting for sensor init
                    DataPin.Write(GpioPinValue.High);
                    if (lastElapsedTime < ReadInterval)
                    {
                        Thread.Sleep(ReadInterval - lastElapsedTime);
                    }

                    // Start to counter measure time
                    stopwatch.Start();

                    // Send request to trasmission from board to sensor
                    DataPin.Write(GpioPinValue.Low);
                    Pi.Timing.SleepMicroseconds(1000);
                    DataPin.Write(GpioPinValue.High);
                    Pi.Timing.SleepMicroseconds(20);
                    DataPin.Write(GpioPinValue.Low);

                    // Acquire measure
                    var sensorData = RetrieveSensorData();
                    OnDataAvailable?.Invoke(this, sensorData);
                }
                catch
                {
                    // swallow
                }

                lastElapsedTime = stopwatch.Elapsed;
                if (stopwatch.IsRunning)
                {
                    stopwatch.Stop();
                }

                stopwatch.Reset();
            }
        }
Esempio n. 22
0
        public void MeasureCallTime()
        {
            // Warm up
            HighResolutionTimer.Sample();

            TimerSample start = HighResolutionTimer.Sample();
            TimerSample end   = HighResolutionTimer.Sample();

            Console.WriteLine(HighResolutionTimer.Duration(start, end));

            HighResolutionTimer timer = new HighResolutionTimer();

            timer.Start();
            timer.Stop();
            Console.WriteLine(timer.Duration(1));
        }
Esempio n. 23
0
        /// <summary>
        /// Initializes a new instance of a <see cref="ComponentTraceEventProvider"/> object using the specified provider name and its unique identity.
        /// </summary>
        /// <param name="providerName">The name of the tracing provider.</param>
        /// <param name="providerGuid">The unique ID of the tracing provider.</param>
        public ComponentTraceEventProvider(string providerName, Guid providerGuid)
        {
            Guard.ArgumentNotNullOrEmptyString(providerName, "providerName");
            Guard.ArgumentNotDefaultValue <Guid>(providerGuid, "providerGuid");

            this.state        = TraceEventProviderState.Initializing;
            this.providerName = providerName;
            this.providerGuid = providerGuid;
            this.highResTimer = new HighResolutionTimer();

            // Configure the trace listener and default trace options.
            this.debugTraceProvider              = new TraceSource(providerName, SourceLevels.All);
            this.debugTraceProvider.Switch       = new SourceSwitch(providerName);
            this.debugTraceProvider.Switch.Level = SourceLevels.All;
            this.debugTraceProvider.Listeners.Add(new DefaultTraceListener());
        }
Esempio n. 24
0
            public double GetData()
            {
                Connection.Write(0x10);
                HighResolutionTimer.Sleep(TimeSpanUtility.FromMicroseconds(150 * 1000));
                byte[] readBuf = Connection.Read(2);

                var valf = readBuf[0] << 8;

                valf |= readBuf[1];
                return(valf / 1.2 * (69 / 69) / 1);

                // var valf = ((readBuf[0] << 8) | readBuf[1]) / 1.2;
                // return valf;

                // return Math.Round(valf / (2 * 1.2), 2);
            }
Esempio n. 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="StoredProcedure"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="connectionInfo">The cached connection string information.</param>
        private StoredProcedure(string name, ConnectionInfo connectionInfo)
        {
            this.connectionInfo = connectionInfo;

            DbCommand dbCommand = connectionInfo.ProviderFactory.CreateCommand();

            dbCommand.CommandText = name;
            dbCommand.CommandType = CommandType.StoredProcedure;
            commandWrapper        = new CommandWrapper(dbCommand, connectionInfo.ProviderFactory);

#if (DEBUG)
            timer = new HighResolutionTimer();
            // Build the timer
            timer.Start();
            timer.Stop();
#endif
        }
Esempio n. 26
0
 public void Stop()
 {
     if (timer == null)
     {
         return;
     }
     lock (mutex)
     {
         if (timer == null)
         {
             return;
         }
         timer.Stop();
         timer.Elapsed -= OnTick;
         timer          = null;
     }
 }
Esempio n. 27
0
        private void GetMeasure()
        {
            var hrt             = new HighResolutionTimer();
            var lastElapsedTime = TimeSpan.FromSeconds(0);

            while (_started)
            {
                try
                {
                    THData measure = null;
                    //Start to comunicate with sensor
                    //Inform sensor that must finish last execution and put it's state in idle
                    _pin.PinMode = GpioPinDriveMode.Output;

                    //Waiting for sensor init
                    _pin.Write(GpioPinValue.High);
                    if (lastElapsedTime < _measureTime)
                    {
                        Thread.Sleep(_measureTime - lastElapsedTime);
                    }

                    //Start to counter measure time
                    hrt.Start();
                    //Send request to trasmission from board to sensor
                    _pin.Write(GpioPinValue.Low);
                    _timing.SleepMicroseconds(1000);
                    _pin.Write(GpioPinValue.High);
                    _timing.SleepMicroseconds(20);
                    _pin.Write(GpioPinValue.Low);

                    //Acquire measure
                    measure = TryGetMeasure();
                    OnSensorRead(measure);
                }
                catch
                {
                    //ignored
                }
                lastElapsedTime = hrt.Elapsed;
                if (hrt.IsRunning)
                {
                    hrt.Stop();
                }
                hrt.Reset();
            }
        }
Esempio n. 28
0
 public void Start()
 {
     if (timer != null)
     {
         return;
     }
     lock (mutex)
     {
         if (timer != null)
         {
             return;
         }
         timer          = new HighResolutionTimer(intervalInMilliseconds);
         timer.Elapsed += OnTick;
         ellapsedTicks  = 0;
         timer.Start();
     }
 }
Esempio n. 29
0
        public void StartStop()
        {
            HighResolutionTimer timer = new HighResolutionTimer();

            timer.Start();
            double elapsedTime = Wait();

            timer.Stop();

            double duration = timer.Duration(1) * TimeToMilliseconds;

            Console.WriteLine("DateTime time: {0:N3}, Timer time: {1:N3}", elapsedTime, duration);

            Assert.Between(
                duration,
                elapsedTime * (1.0 - Variation),
                elapsedTime * (1.0 + Variation)
                );
        }
Esempio n. 30
0
        public TgcExample(string mediaDir, string shadersDir)
        {
            //TgcAxisLines axisLines, TgcCamera camara
            MediaDir            = mediaDir;
            ShadersDir          = shadersDir;
            AxisLines           = new TgcAxisLines();
            AxisLinesEnable     = true;
            FPS                 = true;
            Camara              = new TgcCamera();
            ElapsedTime         = -1;
            HighResolutionTimer = new HighResolutionTimer();
            Frustum             = new TgcFrustum();
            //DirectSound = new TgcDirectSound(); Por ahora se carga por afuera
            DrawText = new TgcText2D();
            Input    = new TgcD3dInput();

            Category    = "Others";
            Name        = "Ejemplo en Blanco";
            Description = "Ejemplo en Blanco. Es hora de empezar a hacer tu propio ejemplo :)";
        }
Esempio n. 31
0
        /// <summary>
        /// Crea un ejemplo con lo necesario para realizar un juego.
        /// </summary>
        /// <param name="mediaDir">Ruta donde estan los Media.</param>
        /// <param name="shadersDir">Ruta donde estan los Shaders.</param>
        public TGCExample(string mediaDir, string shadersDir)
        {
            MediaDir           = mediaDir;
            ShadersDir         = shadersDir;
            AxisLines          = new TgcAxisLines();
            AxisLinesEnable    = true;
            FPSText            = true;
            TimeBetweenRenders = 1F / FPS_60;
            TimeBetweenUpdates = 1F / FPS_60;
            LastRenderTime     = 0;
            LastUpdateTime     = 0;
            ElapsedTime        = -1;
            Camera             = new TgcCamera();
            Timer   = new HighResolutionTimer();
            Frustum = new TgcFrustum();
            //DirectSound = new TgcDirectSound(); Por ahora lo carga el Model
            DrawText = new TgcText2D();
            //Input = new TgcD3dInput(); Por ahora lo carga el Model
            BackgroundColor = DefaultClearColor;

            Category    = "Others";
            Name        = "Ejemplo en Blanco";
            Description = "Ejemplo en Blanco. Es hora de empezar a hacer tu propio ejemplo :)";
        }