Пример #1
0
        void SetDataRate(DataRate speed)
        {
            txDelay = 85;

            byte setup = ReadRegister(RF_SETUP);

            switch (speed)
            {
            case DataRate.RF24_1MBPS:
                setup &= (byte)~(1 << RF_DR_LOW);      // 0
                setup &= (byte)~(1 << RF_DR_HIGH);     // 0
                break;

            case DataRate.RF24_2MBPS:
                setup &= (byte)~(1 << RF_DR_LOW);      // 0
                setup |= (byte)(1 << RF_DR_HIGH);      // 1
                break;

            case DataRate.RF24_250KBPS:
                setup |= (byte)(1 << RF_DR_LOW);        // 1
                setup &= (byte)~(1 << RF_DR_HIGH);      // 0
                break;

            default:
                throw new ArgumentOutOfRangeException("DataRate", speed, "An invalid DataRate was specified");
            }

            WriteRegister(RF_SETUP, setup);
        }
Пример #2
0
        public void Choke_ProvidesExpectedRate(int speedBytesPerSecond, int testDurationSeconds, double stepSizeMs, int requestSize)
        {
            // Choke algorithm deliberately rounds speeds down when fractions are encountered, to avoid overspeed.
            const int tolerancePackets = 3;

            var startTime   = DateTimeOffset.UtcNow;
            var currentTime = startTime;

            _timeSource.GetCurrentTime().Returns(ci => currentTime);

            var bytesAllowed = 0;

            var choke = new Choke(DataRate.FromBytesPerSecond(speedBytesPerSecond), new TimeSourceStopwatch(_timeSource));

            for (double i = 0; i < testDurationSeconds * 1000; i += stepSizeMs)
            {
                // Every N milliseconds we request more data.
                while (choke.RequestBytes((ushort)requestSize))
                {
                    bytesAllowed += requestSize;
                }

                currentTime = startTime.AddMilliseconds(i);
            }

            Assert.AreEqual(speedBytesPerSecond * testDurationSeconds + choke.BucketSizeBytes, bytesAllowed, delta: requestSize * tolerancePackets);
        }
 public void SetDataRate(DataRate value)
 {
     byte[] register = Read(CtrlReg1, 1);
     register[0] = value == DataRate.F100Hz
                       ? Disable(register[0], 0x80)
                       : Enable(register[0], 0x80);
     Write(CtrlReg1, register[0]);
 }
Пример #4
0
 public void SetDataRate(DataRate value)
 {
     byte[] register = Read(CtrlReg1, 1);
     register[0] = value == DataRate.F100Hz
                       ? Disable(register[0], 0x80)
                       : Enable(register[0], 0x80);
     Write(CtrlReg1, register[0]);
 }
Пример #5
0
        /// <summary>
        /// アナログ値(バイナリ)を取得する。
        /// </summary>
        /// <param name="mux">入力マルチプレクサ</param>
        /// <param name="dataRate">データーレート</param>
        /// <param name="pga">ゲイン</param>
        /// <returns>アナログ値(バイナリ)</returns>
        public int ReadRaw(Mux mux, DataRate dataRate = DataRate.Sps128, Pga pga = Pga.Fs2048mV)
        {
            ReadOnlySpan <byte> config = stackalloc byte[]
            {
                (byte)Register.Config,
                (byte)(((byte)SingleShotCoversion.Begin << 7) | ((byte)mux << 4) | ((byte)pga << 1) | (byte)Mode.PowerDownSingleShot),
                (byte)(((byte)dataRate << 5) | (byte)ComparatorQueue.Disable)
            };

            Write(config);
            ReadOnlySpan <byte> conversion = stackalloc byte[] { (byte)Register.Conversion };

            WriteEx(I2cMasterFlags.Start, conversion);
            switch (dataRate)
            {
            case DataRate.Sps8:
                Thread.Sleep(126);
                break;

            case DataRate.Sps16:
                Thread.Sleep(64);
                break;

            case DataRate.Sps32:
                Thread.Sleep(33);
                break;

            case DataRate.Sps64:
                Thread.Sleep(17);
                break;

            case DataRate.Sps128:
                Thread.Sleep(9);
                break;

            case DataRate.Sps250:
                Thread.Sleep(5);
                break;

            case DataRate.Sps475:
                Thread.Sleep(4);
                break;

            case DataRate.Sps860:
                Thread.Sleep(3);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(dataRate));
            }

            Span <byte> readBuffer = stackalloc byte[2];

            ReadEx(I2cMasterFlags.RepeatedStart | I2cMasterFlags.Stop, readBuffer);
            return((short)((readBuffer[0] << 8) | readBuffer[1]));
        }
    }
}
Пример #6
0
        /// <summary>
        /// Copy raw data from data block into array.
        /// </summary>
        /// <param name="rawDataArray">Array for raw data.</param>
        /// <param name="dataRate">Data rate (High, Medium, or Low).</param>
        public void CopyRawDataToArray(ushort[] rawDataArray, DataRate dataRate, bool rawDataMode)
        {
            int i;

            for (i = 0; i < Constant.FrameSize(dataRate, rawDataMode) * Constant.FramesPerBlock; i++)
            {
                rawDataArray[i] = (ushort)(rawData[i]);
            }
        }
        public void Equals_objects_should_work_correctly()
        {
            var val1 = new DataRate(10);
            var val2 = (object)new DataRate(10);
            var val3 = (object)new DataRate(20);
            var val4 = (object)val1;

            val1.Equals(val2).Should().BeTrue();
            val1.Equals(val3).Should().BeFalse();
            val1.Equals(val4).Should().BeTrue();
        }
