添加项目文件。

This commit is contained in:
xyy
2026-01-07 13:42:17 +08:00
parent bd88ab30d1
commit 9cfc6d71ff
33 changed files with 10232 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Data
{
//public class BoolSignal
//{
// private bool _previousValue;
// public event Action OnRisingEdge;
// public bool Value { get; set; }
// public void CheckRisingEdge()
// {
// if (Value && !_previousValue)
// {
// OnRisingEdge?.Invoke();
// }
// _previousValue = Value;
// }
//}
public class BoolSignal
{
private bool _previousValue;
public event Action OnRisingEdge;
public bool Value { get; set; }
public void CheckRisingEdge()
{
if (!Value && _previousValue)
{
OnRisingEdge?.Invoke();
}
_previousValue = Value;
}
}
}

View File

@@ -0,0 +1,121 @@
using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace
{
public class ConductivityTestData
{
public int Id { get; set; }
/// <summary>
/// 条码
/// </summary>
public string barcode { get; set; }
/// <summary>
/// 条码
/// </summary>
public double temperature { get; set; }
/// <summary>
/// 初始压力
/// </summary>
public double startpressure { get; set; }
/// <summary>
/// 保压时间
/// </summary>
public double dwelltime { get; set; }
/// <summary>
/// 压差
/// </summary>
public double diffpressure { get; set; }
/// <summary>
/// 结束压力
/// </summary>
public double endpressure { get; set; }
public DateTime CreateTime { get; set; }
/// <summary>
/// 普通0高温1
/// </summary>
public int Type { get; set; }
}
public class ConductivityRepository
{
private readonly string _connectionString;
public ConductivityRepository()
{
_connectionString = "Server=localhost;Database=fullautowaterpressure;User=root;Password=123456;port=3306;charset=utf8;";
}
public void InsertReportItems(ConductivityTestData data)
{
using (var connection = new MySqlConnection(_connectionString))
{
connection.Open();
var sql = @"INSERT INTO normaltemperature
(barcode, temperature, startpressure, dwelltime,
diffpressure, endpressure, CreateTime, type)
VALUES
(@barcode, @temperature, @startpressure, @dwelltime, @diffpressure,@endpressure,CURRENT_TIMESTAMP,@type)";
connection.Execute(sql, data);
}
}
public void InsertTestDataList(List<ConductivityTestData> dataList)
{
using (var connection = new MySqlConnection(_connectionString))
{
connection.Open();
var sql = @"INSERT INTO normaltemperature
(barcode, temperature, startpressure, dwelltime,
diffpressure, endpressure, CreateTime, type)
VALUES
(@barcode, @temperature, @startpressure, @dwelltime, @diffpressure,@endpressure,CURRENT_TIMESTAMP,@type)";
connection.Execute(sql, dataList);
}
}
public List<ConductivityTestData> GetTestData(DateTime startDate, DateTime endDate)
{
using (var connection = new MySqlConnection(_connectionString))
{
connection.Open();
var sql = @"SELECT * FROM normaltemperature
WHERE TestStartTime BETWEEN @StartDate AND @EndDate
ORDER BY CreateTime DESC";
return connection.Query<ConductivityTestData>(sql, new { StartDate = startDate, EndDate = endDate }).ToList();
}
}
public bool TestConnection()
{
try
{
using (var connection = new MySqlConnection(_connectionString))
{
connection.Open();
return connection.State == ConnectionState.Open;
}
}
catch
{
return false;
}
}
}
}

View File

