读dat文件显示

using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Analwpf.ViewModels
{
using Analwpf.Common.Models;
using Analwpf.util;
using Microsoft.Win32;
using OxyPlot;
using OxyPlot.Annotations;
using OxyPlot.Axes;
using OxyPlot.Series;
using Prism.Commands;
using Prism.Events;
using System.Collections.ObjectModel;
using System.IO;
using System.Numerics;
using System.Threading.Tasks;
using System.Windows;

public class EcanViewModel : BindableBase
{
//选择通道
private List<string> comboChannels;
public List<string> ComboChannels
{
get { return comboChannels; }
set { SetProperty(ref comboChannels, value); }
}
private string selectedComboItem;
public string SelectedComboItem
{
get { return selectedComboItem; }
set { SetProperty(ref selectedComboItem, value); }
}
private string dataTime;
public string DataTime
{
get { return dataTime; }
set { SetProperty(ref dataTime, value); }
}
private List<List<double>> channelData = new List<List<double>>();

private readonly IEventAggregator _eventAggregator;
public EcanViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
ComboChannels = new List<string>() { "通道1", "通道2", "通道3", "通道4", "通道5", "通道6", "通道7", "通道8" };
PlotModels = new ObservableCollection<PlotModel>();
OpenFileCommand = new DelegateCommand(() =>
{
Open();
});
ShowCommand = new DelegateCommand(() =>
{
Show();
});
chart4 = new PlotModel();
SetOxyStyle(chart4);
chart4.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "Time" });
chart4.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "voltage" });
ls = new LineSeries { Title = "曲线图", Color = OxyColors.Black };
ls.InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline;
// 生成频谱图
chart3 = new PlotModel();
chart3.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "频率" });
chart3.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "幅值" });
ls3 = new LineSeries { Title = "频谱图" };
chart4.Series.Add(ls);
chart3.Series.Add(ls3);
PlotModels.Add(chart4);
PlotModels.Add(chart3);
}

private ObservableCollection<PlotModel> plotModels;
public ObservableCollection<PlotModel> PlotModels
{
get { return plotModels; }
set
{
plotModels = value;
RaisePropertyChanged();
}

}
private PlotModel GeneratePlotModel(List<DataPoint> dataPoints2)
{
// 生成OxyPlot的PlotModel对象并设置x、y轴的数据
var plotModel = new PlotModel();
plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "时间" });
plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "amplitude" });
var ls = new LineSeries { Title = "曲线图", Color = OxyColors.AliceBlue };
ls.Points.AddRange(dataPoints2);
plotModel.Series.Add(ls);
return plotModel;
}
private PlotModel GenerateSpePlotModel(List<DataPoint> dataPoints2)
{
// 生成OxyPlot的PlotModel对象并设置x、y轴的数据
var plotModel = new PlotModel();
plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Title = "频率" });
plotModel.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Title = "amplitude" });
var ls = new LineSeries { Title = "曲线图", Color = OxyColors.Green };
ls.Points.AddRange(dataPoints2);
plotModel.Series.Add(ls);
return plotModel;
}


/// <summary>
/// 线条
/// </summary>
private OxyPlot.Series.LineSeries _Series = new OxyPlot.Series.LineSeries()
{
/*InterpolationAlgorithm = InterpolationAlgorithms.CanonicalSpline*/
};

//坐标轴
private LinearAxis _AxisLeft = new LinearAxis() { Position = AxisPosition.Left };
private LinearAxis _AxisBottom = new LinearAxis() { Position = AxisPosition.Bottom };

//注解
private LineAnnotation _lineAnnotationH = new LineAnnotation { Type = LineAnnotationType.Horizontal };
private LineAnnotation _lineAnnotationV = new LineAnnotation { Type = LineAnnotationType.Vertical };
private ImageAnnotation _imageAnnotationC = new ImageAnnotation();

/// <summary>
/// 注解线条点击时的缩放比例
/// </summary>
private int _annotationScale = 2;

/// <summary>
/// 图片注解(十字靶心)尺寸(宽和高)
/// </summary>
private double _imageAnnotationSize = 66;

private Random _random;
private double totalSecond = 0;
/// <summary>
/// 注解横坐标
/// </summary>
public double AnnotationX { get; set; } = 4;

/// <summary>
/// 注解纵坐标
/// </summary>
public double AnnotationY { get; set; } = 4;