Пример #8
0
 public void ReadFromXml(XmlTextReader xml)
 {
     Drive              = (Drive)Enum.Parse(typeof(Drive), xml.GetAttribute("Drive"));
     DataRate           = (DataRate)Enum.Parse(typeof(DataRate), xml.GetAttribute("DataRate"));
     Side               = (DiskSide)Enum.Parse(typeof(DiskSide), xml.GetAttribute("Side"));
     ReadMode           = (ReadMode)Enum.Parse(typeof(ReadMode), xml.GetAttribute("ReadMode"));
     SectorReadAttempts = Math.Max(0, int.Parse(xml.GetAttribute("SectorReadAttempts")));
     FirstTrack         = Math.Max(0, int.Parse(xml.GetAttribute("FirstTrack")));
     FirstTrack         = Math.Min(171, FirstTrack);
     LastTrack          = Math.Min(172, int.Parse(xml.GetAttribute("LastTrack")));
     LastTrack          = Math.Max(0, LastTrack);
 }
Пример #9
0
        /// <inheritdoc/>
        public List <int> ReadRaw(int startChannel, int numOfChannels, DataRate dataRate = DataRate.Sps128, Pga pga = Pga.Fs10035mV)
        {
            var values = new List <int>();

            for (var ch = startChannel; ch < startChannel + numOfChannels; ch++)
            {
                var tmp = ReadRaw(ch, dataRate, pga);
                values.Add(tmp);
            }

            return(values);
        }
        public void Operator_div_should_work_correctly()
        {
            var    val1  = new DataRate(30);
            int    val2I = 2;
            long   val2L = 2;
            double val2D = 2;
            var    res   = 15;

            (val1 / val2I).Should().Be(new DataRate(res));
            (val1 / val2L).Should().Be(new DataRate(res));
            (val1 / val2D).Should().Be(new DataRate(res));
        }
Пример #11
0
        /// <summary>
        /// Set Send Rate
        /// </summary>
        /// <param name="rate">Send Rate</param>
        public void SetDataRate(DataRate rate)
        {
            ce.Write(GpioPinValue.Low);

            byte[] value = new byte[1];
            sensor.TransferSequential(new byte[] { R_REGISTER + RF_SETUP }, value);

            byte setting = (byte)(value[0] & (~0x08) | ((byte)rate << 1));

            sensor.Write(new byte[] { W_REGISTER + RF_SETUP, setting });

            ce.Write(GpioPinValue.High);
        }
