예제 #1
0
        public static (int, byte[]) Header(SyncBufManager bufferManager, byte version, uint devId, long startTick,
                                           BrainDevState state)
        {
            var buf = bufferManager.TakeBuffer(CntStartIndex);

            buf[0] = version;
            var ind = 1;

            unsafe
            {
                WritePrimitive((byte *)&devId, sizeof(uint), buf, ref ind);
                WritePrimitive((byte *)&startTick, sizeof(long), buf, ref ind);
                buf[ind++] = state.DevCode;
                buf[ind++] = state.ChannelCount;
                buf[ind++] = state.Gain;
                buf[ind++] = (byte)state.SampleRate;
                buf[ind++] = (byte)state.TrapOption;
                buf[ind++] = state.EnalbeFilter ? (byte)1 : (byte)0;
                for (var i = ind; i < CntStartIndex; i++)
                {
                    buf[i] = 0;
                }
            }
            return(CntStartIndex, buf);
        }
        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;
                }
            });
        }
예제 #3
0
 /// <summary>
 /// 按照时间、设备状态等数据创建放大器采样数据文件,
 /// 写入文件头(格式定义在SampleDataFileFormat),
 /// 关闭时写入MD5校验值
 /// </summary>
 /// <param name="state"></param>
 /// <param name="devId"></param>
 /// <param name="version"></param>
 /// <param name="bufferManager"></param>
 public FileResource(BrainDevState state, uint devId, byte version, SyncBufManager bufferManager)
 {
     _state         = state;
     _devId         = devId;
     _version       = version;
     _bufferManager = bufferManager;
 }
예제 #4
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);
     });
 }
        /// <summary>
        /// 显示/修改基本设置
        /// </summary>
        /// <param name="state"></param>
        public SettingViewWin(BrainDevState state)
        {
            BrainDeviceManager.OnConnected += OnReconnect;
            InitializeComponent();
            _uithread     = Dispatcher.CurrentDispatcher;
            _unsubscriber = BrainDeviceManager.BrainDeviceState.Subscribe(OnDevStateChanged, () =>
            {
                _uithread.InvokeAsync(OnDisconnect);
            });
            OnDevStateChanged(state);
            var cfglocal = ClientConfig.GetConfig();

            IpTextBox.Text   = cfglocal.Ip;
            PortTextBox.Text = cfglocal.Port.ToString();
            EnableTimeoutCheckBox.IsChecked = cfglocal.EnableCommandTimeout;
            TimeoutTextBox.Text             = cfglocal.TimeoutMilliseconds.ToString();
            AutoStartCheckBox.IsChecked     = cfglocal.IsAutoStart;
        }
        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);
        }
예제 #7
0
        /// <summary>
        /// 显示/测试采样通道的阻抗值
        /// </summary>
        /// <param name="state"></param>
        public ImpedanceViewWin(BrainDevState state)
        {
            BrainDeviceManager.OnConnected += OnReconnect;
            InitializeComponent();
            _currentState = state;
            for (int i = 0; i < _currentState.ChannelCount; i++)
            {
                var         code = _currentState.GetChannelImpedance(i);
                ListBoxItem item = new ListViewItem
                {
                    Content  = $"Channel {i + 1}: {code}",
                    TabIndex = i + 1
                };
                ImpedanceListBox.Items.Add(item);
                item.Selected += OnItemSelected;
            }
            _uithread = Dispatcher.CurrentDispatcher;

            _unsubscriber = BrainDeviceManager.BrainDeviceState.Subscribe(OnDevStateChanged, () =>
            {
                _uithread.InvokeAsync(OnDisconnect);
            });
        }
        private static async void StartPeridSender(Socket socket, CancellationToken ctsToken)
        {
            var sampleTimeTick = 0;

            while (true)
            {
                await Task.Delay(20);

                if (!_brainState.IsStart)
                {
                    return;
                }

                var rate  = _brainState.SampleRate;
                var count = BrainDevState.SampleCountPer20ms(rate);

                try
                {
                    for (int i = 0; i < count; i++)
                    {
                        await SendSampleData(sampleTimeTick, rate, socket, ctsToken);

                        sampleTimeTick++;
                        if (!_brainState.IsStart)
                        {
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return; //any exception will break the sending queues
                }
            }
        }
예제 #9
0
        private async Task StartDevice()
        {
            BrainDeviceManager.Init();
            var sender = await BrainDeviceManager.Connnect("127.0.0.1", 9211);

            _currentState = default(BrainDevState);
            //保证设备参数正常才继续跑逻辑
            BrainDeviceManager.BrainDeviceState.Subscribe(ss =>
            {
                _currentState = ss;
                var pmax      = 4.5f * 2 / _currentState.Gain;
                YVisibleRange = new DoubleRange(-pmax, pmax);
                AppLogger.Debug($"Brain Device State Changed Detected: {ss}");
            }, () =>
            {
                AppLogger.Debug("device stop detected");
            });
            int totalReceived = 0;

            BrainDeviceManager.SampleDataStream.Subscribe(tuple =>
            {
                var(order, datas, arr) = tuple;
                var copyArr            = datas.CopyToArray();
                if (copyArr != null)
                {
                    _viewStream.OnNext(copyArr);
                }
                //Console.Write($" {order} ");
                totalReceived++;
                //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(false);

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

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

            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);

            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 *60);

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

                AppLogger.Debug($"stop receive sample data");
                await Task.Delay(1000);
            }
            BrainDeviceManager.DisConnect();
            fs.Dispose();
        }
예제 #10
0
        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");
        }
예제 #11
0
 private void OnDevStateChanged(BrainDevState ss)
 {
     _currentState = ss;
     _uithread.InvokeAsync(RefreshDevStateUI);
 }
예제 #12
0
        private async Task <DevCommandSender> ConnectDevAsync()
        {
            try
            {
                BrainDeviceManager.Init();
                //TODO config IP and port
                var sender = await BrainDeviceManager.Connnect("127.0.0.1", 9211);

                //TODO config vRef (default = 4.5f)
                //保证设备参数正常才继续跑逻辑
                BrainDeviceManager.BrainDeviceState.Subscribe(ss =>
                {
                    _currentState = ss;
                    ChannelCount  = _currentState.ChannelCount;
                    _uithread.InvokeAsync(CreateChannelParts);
                    var pmax = 4.5f * 2 / _currentState.Gain;
                    //YVisibleRange = new DoubleRange(-pmax, pmax);
                    AppLogger.Debug($"Brain Device State Changed Detected: {ss}");
                }, () =>
                {
                    AppLogger.Debug("device stop detected");
                });
                BrainDeviceManager.SampleDataStream.Subscribe(tuple =>
                {
                    var(order, datas, arr) = tuple;
                    var copyArr            = datas.CopyToArray();
                    if (copyArr != null)
                    {
                        _viewStream.OnNext(copyArr);
                    }
                    //Console.Write($" {order} ");
                    //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(null);
                }
                return(sender);
            }
            catch (Exception)
            {
                return(null);
            }

            /*
             * cmdResult = await sender.SetFilter(false);
             * AppLogger.Debug("SetFilter result:"+cmdResult);
             *
             * cmdResult = await sender.SetTrap(TrapSettingEnum.NoTrap);
             * 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);
             */
        }
예제 #13
0
 private void OnDevStateChanged(BrainDevState ss)
 {
     _currentState = ss;
     _uithread.InvokeAsync(RefreshImpedanceCodes);
 }