iFactory.Godot/Mods/工业数据采集与分析应用分享/Scripts/IDIS_THService.cs

124 lines
3.1 KiB
C#

using Godot;
using System;
using System.Globalization;
using System.Text;
using System.Timers;
using BITFactory;
using BITKit;
using Cysharp.Threading.Tasks;
using SQLitePCL;
using Timer = System.Timers.Timer;
// ReSharper disable All
namespace BITFactory;
public partial class IDIS_THService : Node
{
public enum UpdateMode
{
None,
Update,
Insert,
}
[Export] private UpdateMode currentUpdateMode = UpdateMode.Insert;
[ExportCategory("Services")]
[Export] private IDIS_Service service;
[Export] private 湿Reader thReader;
[ExportCategory("UI 绑定")]
[Export] private Button submitButton;
[Export] private CheckButton autoUpdateButton;
[Export] private OptionButton updateModeButton;
[Export] private LineEdit handleEdit;
[Export] private LineEdit temperatureEdit;
[Export] private LineEdit humidityEdit;
[Export] private RichTextLabel hintsLabel;
[Export] private RichTextLabel autoUpdateLabel;
private Timer autoUpdateTimer;
public override void _Ready()
{
submitButton.Pressed += Submit;
autoUpdateButton.Toggled += toggle =>
{
submitButton.Disabled = toggle;
handleEdit.Editable = !toggle;
temperatureEdit.Editable = !toggle;
humidityEdit.Editable = !toggle;
autoUpdateTimer.Enabled = toggle;
};
updateModeButton.GetPopup().Clear();
updateModeButton.GetPopup().AddItem("不更新");
updateModeButton.GetPopup().AddItem("更新记录");
updateModeButton.GetPopup().AddItem("添加记录");
updateModeButton.GetPopup().IndexPressed += index =>
{
currentUpdateMode = (UpdateMode)index;
};
autoUpdateTimer = new Timer();
autoUpdateTimer.AutoReset = true;
autoUpdateTimer.Interval = 1000;
autoUpdateTimer.Elapsed += AutoUpdate;
}
private async void AutoUpdate(object sender, ElapsedEventArgs e)
{
await UniTask.SwitchToSynchronizationContext(BITApp.SynchronizationContext);
UpdateTH(handleEdit.Text,thReader.temperature.ToString(),thReader.humidity.ToString());
}
private void Submit()
{
switch (handleEdit.Text, temperatureEdit.Text, humidityEdit.Text)
{
case ("", _, _):
hintsLabel.Text = "请输入标识码";
return;
case (_, "", _):
hintsLabel.Text = "请输入温度";
return;
case (_, _, ""):
hintsLabel.Text = "请输入湿度";
return;
}
UpdateTH(handleEdit.Text,temperatureEdit.Text,humidityEdit.Text);
}
private void UpdateTH(string handle,string temperature,string humidity)
{
if (string.IsNullOrEmpty(handle))
{
autoUpdateLabel.SetTextAsync("空的标识码");
return;
}
switch (currentUpdateMode)
{
case UpdateMode.Insert:
service.Register(handle,"温度" ,"float", temperature, "环境");
service.Register(handle, "湿度","float", humidity, "环境");
break;
case UpdateMode.Update:
if (service.Update(handle, "温度",temperature) is false)
{
autoUpdateLabel.SetTextAsync("温度更新失败,未知异常");
return;
}
if (service.Update(handle, "湿度",humidity) is false)
{
autoUpdateLabel.SetTextAsync("湿度更新失败,未知异常");
return;
}
break;
default:
break;
}
autoUpdateLabel.SetTextAsync($"温湿度已自动更新:{DateTime.Now}");
}
}