Пример #12
0
        /// <summary>
        /// Initialize a new Ads1115 device connected through I2C with an additional GPIO controller for interrupt handling.
        /// </summary>
        /// <param name="i2cDevice">The I2C device used for communication.</param>
        /// <param name="gpioController">The GPIO Controller used for interrupt handling</param>
        /// <param name="gpioInterruptPin">The pin number where the interrupt line is attached on the GPIO controller</param>
        /// <param name="shouldDispose">True (the default) if the GPIO controller shall be disposed when disposing this instance</param>
        /// <param name="inputMultiplexer">Input Multiplexer</param>
        /// <param name="measuringRange">Programmable Gain Amplifier</param>
        /// <param name="dataRate">Data Rate</param>
        /// <param name="deviceMode">Initial device mode</param>
        public Ads1115(I2cDevice i2cDevice,
                       GpioController?gpioController, int gpioInterruptPin, bool shouldDispose = true, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096,
                       DataRate dataRate = DataRate.SPS128, DeviceMode deviceMode = DeviceMode.Continuous)
            : this(i2cDevice, inputMultiplexer, measuringRange, dataRate, deviceMode)
        {
            _gpioController = gpioController ?? new GpioController();
            if (gpioInterruptPin < 0 || gpioInterruptPin >= _gpioController.PinCount)
            {
                throw new ArgumentOutOfRangeException(nameof(gpioInterruptPin), $"The given GPIO Controller has no pin number {gpioInterruptPin}");
            }

            _gpioInterruptPin = gpioInterruptPin;
            _shouldDispose    = shouldDispose || gpioController is null;
        }
Пример #13
0
        /// <summary>
        /// Set Send Rate
        /// </summary>
        /// <param name="rate">Send Rate</param>
        public bool SetDataRate(DataRate rate)
        {
            bool result = false;

            byte setting = ReadRegister(RF_SETUP);

            setting  = (byte)(setting & ~((byte)DataRate.DR250Kbps | (byte)DataRate.DR2Mbps));
            setting |= (byte)rate;
            WriteRegister(RF_SETUP, setting);

            result = ReadRegister(RF_SETUP) == setting;

            return(result);
        }
Пример #14
0
        public void Initialize(DataRate ouputDataRate                = DataRate._95Hz,
                               AxisSelection axisSelection           = AxisSelection.All,
                               PowerMode powerMode                   = PowerMode.Active,
                               HighPassFilterMode hpMode             = HighPassFilterMode.Normal,
                               HighPassConfiguration hpConfiguration = HighPassConfiguration.HPConf0,
                               Scale scale         = Scale._0250,
                               LowPass2Mode lpMode = LowPass2Mode.Bypassed)
        {
            // we are setting the 5 control registers in a single SPI write operation
            // by taking advantage on the consecutive write capability
            byte[] configBuffer = new byte[5];

            // control register 1
            configBuffer[0]  = (byte)axisSelection;
            configBuffer[0] |= (byte)powerMode;
            configBuffer[0] |= (byte)ouputDataRate;

            // control register 2
            if (hpMode != HighPassFilterMode.Bypassed)
            {
                configBuffer[1] = (byte)hpConfiguration;
            }

            // control register 3 skipped

            // control register 4
            configBuffer[3] = (byte)scale;
            // TDB
            // block auto-update
            // endianess

            // control register 5
            if (hpMode != HighPassFilterMode.Bypassed)
            {
                // high pass filter enabled
                configBuffer[4] = 0x10;

                if (lpMode != LowPass2Mode.Bypassed)
                {
                    configBuffer[4] |= 0x08 | 0x02;
                }
                else
                {
                    configBuffer[4] |= 0x04 | 0x01;
                }
            }

            WriteOperation(ControlRegister1, configBuffer);
        }
        public void Operator_mul_should_work_correctly()
        {
            var    val1   = new DataRate(30);
            int    val2I  = 2;
            long   val2L  = 2;
            double val2D  = 2;
            var    val2TS = TimeSpan.FromSeconds(2);
            var    res    = 60;

            (val1 * val2I).Should().Be(new DataRate(res));
            (val1 * val2L).Should().Be(new DataRate(res));
            (val1 * val2D).Should().Be(new DataRate(res));
            (val1 * val2TS).Should().Be(new DataSize(res));
            (val2TS * val1).Should().Be(new DataSize(res));
        }
