public EEGExampleViewModel()
        {
            _startCommand = new ActionCommand(StartDevCmd, () => !IsRunning);
            _stopCommand  = new ActionCommand(StopDevCmd, () => IsRunning);
            _resetCommand = new ActionCommand(ResetDevCmd, () => !IsRunning && !IsReset);

            _uithread     = Dispatcher.CurrentDispatcher;
            _currentState = default(BrainDevState);
            _viewStream   = new Subject <int[]>();
            _viewStream.SubscribeOn(_uithread).Subscribe(
                intArr =>
            {
                var passTimes = BrainDevState.PassTimeMs(_currentState.SampleRate, _pakNum);
                _pakNum++;
                for (int i = 0; i < _channelViewModels.Count; i++)
                {
                    // Get the dataseries created for this channel
                    var channel    = _channelViewModels[i];
                    var dataseries = channel.ChannelDataSeries;

                    var val     = intArr[i];
                    var voltage = BitDataConverter.Calculatevoltage(val, 4.5f, _currentState.Gain);
                    dataseries.Append(passTimes, voltage);

                    // For reporting current size to GUI
                    _currentSize = dataseries.Count;
                }
            });
        }
Esempio n. 2
0
 private void InitDevice()
 {
     _viewStream = new Subject <int[]>();
     _pakNum     = 0;
     _viewStream.SubscribeOn(Dispatcher.CurrentDispatcher).Subscribe(
         intArr =>
     {
         _pakNum++;
         var passTimes = BrainDevState.PassTimeMs(_currentState.SampleRate, _pakNum) / 1000;
         var val       = intArr[0];
         var voltage   = BitDataConverter.Calculatevoltage(val, 4.5f, _currentState.Gain);
         _series0.Append(passTimes, voltage);
         XVisibleRange = ComputeXAxisRange(passTimes);
     });
 }
        private static async Task SendSampleData(int sampleTimeTick, SampleRateEnum rate, Socket socket, CancellationToken ctsToken)
        {
            byte size = 2 + ChannelCount * 3;
            var  buf  = bmgr.TakeBuffer(size);
            //_r.NextBytes(buf);
            var         passTimes = BrainDevState.PassTimeMs(rate, sampleTimeTick);
            const float max       = 4.5f / 24;

            buf[0] = (byte)DevCommandFuncId.StartStop;
            buf[1] = _brainState.SamplePacketOrder++;
            for (int i = 0; i < ChannelCount; i++)
            {
                var sampleValue = Math.Sin(passTimes * 2 / 1000f * Math.PI + i * simalatedDelta) * max;
                var(b0, b1, b2)    = BitDataConverter.ConvertTo(sampleValue, 4.5f, 24);
                buf[2 + i * 3]     = b0;
                buf[2 + 1 + i * 3] = b1;
                buf[2 + 2 + i * 3] = b2;
            }
            await SendWithHeadTail(socket, buf, size, ctsToken);

            bmgr.ReturnBuffer(buf);
        }
        private static async Task TestBrainDeviceManager()
        {
            var cfg       = ClientConfig.GetConfig();
            var lowFilter = new LowPassFilter()
            {
                LowPassRate = 10
            };
            var highFilter = new HighPassFilter()
            {
                HighPassRate = 10000
            };
            var bPassFilter = new BandPassFilter()
            {
                LowCutoffRate = 20, HighCutoffRate = 30
            };
            var bStopFilter = new BandStopFilter()
            {
                LowPassRate = 35, HighPassRate = 38
            };
            var mFilter = new MedianFilter()
            {
                HalfMedianWindowSize = 7
            };
            var bandFilter = new BandPassStopFilter
            {
                BandFilterList = new List <BandFilter> {
                    lowFilter, highFilter, bPassFilter, bStopFilter
                }
            };

            bandFilter.Disable = true;
            var allFilter = new FilterTypeList()
            {
                Filters = new List <FilterType> {
                    bandFilter, mFilter
                }
            };
            var filterParameters = new Dictionary <string, string>
            {
                { FilterTypeList.FIRhalfOrderOptionName, 10.ToString() }
            };

            cfg.FilterLst = allFilter;
            IOnlineFilter         filter     = null;
            WaveletReconstruction waveletRec = null;

            cfg.WaveletRecCfg = new WaveletReconstructionConfig
            {
                AvgLevel          = 8,
                ConvolutionMode   = ConvolutionModeEnum.Normal,
                ExtensionMode     = SignalExtension.ExtensionMode.SymmetricHalfPoint,
                Level             = 8,
                MotherWaveletName = "db5",
                WindowSize        = 15
            };
            cfg.WriteToFile(ClientConfig.DefaultConfigFileName);


            BrainDeviceManager.Init();
            var sender = await BrainDeviceManager.Connnect("127.0.0.1", 9211);

            BrainDevState currentState = default(BrainDevState);

            //保证设备参数正常才继续跑逻辑
            BrainDeviceManager.BrainDeviceState.Subscribe(ss =>
            {
                currentState = ss;
                filterParameters.Update(
                    FilterTypeList.SampleRateOptionName,
                    BrainDevState.SampleCountPer1Sec(ss.SampleRate).ToString()
                    );
                //AppLogger.Debug($"Brain Device State Changed Detected: {ss}");
            }, () =>
            {
                AppLogger.Debug("device stop detected");
            });
            int totalReceived    = 0;
            var medianFilter     = OnlineFirFilter.CreateDenoise(7);
            var fastMedianFilter = new OnlineFastMedianFilter(3);

            BrainDeviceManager.SampleDataStream.Subscribe(tuple =>
            {
                var(order, datas, arr) = tuple;
                //Console.Write($" {order} ");
                var passTimes = BrainDevState.PassTimeMs(currentState.SampleRate, totalReceived) / 1000;
                var intArr    = datas.CopyToArray();
                var val       = intArr[0];
                var voltage   = BitDataConverter.Calculatevoltage(val, 4.5f, currentState.Gain);
                totalReceived++;
                var m1 = medianFilter.ProcessSample(voltage);
                var m2 = fastMedianFilter.ProcessSample(voltage);
                AppLogger.Debug($"passTimes:{passTimes},val:{val},voltage:{voltage},median filter:{m1},fast:{m2},{m1==m2}");
                if (filter == null)
                {
                    filter     = allFilter.CreateFilter(filterParameters);
                    waveletRec = cfg.WaveletRecCfg.Create(
                        BrainDevState.SampleCountPer1Sec(currentState.SampleRate));
                    waveletRec.ReconstructionStream.Subscribe(reconstruct =>
                    {
                        var(vol, tim) = reconstruct;
                        AppLogger.Debug($"wavelet reconstruction:{vol} at {tim}");
                    });
                }
                waveletRec?.BufferData((voltage, passTimes));
                AppLogger.Debug($"filter processed:{filter.ProcessSample(voltage)}");
                //AppLogger.Debug($"order:{order}");
                //AppLogger.Debug($"converted values:{datas.Show()}");
                //AppLogger.Debug($"original datas:{arr.Show()}");
            }, () =>
            {
                AppLogger.Debug("device sampling stream closed detected");
            });

            var cmdResult = await sender.QueryParam();

            AppLogger.Debug("QueryParam result:" + cmdResult);
            if (cmdResult != CommandError.Success)
            {
                AppLogger.Error("Failed to QueryParam, stop");
                BrainDeviceManager.DisConnect();
                return;
            }


            cmdResult = await sender.SetFilter(true);

            AppLogger.Debug("SetFilter result:" + cmdResult);

            cmdResult = await sender.SetTrap(TrapSettingEnum.Trap_50);

            AppLogger.Debug("SetTrap result:" + cmdResult);

            cmdResult = await sender.SetSampleRate(SampleRateEnum.SPS_2k);

            AppLogger.Debug("SetSampleRate result:" + cmdResult);

            cmdResult = await sender.QueryParam();

            AppLogger.Debug("QueryParam result:" + cmdResult);

            cmdResult = await sender.QueryFaultState();

            AppLogger.Debug("QueryFaultState result:" + cmdResult);

            cmdResult = await sender.TestSingleImpedance(1);

            AppLogger.Debug("TestSingleImpedance result:" + cmdResult);

            cmdResult = await sender.TestMultiImpedance(30);

            AppLogger.Debug("TestMultiImpedance result:" + cmdResult);

            Console.ReadLine();
            var fs = new FileResource(currentState, 19801983, 1, BrainDeviceManager.BufMgr);

            fs.StartRecord(BrainDeviceManager.SampleDataStream);
            cmdResult = await sender.Start();

            if (cmdResult != CommandError.Success)
            {
                AppLogger.Error("Failed to start sampler");
            }
            else
            {
                AppLogger.Debug($"start receive sample data");
                await Task.Delay(1000 *10);

                AppLogger.Debug($"stoping");
                await sender.Stop();

                AppLogger.Debug($"stop receive sample data");
                await Task.Delay(1000);
            }

            BrainDeviceManager.DisConnect();
            fs.Dispose();

            var readf = new FileSampleData(fs.ResourceId, BrainDeviceManager.BufMgr);

            Console.WriteLine($"expecte to read {totalReceived} blocks");
            Console.WriteLine($"start reading saved sampling data");
            int readCount = 0;

            readf.DataStream.Subscribe(tuple =>
            {
                var(order, datas, arr) = tuple;
                Console.Write($" {order} ");
                readCount++;
                //AppLogger.Debug($"order:{order}");
                //AppLogger.Debug($"converted values:{datas.Show()}");
                //AppLogger.Debug($"original datas:{arr.Show()}");
            }, () =>
            {
                AppLogger.Debug($"read sampling data file end,count :{readCount},expected count:{totalReceived}");
            });
            readf.Start();
            await Task.Delay(1000 *10);

            Console.Write($"wait complete");
        }