using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
static public int SampleRate = 2000;//单位值HZ
struct myData
{
public int x; //峰的X值
public double y; //峰的Y值
}
private int GetPeak(double[] buf) //buf[],存储的曲线点:源数据
{
int num_peak = 0;
double preValue = 0, curValue = 0, nextValue = 0;
for (int i = 1; i < buf.Count() - 1; i++)
{
if (buf[i] <= thresholdValue) { continue; }
preValue = Math.Round(buf[i - 1], 1);
curValue = Math.Round(buf[i], 1);
nextValue = Math.Round(buf[i + 1], 1);
if (preValue < curValue && curValue <= nextValue)
{
cache.x = i;
cache.y = curValue;
lst_Peak.Add(cache);
}
}
Console.WriteLine("1:峰值个数:" + lst_Peak.Count);
if (lst_Peak.Count < 1)
{
//saveBUGData(buf); //输出错误数值,方便分析
}
else
{
foreach (var data in lst_Peak)
{
Console.WriteLine("X:" + data.x + "Y:" + data.y);
}
num_peak = filterPeak(lst_Peak);
}
if (num_peak == 0)
{
Console.WriteLine("异常");
}
return num_peak;
}
private int filterPeak(List<myData> lst)
{//过滤峰值
double rate = 0;
try
{
double sum = 0;
double maxValue = 0;
double meanValue = -10; //均值
for (int i = 0; i < lst.Count - 1;) //过滤峰值
{
if (lst[i + 1].x - lst[i].x < 0.3 * SampleRate) //过滤毛刺数据。0.3*SampleRate,根据周期进行调整
{
if (lst[i].y < lst[i + 1].y)
{
lst.RemoveAt(i);
}
else
{
lst.RemoveAt(i + 1);
}
}
else
{
if (lst[i].y > maxValue)
{//记录最大值,无输入源时,会使用此数据
maxValue = lst[i].y;
}
i++;
}
}
if (maxValue < 0.2) //空载时,值<0.2
{
rate = 0;
Console.WriteLine("设备空载");
}
else //非空载
{
sum = lst[lst.Count - 1].x - lst[0].x;
Console.WriteLine("2:过滤后的峰值个数" + lst.Count);
switch (lst.Count)
{
case 0:
Console.WriteLine("未检测到波峰");
break;
case 1:
Console.WriteLine("仅有1个波峰");
Console.WriteLine("X:" + lst[0].x + "Y:" + lst[1].y);
break;
default:
meanValue = sum / (lst.Count - 1);
rate = 60 / (meanValue / SampleRate); //采样间隔3s,计算60s的rate,
Console.WriteLine("3:采集的峰峰间隔" + meanValue);
break;
}
}
}
catch { }
return (int)rate;
}
private void saveBUGData(double[] bugData)
{
try
{
string path = "Debug"+DateTime.Now.ToString("yyyyMMdd_hhmmss") + ".csv";
FileStream fs = new FileStream(path, FileMode.OpenOrCreate | FileMode.Append);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
sw.Flush();
foreach (var data in bugData)
{
sw.WriteLine(data + ",");
}
sw.Close();
fs.Close();
}
catch
{
Console.WriteLine("错误信息记录时出现异常");
}
}