Пример #16
0
        public void Operator_div_should_work_correctly()
        {
            var    val1   = new DataSize(30);
            int    val2I  = 2;
            long   val2L  = 2;
            double val2D  = 2;
            var    val2TS = TimeSpan.FromSeconds(2);
            var    val2DR = DataRate.FromBytesPerSecond(2);
            var    res    = 15;

            (val1 / val2I).Should().Be(new DataSize(res));
            (val1 / val2L).Should().Be(new DataSize(res));
            (val1 / val2D).Should().Be(new DataSize(res));
            (val1 / val2TS).Should().Be(new DataRate(res));
            (val1 / val2DR).Should().Be(new TimeSpan(0, 0, 0, res));
        }
Пример #17
0
        /// <inheritdoc/>
        public int ReadRaw(int channel, DataRate dataRate = DataRate.Sps128, Pga pga = Pga.Fs10035mV)
        {
            if (!IsInitialized)
            {
                Initialize();
            }

            byte extMux;

            Ads1115Slave.Mux adcMux;
            if (channel < 16)
            {
                extMux = (byte)((_mux & 0xf0) | channel);
                adcMux = Ads1115Slave.Mux.Ain0Gnd;
            }
            else if (channel < 32)
            {
                extMux = (byte)((_mux & 0x0f) | ((channel & 0x0f) << 4));
                adcMux = Ads1115Slave.Mux.Ain1Gnd;
            }
            else if (channel < 48)
            {
                extMux = (byte)((_mux & 0xf0) | channel);
                adcMux = Ads1115Slave.Mux.Ain0Ain3;
            }
            else if (channel < 64)
            {
                extMux = (byte)((_mux & 0x0f) | ((channel & 0x0f) << 4));
                adcMux = Ads1115Slave.Mux.Ain1Ain3;
            }
            else if (channel < 256)
            {
                throw new ArgumentOutOfRangeException(nameof(channel));
            }
            else
            {
                extMux = (byte)(channel & 0xff);
                adcMux = Ads1115Slave.Mux.Ain0Ain1;
            }

            _pca9554.WritePort(extMux);
            _mux = extMux;
            Thread.Sleep(1);
            return(_ads1115.ReadRaw(adcMux, (Ads1115Slave.DataRate)dataRate, (Ads1115Slave.Pga)pga));
        }
Пример #18
0
        /// <summary>
        /// Initialize a new Ads1115 device connected through I2C
        /// </summary>
        /// <param name="i2cDevice">The I2C device used for communication.</param>
        /// <param name="inputMultiplexer">Input Multiplexer</param>
        /// <param name="measuringRange">Programmable Gain Amplifier</param>
        /// <param name="dataRate">Data Rate</param>
        /// <param name="deviceMode">Initial device mode</param>
        public Ads1115(I2cDevice i2cDevice, InputMultiplexer inputMultiplexer = InputMultiplexer.AIN0, MeasuringRange measuringRange = MeasuringRange.FS4096,
                       DataRate dataRate = DataRate.SPS128, DeviceMode deviceMode = DeviceMode.Continuous)
        {
            _i2cDevice          = i2cDevice ?? throw new ArgumentNullException(nameof(i2cDevice));
            _inputMultiplexer   = inputMultiplexer;
            _measuringRange     = measuringRange;
            _dataRate           = dataRate;
            _gpioController     = null;
            _gpioInterruptPin   = -1;
            _deviceMode         = deviceMode;
            ComparatorMode      = ComparatorMode.Traditional;
            _comparatorPolarity = ComparatorPolarity.Low;
            _comparatorLatching = ComparatorLatching.NonLatching;
            _comparatorQueue    = ComparatorQueue.Disable;

            SetConfig();
            DisableAlertReadyPin();
        }
Пример #19
0
 public static int MaxNeuralChannel(DataRate dataRate)
 {
     if (dataRate == DataRate.High)
     {
         return(9);
     }
     else if (dataRate == DataRate.Medium)
     {
         return(6);
     }
     else if (dataRate == DataRate.Low)
     {
         return(5);
     }
     else
     {
         return(-1);
     }
 }