/// <summary>
/// 设置 OxyPlot 样式
/// </summary>
private void SetOxyStyle(PlotModel plot)
{
//图表边框;
plot.PlotAreaBorderThickness = new OxyThickness(1, 0, 0, 1);
//PlotModel.PlotAreaBorderThickness = new OxyThickness(0);
plot.PlotAreaBorderColor = OxyColor.Parse("#9C9C9C");
//PlotModel.PlotAreaBackground = OxyColor.Parse("#FFFFFF");
plot.Background = OxyColor.Parse("#FFFFFF");
plot.TextColor = OxyColor.Parse("#1E436B");
plot.DefaultFontSize = 14;
/*
//线条;
_Series.Color = OxyColor.Parse("#32C5FF");
_Series.StrokeThickness = 4;
_Series.TrackerFormatString = "时间: {2:0.##}\n温度: {4:0.##}";
//是否在没有实际点的地方显示(插值)Tracker(点信息);
_Series.CanTrackerInterpolatePoints = false;

#region 坐标轴
//坐标轴线设置(需要把图表边框设为0才能生效)
_AxisLeft.AxislineStyle = LineStyle.Solid;
_AxisLeft.AxislineColor = OxyColor.Parse("#9C9C9C");
_AxisLeft.AxislineThickness = 1;
//缩放;
_AxisLeft.IsZoomEnabled = false;
//平移(按住鼠标右键平移)
_AxisLeft.IsPanEnabled = false;
//刻度
_AxisLeft.TickStyle = TickStyle.None;
//小刻度线;
_AxisLeft.MinorTickSize = 0;
//主网格线;
_AxisLeft.MajorGridlineStyle = LineStyle.Solid;
_AxisLeft.MajorGridlineColor = OxyColor.Parse("#F3F3F3");

//坐标轴线设置(需要把图表边框设为0才能生效)
_AxisBottom.AxislineStyle = LineStyle.Solid;
_AxisBottom.AxislineColor = OxyColor.Parse("#9C9C9C");
_AxisBottom.AxislineThickness = 1;
//缩放;
_AxisBottom.IsZoomEnabled = false;
//平移(按住鼠标右键平移)
_AxisBottom.IsPanEnabled = false;
//刻度
_AxisBottom.TickStyle = TickStyle.None;
//小刻度线;
_AxisBottom.MinorTickSize = 0;
//主网格线;
_AxisBottom.MajorGridlineStyle = LineStyle.Solid;
_AxisBottom.MajorGridlineColor = OxyColor.Parse("#F3F3F3");

#endregion

//PlotModel.Axes.Clear();
plot.Axes.Add(_AxisLeft);
plot.Axes.Add(_AxisBottom);
*/
//plot.Series.Add(_Series);
}
public PlotModel chart4;
public PlotModel chart3;
public LineSeries ls;
public LineSeries ls3;
//输入时间框

private int _yourNumber=0;
public int YourNumberProperty
{
get { return _yourNumber; }
set
{
if (value >= 0 && value <= 599)
{
_yourNumber = value;
RaisePropertyChanged(nameof(YourNumberProperty));
}
else
{
MessageBox.Show("输入时间超限");
}
}
}
private int _endNumber = 1;
public int EndNumberProperty
{
get { return _endNumber; }
set
{
if (value >= 1 && value <= 600)
{
_endNumber = value;
RaisePropertyChanged(nameof(EndNumberProperty));
}
else
{
MessageBox.Show("输入时间超限");
}
}
}
private async Task GenerateMixedWaveform(int channel)
{
int fs = 16384;
const int duration = 600;

var t = Enumerable.Range(0, (fs * duration))
.Select(i => (float)i / fs)
.ToArray();
List<double> floatList = channelData[channel];
//t.Select(time => 0.26 * Math.Sin(2 * Math.PI * 2600 * time)).ToList();
//
await Task.Delay(1000);


int start = _yourNumber * fs;
int sum = _endNumber * fs;

 

/* List<double> floatList1 = new List<double>();
switch (channel)
{
case 0:
floatList1 = t.Select(time => 0.25 * Math.Sin(2 * Math.PI * 25 * time)).ToList();
break;
case 1:
floatList1 = t.Select(time => 0.5 * Math.Sin(2 * Math.PI *50 * time)).ToList();
break;
case 2:
floatList1 = t.Select(time => 0.17 * Math.Sin(2 * Math.PI * 1700 * time)).ToList();
break;
case 3:
floatList1 = t.Select(time => 0.2 * Math.Sin(2 * Math.PI * 2000 * time)).ToList();
break;
case 4:
floatList1 = t.Select(time => 0.23 * Math.Sin(2 * Math.PI * 2300 * time)).ToList();
break;
case 5:
floatList1 = t.Select(time => 0.26 * Math.Sin(2 * Math.PI * 2600 * time)).ToList();
break;
case 6:
floatList1 = t.Select(time => 0.5 * Math.Sin(2 * Math.PI * 5000 * time)).ToList();
break;
default:
break;
}*/


ls.Points.Clear();
var waveform = new List<DataPoint>();
//floatList.ToArray().Length
for (int i = start; i < sum; i++)
{
waveform.Add(new DataPoint(t[i], floatList[i]));
}

ls.Points.AddRange(waveform);
chart4.InvalidatePlot(true);

var dataPoints2 = new List<DataPoint>();
var pointsCount =16384*600;
Complex[] sigl_fft = FourierTransform.FFT1(floatList.ToArray());
// 将FFT结果添加到图表序列
for (int i = 0; i < pointsCount / 2; i++)
{
double magnitude = sigl_fft[i].Magnitude / pointsCount; // 归一化FFT输出
double freq = i * (double)fs / pointsCount;
dataPoints2.Add(new DataPoint(freq, magnitude));
}
/*
int L = sigl_fft.Length;
double[] P2 = new double[L];
//对量纲进行还原
for (int i = 0; i < L; i++)
{
P2[i] = Complex.Abs(sigl_fft[i] / L);
}

double[] P1 = new double[L / 2 + 1];
Array.Copy(P2, P1, L / 2 + 1);
for (int i = 1; i < P1.Length-1 ; i++)
{
P1[i] = 2 * P1[i];
}
double[] f = new double[L / 2];
for (int i = 0; i < L / 2; i++)
{
f[i] = i * fs*duration / L;
dataPoints2.Add(new DataPoint(f[i], P1[i]));

}
*/

ls3.Points.Clear();
ls3.Points.AddRange(dataPoints2);
chart3.InvalidatePlot(true);
}
public void Open()
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = ".dat files|*.dat";
openFileDialog.DefaultExt = ".dat";
int channels = 8;
int bufferSize = 16384;
int totalChannels = channels * bufferSize;
int startIndex = 9;
int readSeconds = 600;
List<int> floatList = new List<int>();
for (int i = 0; i < 8; i++)
{
channelData.Add(new List<double>());
}

