375 lines
14 KiB
C#

using Assets.Scenes.Ride.Scripts;
using Assets.Scripts;
using Assets.Scripts.Apis.Models;
using Assets.Scripts.Devices.Ant;
using Assets.Scripts.Devices.Ant.Interfaces;
using Assets.Scripts.Devices.Ble;
using Assets.Scripts.Devices.Ble.Characteristic;
using Assets.Scripts.Devices.Ble.Devices;
using ChartAndGraph;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
public class RowerHomeScript : PFUIPanel
{
private class TempRowerCalc
{
public int power { get; set; }
public ushort pace { get; set; }
public uint rate { get; set; }
public int heartRate { get; set; }
}
/// <summary>
/// 划船机数据
/// </summary>
private FtmsRowerData RowerData
{
get
{
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.Rower);
if (device != null)
{
return ((IRowerDevice)device).rowerData;
}
return null;
}
}
/// <summary>
/// 心率数据
/// </summary>
private int? HeartRate
{
get
{
var device = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.HeartRate);
if (device != null)
{
return ((IHeartRateDevice)device).HeartRate;
}
return null;
}
}
GameObject btnStart;
Transform left, bottom;
float timer = 1.0f;
EventHandler PaintPullCurveDelegate;
List<DoubleVector2> pullList = new List<DoubleVector2>();
Dictionary<object, Sprite> spriteDict;
List<string> records;
List<TempRowerCalc> values;
DateTime startTime,createTime;
double Kj = 0;
int seconds = 0;
bool isPause = false;
protected override void Awake()
{
spriteDict = new Dictionary<object, Sprite>()
{
{"Start",Resources.Load<Sprite>("Images/Rower/System_play")},
{"Untagged",Resources.Load<Sprite>("Images/Rower/System_pause")},
{0,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0001") },
{1,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0002") },
{2,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0003") },
{3,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0004") },
{4,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0005") },
{5,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0006") },
{6,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0007") },
{7,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0008") },
{8,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0009") },
{9,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0010") },
{10,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0011") },
{11,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0012") },
{12,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0013") },
{13,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0014") },
{14,Resources.Load<Sprite>("Images/Rower/序列帧/划船机0015") },
};
GetComponent<RectTransform>().localScale = Vector3.one;
GetComponent<RectTransform>().localPosition = Vector3.zero;
//mainNav.ShowExit();
var btnHome = transform.Find("Other/BtnHome").gameObject;
UIManager.AddEvent(btnHome, UnityEngine.EventSystems.EventTriggerType.PointerClick, b => ReturnHome());
btnStart = transform.Find("Other1/BtnStart").gameObject;
UIManager.AddEvent(btnStart, UnityEngine.EventSystems.EventTriggerType.PointerClick, b => HandleStartOrPause());
left = transform.Find("Left");
bottom = transform.Find("Bottom");
PaintPullCurveDelegate = new EventHandler(PaintPullCurve);
Init();
}
public override void Show()
{
base.Show();
var mainNav = this.transform.Find("MainNav").GetComponent<MainNav>();
mainNav.ShowRowerTab();
transform.MyDOFade();
Init();
//transform.Find("Left/Rower").GetComponent<RowerAnimation>().StartAnimation();
}
private void HandleStartOrPause()
{
//UIManager.ShowRowerResult();
//return;
if (btnStart.CompareTag("Start"))
{
#if !UNITY_EDITOR
if (RowerData == null)
{
Utils.showToast(null, "Please connect the device!");
return;
}
#endif
UIManager.ShowCountDownAnimation(() =>
{
if (RowerData != null)
{
RowerData.PullChanged += PaintPullCurveDelegate;
}
if (!isPause)
{
startTime = UIManager.Now.GetDateTime();
}
TimerTicks();
openTimer = true;
timer = 1.0f;
btnStart.GetComponent<Image>().sprite = spriteDict["Untagged"];
btnStart.tag = "Untagged";
});
}
else
{
UIManager.ShowConfirm3("Quit", "Do you want to keep the record?",
() =>
{
UIManager.CloseConfirm();
Save();
Init();
},
()=>
{
Init();
},
()=>
{
openTimer = false;
isPause = true;
RowerData.PullChanged -= PaintPullCurveDelegate;
btnStart.GetComponent<Image>().sprite = spriteDict["Start"];
btnStart.tag = "Start";
});
}
Debug.Log(RowerData);
//StartCoroutine();
}
private void Save()
{
createTime = UIManager.Now.GetDateTime();
var bleDevice = App.MainDeviceAdapter.GetDevices().FirstOrDefault(d => (d.State == DeviceState.Connected || d.State == DeviceState.Connecting) && d.Sensor == SensorType.Rower) as BleDevice;
RowerRecordModel model = new RowerRecordModel();
model.Ticks = records.Count;
if (bleDevice != null)
{
model.ManufacturerName = bleDevice.Name + " " + bleDevice.Network + " " + bleDevice.Sensor;
model.DeviceNumber = $"{ bleDevice.Address },{ bleDevice.Sensor }";
}
model.Id = Guid.NewGuid().ToString();
model.Weight = App.CurrentUser.Weight;
model.Kj = RowerData.TotalEnergy;
model.StartTime = startTime;
model.CreateTime = createTime;
Debug.Log(values.Count);
if (values.Count > 0)
{
model.MaxPower = values.Max(x => x.power);
model.MaxPace = values.Where(x => x.pace > 0).Min(x => x.pace);
model.MaxRate = values.Max(x => x.rate);
model.MaxHeartRate = values.Max(x => x.heartRate);
model.AvgPower = values.Average(x => x.power);
model.AvgPace = values.Where(x => x.pace > 0).Average(x => x.pace);
model.AvgRate = values.Average(x => x.rate);
model.AvgHeartRate = (int)values.Average(x => x.heartRate);
}
model.StrokeCount = RowerData.StrokeCount;
model.TotalTime = RowerData.ElapsedTime;
model.TotalDistance = RowerData.TotalDistance;
var path = PFConstants.RowerRecordFolder + "/" + model.Id;
Helper.CreateDirectoryIfNotExsit(path);
var files = new List<string>();
try
{
var fname = path + "/" + model.Id + ".txt";
using (var fs = new FileInfo(fname).OpenWrite())
{
var stream = new StreamWriter(fs);
stream.BaseStream.Seek(0, SeekOrigin.End);
foreach (var item in records)
{
stream.Write(item + "\r\n");
}
stream.Flush();
stream.Close();
files.Add(fname);
}
}
catch (Exception ex)
{
Helper.DelectDir(path);
Debug.Log(ex.Message);
}
UIManager.ShowRowerWelldone(model);
Task.Run(()=>
{
var res = ConfigHelper.rowerApi.Add(model, files);
});
}
private void Init()
{
if (RowerData != null)
{
RowerData.PullChanged -= PaintPullCurveDelegate;
RowerData.Reset();
}
btnStart.tag = "Start";
btnStart.GetComponent<Image>().sprite = spriteDict["Start"];
left.Find("Rower").GetComponent<Image>().sprite = spriteDict[0];
left.Find("LeftImage/Value").GetComponent<Image>().fillAmount = 0;
left.Find("RightImage/Value").GetComponent<Image>().fillAmount = 0;
left.Find("Times/Value").GetComponent<Text>().text = "---";
left.Find("Calories/Value").GetComponent<Text>().text = "---";
pullList = new List<DoubleVector2>();
transform.Find("Mid/GraphChart").GetComponent<RowerGraphChartFeed>().SetData(pullList);
openTimer = false;
bottom.Find("Time/Value").GetComponent<Text>().text = "---";
bottom.Find("KM/Value").GetComponent<Text>().text = "---";
bottom.Find("W/Value").GetComponent<Text>().text = "---";
bottom.Find("W/AvgValue").GetComponent<Text>().text = "---";
bottom.Find("500/Value").GetComponent<Text>().text = "---";
bottom.Find("500/AvgValue").GetComponent<Text>().text = "---";
bottom.Find("MS/Value").GetComponent<Text>().text = "---";
bottom.Find("MS/AvgValue").GetComponent<Text>().text = "---";
bottom.Find("BPM/Value").GetComponent<Text>().text = "---";
records = new List<string>();
values = new List<TempRowerCalc>();
Kj = 0;
x = 0;
seconds = 0;
isPause = false;
}
private void ReturnHome()
{
UIManager.ShowHomePanel();
}
// Update is called once per frame
bool openTimer = false;
double x = 0f;
//List<ushort> tempList = new List<ushort>()
//{
// 0,1,4,5,12,13,16,20,30,40,50,60,500
//};
//int tempx = 0;
void TimerTicks()
{
//Debug.Log(123);
//PaintPullCurve(tempList[(tempx++) % tempList.Count]);
if (RowerData == null) return;
bottom.Find("Time/Value").GetComponent<Text>().text = TimeSpan.FromSeconds(seconds++).ToString();
bottom.Find("KM/Value").GetComponent<Text>().text = RowerData.TotalDistance.ToString();
var power = RowerData.InstantaneousPower;
bottom.Find("W/Value").GetComponent<Text>().text = power.ToString();
bottom.Find("W/AvgValue").GetComponent<Text>().text = RowerData.AveragePower.ToString();
var pace = RowerData.InstantaneousPace;
bottom.Find("500/Value").GetComponent<Text>().text = TimeSpan.FromSeconds(pace).ToString(@"mm\:ss");
bottom.Find("500/AvgValue").GetComponent<Text>().text = TimeSpan.FromSeconds(RowerData.AveragePace).ToString(@"mm\:ss");
var rate = RowerData.StrokeRate;
bottom.Find("MS/Value").GetComponent<Text>().text = rate.ToString();
bottom.Find("MS/AvgValue").GetComponent<Text>().text = RowerData.AverageStrokeRate.ToString();
var heartRate = HeartRate ?? 0;
bottom.Find("BPM/Value").GetComponent<Text>().text = heartRate.ToString();
left.Find("Times/Value").GetComponent<Text>().text = RowerData.StrokeCount.ToString();
left.Find("Calories/Value").GetComponent<Text>().text = RowerData.TotalEnergy.ToString();
records.Add($"{RowerData.StrokeCount},{RowerData.ElapsedTime},{RowerData.TotalDistance},{RowerData.InstantaneousPower},{RowerData.InstantaneousPace},{RowerData.StrokeRate},{RowerData.ResistanceLevel},{heartRate}");
values.Add(new TempRowerCalc() { pace = pace, power = power, rate = rate,heartRate = heartRate });
//Debug.Log(1);
}
void PaintPullCurve(object sender, EventArgs e)
{
var ftms = (FtmsRowerData)sender;
Debug.Log(ftms.PullValue);
PaintPullCurve(ftms.PullValue);
}
void PaintPullCurve(ushort y)
{
if (y > 1000) y = 1000;
//拉力条
var rate = ((float)y) * 2 / 1000;
if (rate > 1) rate = 1;
left.Find("LeftImage/Value").GetComponent<Image>().fillAmount = rate;
left.Find("RightImage/Value").GetComponent<Image>().fillAmount = rate;
//动画
left.Find("Rower").GetComponent<Image>().sprite = spriteDict[y / 67];
//曲线
if (y == 0)
{
if (pullList.Count == 0)
{
x = 0;
pullList.Add(new DoubleVector2(x, y));
transform.Find("Mid/GraphChart").GetComponent<RowerGraphChartFeed>().SetData(pullList);
}
else
{
x += 0.1;
pullList.Add(new DoubleVector2(x, y));
transform.Find("Mid/GraphChart").GetComponent<RowerGraphChartFeed>().SetData(pullList);
pullList.Clear();
x = 0;
pullList.Add(new DoubleVector2(x, y));
}
}
else
{
x += 0.1;
pullList.Add(new DoubleVector2(x, y));
transform.Find("Mid/GraphChart").GetComponent<RowerGraphChartFeed>().SetData(pullList);
}
Debug.Log($"{x},{y}");
//transform.Find("Mid/GraphChart").GetComponent<RowerGraphChartFeed>().SetData(pullList);
//pullList.Add(new DoubleVector2(x, y));
//if (pullList.Count >= 75)
//{
// pullList.RemoveAt(0);
// pullList = pullList.Select(val => new DoubleVector2(val.x - 0.1, val.y)).ToList();
//}
//else
//{
// x += 0.1f;
//}
}
void Update()
{
if (openTimer)
{
timer -= Time.deltaTime;
if (timer <= 0)
{
TimerTicks();
timer = 1f + timer;
}
}
}
}