Пример #20
0
        public static bool TryParse(string input, out DataRate result)
        {
            input = input
                    .ToLower()
                    .Replace(Second3, string.Empty)
                    .Replace(Second2, string.Empty)
                    .Replace(Second1, string.Empty)
                    .Trim('.')
                    .Trim();

            if (DataSizeParser.TryParse(input, out var res))
            {
                result = res / TimeSpan.FromSeconds(1);
                return(true);
            }

            result = default;
            return(false);
        }
Пример #21
0
 public static double MsecPerRAMPage(DataRate dataRate)
 {
     if (dataRate == DataRate.High)
     {
         return(1000.0 * Constant.FramePeriod * 2.2069);
     }
     else if (dataRate == DataRate.Medium)
     {
         return(1000.0 * Constant.FramePeriod * 4.0000);
     }
     else if (dataRate == DataRate.Low)
     {
         return(1000.0 * Constant.FramePeriod * 8.0000);
     }
     else
     {
         return(0.0);
     }
 }
Пример #22
0
 public static int MinNeuralChannel(DataRate dataRate)
 {
     if (dataRate == DataRate.High)
     {
         return(0);
     }
     else if (dataRate == DataRate.Medium)
     {
         return(2);
     }
     else if (dataRate == DataRate.Low)
     {
         return(4);
     }
     else
     {
         return(-1);
     }
 }
Пример #23
0
 /// <summary>
 /// Configure FPGA board to receive data of certain rate.
 /// </summary>
 /// <param name="dataRate">Data rate (High, Medium, or Low).</param>
 public void SetDataRate(DataRate dataRate)
 {
     if (myXEM != null)
     {
         if (dataRate == DataRate.Low)
         {
             myXEM.SetWireInValue(wireInDataRate, 3);
         }
         else if (dataRate == DataRate.Medium)
         {
             myXEM.SetWireInValue(wireInDataRate, 1);
         }
         else if (dataRate == DataRate.High)
         {
             myXEM.SetWireInValue(wireInDataRate, 0);
         }
         myXEM.UpdateWireIns();
     }
     Debug.WriteLine("XEM data rate changed to dataRate = " + dataRate);
 }
Пример #24
0
        public const int TriggerDelay  = 13;   // numbers of samples before spike threshold crossing to save

        public static int FrameSize(DataRate dataRate, bool rawDataMode)
        {
            if (rawDataMode)
            {
                if (dataRate == DataRate.High)
                {
                    return(198);
                }
                else if (dataRate == DataRate.Medium)
                {
                    return(102);
                }
                else if (dataRate == DataRate.Low)
                {
                    return(54);
                }
                else
                {
                    return(-1);
                }
            }
            else
            {
                if (dataRate == DataRate.High)
                {
                    return(174);
                }
                else if (dataRate == DataRate.Medium)
                {
                    return(96);
                }
                else if (dataRate == DataRate.Low)
                {
                    return(48);
                }
                else
                {
                    return(-1);
                }
            }
        }
Пример #25
0
        public static unsafe IntPtr Open(DataRate dataRate, Drive drive)
        {
            string fileName = drive == Drive.A ? "\\\\.\\fdraw0" : "\\\\.\\fdraw1";
            IntPtr handle   = CreateFile(fileName, EFileAccess.GenericRead | EFileAccess.GenericWrite, 0, IntPtr.Zero, ECreationDisposition.OpenExisting, 0, IntPtr.Zero);

            if ((int)handle == INVALID_HANDLE_VALUE)
            {
                int lastError = Marshal.GetLastWin32Error();
                Log.Error?.Out($"Не удалось открыть драйвер: {lastError} {WinErrors.GetSystemMessage(lastError)} {(lastError == 2 ? $"(Drive {drive}: is not installed)" : "")}");
                return(handle);
            }
            uint dwRet;
            bool r = DeviceIoControl(handle, IOCTL_FD_SET_DATA_RATE, (IntPtr)(&dataRate), sizeof(byte), IntPtr.Zero, 0, out dwRet, IntPtr.Zero);

            if (!r)
            {
                int lastError = Marshal.GetLastWin32Error();
                Log.Error?.Out($"Ошибка при установке DataRate: {lastError} {WinErrors.GetSystemMessage(lastError)}");
            }
            return(handle);
        }