if (openFileDialog.ShowDialog() == true)
{
{
string filePath = openFileDialog.FileName;
byte[] data = File.ReadAllBytes(filePath); // 读取文件的二进制数据
// 存储转换后的数据
// 存储转换后的数据
for (int i = 0; i < 6; i++)
{
int decimalValue = Convert.ToInt32(data[i]); // 将字节转换为十进制数
floatList.Add(decimalValue);
}
DataTime = floatList[0] + "-" + floatList[1] + "-" + floatList[2] + " " + floatList[3] + ":" + floatList[4] + ":" + floatList[5];

int dataIndex = 8; // 从第9个字节开始读取数据
for (int i = 0; i < 600; i++) // 每秒存储
{
for (int channel = 0; channel < 8; channel++) // 8个通道
{
for (int j = 0; j < 16384; j++) // 每个通道16384组数据
{
byte[] bytePair1 = { data[dataIndex+1], data[dataIndex] };
string hexPair1 = BitConverter.ToString(bytePair1).Replace("-", "");
//ushort value = (ushort)((data[dataIndex] << 8) | data[dataIndex + 1]); // 将两组byte转换为一个16位值
// float convertedValue = ((value * 2.0f) / 65536.0f - 1) * 3.0f;
if (int.TryParse(hexPair1, System.Globalization.NumberStyles.HexNumber, null, out int decimalValue))
{
double a = (double)decimalValue * 2 / (double)65536;
double temp = (a - 1) * 3.0;
channelData[channel].Add(temp);
}

dataIndex += 2; // 每次读取两个byte
}
}
}

}
}

}
public async void Show()
{
string cannel = SelectedComboItem;
if (_yourNumber < _endNumber)
{
switch (cannel)
{
case "通道1":
await GenerateMixedWaveform(0);
break;
case "通道2":
await GenerateMixedWaveform(1);
break;
case "通道3":
await GenerateMixedWaveform(2);
break;
case "通道4":
await GenerateMixedWaveform(3);
break;
case "通道5":
await GenerateMixedWaveform(4);
break;
case "通道6":
await GenerateMixedWaveform(5);
break;
case "通道7":
await GenerateMixedWaveform(6);
break;
case "通道8":
await GenerateMixedWaveform(7);
break;
default:
break;
}
}
else
{
MessageBox.Show("开始时间大于结束时间");
}

}
public DelegateCommand OpenFileCommand { get; private set; }
public DelegateCommand ShowCommand { get; private set; }
}
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Analwpf.Views
{
/// <summary>
/// EcanView.xaml 的交互逻辑
/// </summary>
public partial class EcanView : UserControl
{
public EcanView()
{
InitializeComponent();
}
}
}

posted @ 2023-11-30 09:09  天明宝  阅读(20)  评论(0编辑  收藏  举报