@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace
{
public class DataChange
{
/// <summary>
/// ushort转为float类型
/// </summary>
/// <param name="P1"></param>
/// <param name="P2"></param>
/// <returns>float型数据</returns>
public float UshortToFloat(ushort P1, ushort P2)
{
int intSign, intSignRest, intExponent, intExponentRest;
float faResult, faDigit;
intSign = P1 / 32768;
intSignRest = P1 % 32768;
intExponent = intSignRest / 128;
intExponentRest = intSignRest % 128;
faDigit = (float)(intExponentRest * 65536 + P2) / 8388608;
faResult = (float)Math.Pow(-1, intSign) * (float)Math.Pow(2, intExponent - 127) * (faDigit + 1);
return faResult;
}
/// <summary>
/// ushort转为int类型
/// </summary>
/// <param name="u1"></param>
/// <param name="u2"></param>
/// <returns>返回int型数据</returns>
public int UshortToInt1(ushort u1, ushort u2)
{
ushort[] maidong = new ushort[2] { u1, u2 };
byte[] bytes = new byte[maidong.Length * 2];
Buffer.BlockCopy(maidong, 0, bytes, 0, bytes.Length);
int result = BitConverter.ToInt32(bytes, 0);
// 将字节数组转换为32位无符号整数
return result;
}
/// <summary>
/// Float转为Ushort数组发送
/// </summary>
/// <param name="value"></param>
/// <returns>返回ushort数组</returns>
public ushort[] SplitFloatToUShortArray(float value)
{
byte[] floatBytes = BitConverter.GetBytes(value);
ushort[] ushortArray = new ushort[floatBytes.Length / 2];
for (int i = 0, j = 0; i < floatBytes.Length; i += 2, j++)
{
ushortArray[j] = BitConverter.ToUInt16(floatBytes, i);
}
return ushortArray;
}
/// <summary>
/// Int转为ushort数组发送
/// </summary>
/// <param name="res"></param>
/// <returns>返回ushort数组</returns>
public ushort[] intToushorts(int res)
{
ushort ust1 = (ushort)(res >> 16);
ushort ust2 = (ushort)res;
return new ushort[] { ust2, ust1 };
}
}
}

View File

@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace .DATA
{
/// <summary>
/// 基于单例模式的WinForm窗口管理器
/// 提供流畅的窗口切换API
/// </summary>
public sealed class FormManager
{
// 单例实例
private static readonly Lazy<FormManager> _instance = new Lazy<FormManager>(() => new FormManager());
// 存储所有窗口实例
private readonly Dictionary<Type, Form> _formInstances = new Dictionary<Type, Form>();
// 私有构造函数,防止外部实例化
private FormManager() { }
/// <summary>
/// 获取单例实例
/// </summary>
public static FormManager Instance => _instance.Value;
/// <summary>
/// 注册窗口实例
/// </summary>
/// <typeparam name="T">窗口类型</typeparam>
/// <param name="formInstance">窗口实例</param>
/// <returns>返回自身,支持链式调用</returns>
public FormManager RegisterForm<T>(T formInstance) where T : Form
{
Type formType = typeof(T);
if (!_formInstances.ContainsKey(formType))
{
_formInstances[formType] = formInstance;
// 监听窗口关闭事件,自动移除注册
formInstance.FormClosed += (s, e) => _formInstances.Remove(formType);
}
return this;
}
/// <summary>
/// 显示指定窗口并隐藏当前活动窗口
/// </summary>
/// <typeparam name="T">要显示的窗口类型</typeparam>
/// <returns>返回自身,支持链式调用</returns>
public FormManager SwitchTo<T>() where T : Form
{
Type targetType = typeof(T);
// 检查目标窗口是否已注册
if (!_formInstances.TryGetValue(targetType, out Form targetForm))
{
throw new InvalidOperationException($"窗口 {targetType.Name} 未注册,请先调用 RegisterForm 方法");
}
// 隐藏当前活动窗口
Form activeForm = Form.ActiveForm;
if (activeForm != null && activeForm != targetForm)
{
activeForm.Hide();
}
// 显示目标窗口并置于顶层
targetForm.Show();
targetForm.BringToFront();
return this;
}
/// <summary>
/// 显示指定窗口
/// </summary>
/// <typeparam name="T">要显示的窗口类型</typeparam>
/// <returns>返回自身,支持链式调用</returns>
public FormManager ShowForm<T>() where T : Form
{
Type targetType = typeof(T);
if (_formInstances.TryGetValue(targetType, out Form targetForm))
{
targetForm.Show();
targetForm.BringToFront();
}
return this;
}
/// <summary>
/// 隐藏指定窗口
/// </summary>
/// <typeparam name="T">要隐藏的窗口类型</typeparam>
/// <returns>返回自身,支持链式调用</returns>
public FormManager HideForm<T>() where T : Form
{
Type targetType = typeof(T);
if (_formInstances.TryGetValue(targetType, out Form targetForm))
{
targetForm.Hide();
}
return this;
}
/// <summary>
/// 获取已注册的窗口实例
/// </summary>
/// <typeparam name="T">窗口类型</typeparam>
/// <returns>窗口实例</returns>
public T GetForm<T>() where T : Form
{
Type targetType = typeof(T);
if (_formInstances.TryGetValue(targetType, out Form form))
{
return form as T;
}
return null;
}
}
}