Пример #26
0
        public void Choke_SatisfiesRequestsWheNotDepleted()
        {
            var startTime = DateTimeOffset.UtcNow;

            _timeSource.GetCurrentTime().Returns(startTime);

            var choke = new Choke(DataRate.FromBytesPerSecond(10000), new TimeSourceStopwatch(_timeSource));

            // The test is ignorant of the internal buffers but this must surely deplete it.
            for (var i = 0; i < 100; i++)
            {
                choke.RequestBytes(100);
            }

            Assert.IsFalse(choke.RequestBytes(100));

            // After a second there should be some capacity available gain.
            _timeSource.GetCurrentTime().Returns(startTime.AddSeconds(1));

            Assert.IsTrue(choke.RequestBytes(100));
        }
Пример #27
0
        public void SetConfig(
			bool triggerConversion = false, 
			InputMode? inputMode = null,
			Scaling? scaling = null,
			OperatingMode? operatingMode = null,
			DataRate? dataRate = null)
        {
            var config = configRegister;

            if (triggerConversion)
                config.SetBit1(15);

            if (scaling != null)
                config = config.SetBits(12, (ushort)scaling, 3);

            if (inputMode != null)
                config = config.SetBits(9, (ushort)inputMode.Value, 3);

            if (operatingMode != null)
                config = config.SetBits(8, (ushort)operatingMode.Value, 1);

            if (dataRate != null)
                config = config.SetBits(5, (ushort)dataRate.Value, 3);

            configRegister = config;
        }
Пример #28
0
        public override bool Initialize(TestModeEquipmentParameters[] Inno_25GBert_PPGStruct)
        {
            lock (syncRoot)
            {
                int i = 0;
                try
                {
                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "Addr", out i))
                    {
                        Addr = Convert.ToByte(Inno_25GBert_PPGStruct[i].DefaultValue);
                        switch (Addr)
                        {
                        case 0:
                            pDevice = LVEnum_1.Device_0;
                            break;

                        case 1:
                            pDevice = LVEnum_1.Device_1;
                            break;

                        case 2:
                            pDevice = LVEnum_1.Device_2;
                            break;

                        case 3:
                            pDevice = LVEnum_1.Device_3;
                            break;

                        default:
                            pDevice = LVEnum_1.Device_1;
                            break;
                        }
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no Addr");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "ED_Version", out i))
                    {
                        byte Ed_Value = Convert.ToByte(Inno_25GBert_PPGStruct[i].DefaultValue);
                        switch (Ed_Value)
                        {
                        case 0:
                            pED_Version = ED_Version.R1;
                            break;

                        case 1:
                            pED_Version = ED_Version.R2;
                            break;

                        default:
                            pED_Version = ED_Version.R2;
                            break;
                        }
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no Addr");
                        return(false);
                    }


                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "TriggerOutputList".ToUpper(), out i))
                    {
                        TriggerOutputList = Inno_25GBert_PPGStruct[i].DefaultValue.Split(',');
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no TriggerOutputList");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "IOTYPE", out i))
                    {
                        IOType = Inno_25GBert_PPGStruct[i].DefaultValue;
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no IOTYPE");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "RESET", out i))
                    {
                        Reset = Convert.ToBoolean(Inno_25GBert_PPGStruct[i].DefaultValue);
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no RESET");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "NAME", out i))
                    {
                        Name = Inno_25GBert_PPGStruct[i].DefaultValue;
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no NAME");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "DATARATE", out i))
                    {
                        dataRate = Inno_25GBert_PPGStruct[i].DefaultValue;
                        // pDataRate = (DataRate)Convert.ToDouble(dataRate);
                        switch (dataRate)
                        {
                        case "25.78":
                            pDataRate = DataRate.Rate25;
                            break;

                        case "28":
                            pDataRate = DataRate.Rate28;
                            break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no DATARATE");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "PPGInvert".ToUpper(), out i))
                    {
                        PPGInvert = (PG_Inverted)Convert.ToByte(Inno_25GBert_PPGStruct[i].DefaultValue);
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no PPGInvert");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "PPGPattern".ToUpper(), out i))
                    {
                        pTxPrbsType = (TxPrbsType)Convert.ToByte(Inno_25GBert_PPGStruct[i].DefaultValue);
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no PPGPattern");
                        return(false);
                    }

                    if (Algorithm.FindFileName(Inno_25GBert_PPGStruct, "SWING", out i))
                    {
                        pSwing = (TX_Set_Swing)Convert.ToByte(Inno_25GBert_PPGStruct[i].DefaultValue);
                    }
                    else
                    {
                        Log.SaveLogToTxt("there is no SWING");
                        return(false);
                    }

                    if (!Connect())
                    {
                        return(false);
                    }
                }
                catch (InnoExCeption error)
                {
                    Log.SaveLogToTxt("ErrorCode=" + error.ID + "Reason=" + error.TargetSite.Name + "Fail");
                    throw error;
                }

                catch (Exception error)
                {
                    Log.SaveLogToTxt("ErrorCode=" + ExceptionDictionary.Code._Los_parameter_0x05102 + "Reason=" + error.TargetSite.Name + "Fail");
                    throw new InnoExCeption(ExceptionDictionary.Code._Funtion_Fatal_0x05002, error.StackTrace);
                    // throw new InnoExCeption(ex);
                }
                return(true);
            }
        }
Пример #29
0
        /// <summary>
        /// USBData constructor.
        /// </summary>
        /// <param name="rawFrameBlock">Data block from USB interface.</param>
        /// <param name="dataRate">Data rate (Low, Medium, or High).</param>
        /// <param name="hammingDecoder">Hamming code decoder object.</param>
        public USBData(UInt16[] rawFrameBlock, DataRate dataRate, bool rawDataMode, HammingDecoder hammingDecoder)
        {
            int frame, channel, index, indexNeural, i;
            int numBitErrors;
            int bitErrorCount  = 0;
            int wordErrorCount = 0;

            int minNeuralChannel = Constant.MinNeuralChannel(dataRate);
            int maxNeuralChannel = Constant.MaxNeuralChannel(dataRate);
            int frameSize        = Constant.FrameSize(dataRate, rawDataMode);

            const double expectedFrameTimer = Constant.FPGAClockFreq * Constant.FramePeriod / 32.0; // = 960
            const int    maxFrameTimer      = (int)(expectedFrameTimer * 1.01);
            const int    minFrameTimer      = (int)(expectedFrameTimer / 1.01);

            missingFrameCount = 0;
            falseFrameCount   = 0;

            timeStampNanos = MainForm.GetAbsTimeNS();

            for (i = 0; i < frameSize * Constant.FramesPerBlock; i++)
            {
                rawData[i] = rawFrameBlock[i];
            }

            index       = 0;
            indexNeural = 0;
            double vOut;

            for (frame = 0; frame < Constant.FramesPerBlock; frame++)
            {
                for (i = 0; i < Constant.NeuralSamplesPerFrame; i++)
                {
                    for (channel = minNeuralChannel; channel <= maxNeuralChannel; channel++)
                    {
                        neuralData[channel, indexNeural + i] =
                            Constant.ADCStepNeural * ((neuralData16[channel, indexNeural + i] = hammingDecoder.DecodeDataCountErrors(rawFrameBlock[index], out numBitErrors, ref bitErrorCount, ref wordErrorCount)) - Constant.ADCOffset);
                        if (numBitErrors == 2 && (indexNeural + i) > 0)
                        {
                            neuralData[channel, indexNeural + i]   = neuralData[channel, indexNeural + i - 1];
                            neuralData16[channel, indexNeural + i] = neuralData16[channel, indexNeural + i - 1];
                        }
                        index++;
                    }
                    for (channel = 0; channel < minNeuralChannel; channel++)
                    {
                        neuralData[channel, indexNeural + i]   = 0.0;
                        neuralData16[channel, indexNeural + i] = (UInt16)Constant.ADCOffset;
                    }
                    for (channel = maxNeuralChannel + 1; channel < Constant.TotalNeuralChannels; channel++)
                    {
                        neuralData[channel, indexNeural + i]   = 0.0;
                        neuralData16[channel, indexNeural + i] = (UInt16)Constant.ADCOffset;
                    }
                }
                indexNeural += Constant.NeuralSamplesPerFrame;

                for (channel = 0; channel < Constant.TotalEMGChannels; channel++)
                {
                    EMGData[channel, frame] =
                        Constant.ADCStepEMG * ((EMGData16[channel, frame] = hammingDecoder.DecodeDataCountErrors(rawFrameBlock[index], out numBitErrors, ref bitErrorCount, ref wordErrorCount)) - Constant.ADCOffset);
                    if (numBitErrors == 2 && frame > 0)
                    {
                        EMGData[channel, frame]   = EMGData[channel, frame - 1];
                        EMGData16[channel, frame] = EMGData16[channel, frame - 1];
                    }
                    index++;
                }

                for (channel = 0; channel < Constant.TotalAuxChannels; channel++)
                {
                    vOut = Constant.ADCStep * (hammingDecoder.DecodeDataCountErrors(rawFrameBlock[index], out numBitErrors, ref bitErrorCount, ref wordErrorCount) - Constant.ADCOffset);

                    // Empirical equation modeling nonlinearity of auxiliary amplifier (see testing data, 6/25/11)
                    auxData[channel, frame] = 4.343 * vOut + 0.1 * Math.Exp(12.0 * (vOut - 0.82)) + 0.2 * Math.Exp(130.0 * (vOut - 1.0));

                    // Limit result to between 0 and 6.0 V
                    if (auxData[channel, frame] > 6.0)
                    {
                        auxData[channel, frame] = 6.0;
                    }
                    else if (auxData[channel, frame] < 0.0)
                    {
                        auxData[channel, frame] = 0.0;
                    }

                    if (numBitErrors == 2 && frame > 0)
                    {
                        auxData[channel, frame] = auxData[channel, frame - 1];
                    }

                    auxData16[channel, frame] = (UInt16)(auxData[channel, frame] / Constant.ADCStep + Constant.ADCOffset);

                    index++;
                }

                chipID[frame] = hammingDecoder.DecodeDataCountErrors(rawFrameBlock[index], out numBitErrors, ref bitErrorCount, ref wordErrorCount);
                index++;

                chipFrameCounter[frame] = hammingDecoder.DecodeDataCountErrors(rawFrameBlock[index], out numBitErrors, ref bitErrorCount, ref wordErrorCount);
                index++;

                boardFrameCounter[frame]      = hammingDecoder.DecodeData(rawFrameBlock[index++]) + 2048 * hammingDecoder.DecodeData(rawFrameBlock[index++]);
                boardFrameTimer[frame]        = hammingDecoder.DecodeData(rawFrameBlock[index++]) + 2048 * hammingDecoder.DecodeData(rawFrameBlock[index++]);
                TTLInputs[frame]              = hammingDecoder.DecodeData(rawFrameBlock[index++]);
                frameMarkerCorrelation[frame] = hammingDecoder.DecodeData(rawFrameBlock[index++]);

                if (dataRate == DataRate.Low || dataRate == DataRate.Medium)
                {
                    index += 2;
                }

                if (boardFrameTimer[frame] > maxFrameTimer)
                {
                    missingFrameCount++;
                }
                else if (boardFrameTimer[frame] < minFrameTimer)
                {
                    falseFrameCount++;
                }
            }

            BER = ((double)bitErrorCount) / ((double)(Constant.FramesPerBlock * Constant.BitsPerWord * (Constant.NeuralSamplesPerFrame * (maxNeuralChannel - minNeuralChannel + 1) + (Constant.TotalEMGChannels + Constant.TotalAuxChannels + 2))));
            WER = ((double)wordErrorCount) / ((double)(Constant.FramesPerBlock * (Constant.NeuralSamplesPerFrame * (maxNeuralChannel - minNeuralChannel + 1) + (Constant.TotalEMGChannels + Constant.TotalAuxChannels + 2))));
        }
 public void Should_Parse()
 {
     DataRate.Parse("10 /sec").Should().Be(new DataRate(10));
 }
 public void Should_TryParse()
 {
     DataRate.TryParse("10 /sec", out var res).Should().BeTrue().And.Be(res == new DataRate(10));
 }
        public void Should_return_FromPetabytesPerSecond()
        {
            var val = 100;

            DataRate.FromPetabytesPerSecond(val).Should().Be(new DataRate(val * DataSizeConstants.Petabyte));
        }