View File

@@ -0,0 +1,234 @@
using Modbus.Device;
using Modbus;
using Sunny.UI;
using System;
using System.Threading;
using System.Windows.Forms;
namespace
{
public class Function
{
ModbusMaster master;
IModbusMaster modbusMaster;
DataChange dc = new DataChange();
public enum ButtonType
{
,
,
,
}
public enum DataType
{
,
}
public Function(ModbusMaster master_in)
{
this.master = master_in;
}
public Function(IModbusMaster modbusMaster)
{
this.modbusMaster = modbusMaster;
}
public void BtnClickFunction(ButtonType buttonType, ushort address)
{
try
{
switch (buttonType)
{
case ButtonType.:
master.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
master.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
case ButtonType.:
if (master.ReadCoils(1, address, 1)[0])
{
master.WriteSingleCoil(1, address, false); Thread.Sleep(100);
}
else
{ master.WriteSingleCoil(1, address, true); Thread.Sleep(100); }
break;
case ButtonType.:
master.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
break;
case ButtonType.:
master.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
default:
break;
}
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void BtnClickFunctionForNew(ButtonType buttonType, ushort address)
{
try
{
switch (buttonType)
{
case ButtonType.:
modbusMaster.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
modbusMaster.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
case ButtonType.:
if (modbusMaster.ReadCoils(1, address, 1)[0])
{
modbusMaster.WriteSingleCoil(1, address, false); Thread.Sleep(100);
}
else
{ modbusMaster.WriteSingleCoil(1, address, true); Thread.Sleep(100); }
break;
case ButtonType.:
modbusMaster.WriteSingleCoil(1, address, true);
Thread.Sleep(100);
break;
case ButtonType.:
modbusMaster.WriteSingleCoil(1, address, false);
Thread.Sleep(100);
break;
default:
break;
}
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void WriteToPLC(string inPutValue, ushort address, DataType dataType)
{
try
{
switch (dataType)
{
case DataType.:
double value = inPutValue.ToDouble();
if (UIInputDialog.ShowInputDoubleDialog(ref value, UIStyle.Inherited, desc: "请输入值", showMask: false))
{
master.WriteMultipleRegisters(1, address, dc.SplitFloatToUShortArray((float)value));
}
break;
case DataType.:
int value_int = inPutValue.ToInt();
if (UIInputDialog.ShowInputIntegerDialog(ref value_int, UIStyle.Inherited, desc: "请输入数据:"))
{
master.WriteMultipleRegisters(1, address, dc.intToushorts(value_int));
}
break;
default:
break;
}
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void WriteToPLCForNew(string inPutValue, ushort address, DataType dataType, bool isok=false,float max=0,float min=0)
{
try
{
//KeyboardHelper.ShowSoftKeyboard();
switch (dataType)
{
case DataType.:
double value = inPutValue.ToDouble();
if (UIInputDialog.ShowInputDoubleDialog(ref value, UIStyle.Inherited, desc: "请输入值", showMask: false))
{
if ( isok&&value > max || value < min)
{
MessageBox.Show("数据不正确");
return;
}
modbusMaster.WriteMultipleRegisters(1, address, dc.SplitFloatToUShortArray((float)value));
}
break;
case DataType.:
int value_int = inPutValue.ToInt();
if (UIInputDialog.ShowInputIntegerDialog(ref value_int, UIStyle.Inherited, desc: "请输入数据:"))
{
modbusMaster.WriteMultipleRegisters(1, address, dc.intToushorts(value_int));
//if (isok)
//{ modbusMaster.WriteSingleCoil(1, 25, true); }
}
break;
default:
break;
}
//KeyboardHelper.HideSoftKeyboard();
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
public void WriteToPLCForNew(string inPutValue, ushort address, DataType dataType, int d)
{
try
{
//KeyboardHelper.ShowSoftKeyboard();
switch (dataType)
{
case DataType.:
double value = inPutValue.ToDouble();
if (UIInputDialog.ShowInputDoubleDialog(ref value, UIStyle.Inherited, d, desc: "请输入值", showMask: false))
{
modbusMaster.WriteMultipleRegisters(1, address, dc.SplitFloatToUShortArray((float)value));
}
break;
case DataType.:
int value_int = inPutValue.ToInt();
if (UIInputDialog.ShowInputIntegerDialog(ref value_int, UIStyle.Inherited, desc: "请输入数据:"))
{
modbusMaster.WriteMultipleRegisters(1, address, dc.intToushorts(value_int));
//if (isok)
//{ modbusMaster.WriteSingleCoil(1, 25, true); }
}
break;
default:
break;
}
//KeyboardHelper.HideSoftKeyboard();
}
catch (Exception ex)
{
MessageBox.Show("操作失败!" + "\n" + "\n" + ex.Message, "错误");
}
}
}
}

View File

@@ -0,0 +1,21 @@
namespace
{
public class LoginData
{
static string _userName = "";
public string UserName
{
get { return _userName; }
set { _userName = value; }
}
//登陆权限
static int _userPower = 0;//0为普通用户1为管理员
public int UserPower
{
get { return _userPower; }
set { _userPower = value; }
}
}
}

View File

@@ -0,0 +1,69 @@
using System;
using Modbus.Device;
using System.Net.Sockets;
namespace .Data
{
// 单例模式:全局唯一资源管理器
public class ModbusResourceManager
{
// 私有构造函数禁止外部new
private ModbusResourceManager() { }
// 唯一实例
private static readonly Lazy<ModbusResourceManager> _instance = new Lazy<ModbusResourceManager>(() => new ModbusResourceManager());
public static ModbusResourceManager Instance => _instance.Value;
// 共享资源
public TcpClient TcpClient { get; private set; }
public IModbusMaster ModbusMaster { get; private set; }
// 初始化资源在程序启动时调用如MainWindow加载时
public bool Init(string ip, int port)
{
try
{
// 先释放旧资源
ReleaseResource();
// 创建新连接
TcpClient = new TcpClient();
TcpClient.Connect(ip, port);
ModbusMaster = ModbusIpMaster.CreateIp(TcpClient);
return true;
}
catch (Exception ex)
{
Console.WriteLine($"资源初始化失败:{ex.Message}");
ReleaseResource();
return false;
}
}
public void Dispose()
{
try
{
ModbusMaster?.Dispose();
TcpClient?.Close();
}
catch
{
// 忽略清理时的异常
}
}
// 释放资源(统一释放,避免重复关闭)
public void ReleaseResource()
{
ModbusMaster?.Dispose();
ModbusMaster = null;
//if (TcpClient?.Connected ?? false)
//{
// TcpClient.Close();
//}
TcpClient?.Dispose();
TcpClient = null;
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace .Data
{
internal class PLC_Data
{
}
}

View File

@@ -0,0 +1,71 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Principal;
using System.Windows;
public class KeyboardHelper
{
public static void ShowSoftKeyboard()
{
if (!IsRunAsAdmin())
{
RestartAsAdmin();
return;
}
// 替换原有的 Process.Start 代码
string oskPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "osk.exe");
if (File.Exists(oskPath))
{
Process.Start(new ProcessStartInfo
{
FileName = oskPath,
UseShellExecute = true
});
}
else
{
//MessageBox.Show("未找到屏幕键盘程序osk.exe可能系统文件缺失或非Windows系统。", "错误");
}
}
public static void HideSoftKeyboard()
{
try
{
Process.Start("cmd.exe", "/C taskkill /IM osk.exe /F");
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
private static void RestartAsAdmin()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
startInfo.Verb = "runas";
try
{
Process.Start(startInfo);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Environment.Exit(0);
}
}