using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Newtonsoft.Json;
using PLCSharp.VVMs.Connects.ModbusTcp;
using PLCSharp.VVMs.Connects.Socket;
using Prism.Mvvm;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
namespace PLCSharp.VVMs.Connects
{
public enum CommunicationDataType
{
String,
Bytes,
}
///
/// 连接
///
public class Connect : BindableBase
{
///
/// 唯一标识
///
[Key]
public Guid ID { get; set; } = Guid.NewGuid();
private bool SetWithPrompt(ref T field, T value, [System.Runtime.CompilerServices.CallerMemberName] string propName = null)
{
if (!EqualityComparer.Default.Equals(field, value))
Params.Prompt = "已修改,请保存";
return SetProperty(ref field, value, propName);
}
private string _Name;
///
/// 连接配置
///
public string Name
{
get => _Name;
set => SetWithPrompt(ref _Name, value);
}
private string _IP_SerialPort;
///
/// IP_串口端口
///
public string IP_SerialPort
{
get => _IP_SerialPort;
set => SetWithPrompt(ref _IP_SerialPort, value);
}
private int _Port;
///
/// 端口
///
public int Port
{
get => _Port;
set => SetWithPrompt(ref _Port, value);
}
private ProtocolType _Type;
///
/// 协议类型
///
[JsonIgnore]
public ProtocolType Type
{
get { return _Type; }
set
{
if (_Type == ProtocolType.Undefined)
{
if (value != ProtocolType.Undefined)
{
SetProperty(ref _Type, value);
}
}
else if (_Type != value)
{
MessageBox.Show("选定协议后不可改变!");
}
}
}
private string _Comment;
///
/// 备注
///
public string Comment
{
get => _Comment;
set => SetWithPrompt(ref _Comment, value);
}
#region NotMapped
private bool _LogSwitch;
///
/// 日志开关
///
[NotMapped]
public bool LogSwitch
{
get { return _LogSwitch; }
set { SetProperty(ref _LogSwitch, value); }
}
private bool _Connected;
///
/// 连接成功
///
[NotMapped]
public bool Connected
{
get { return _Connected; }
set { SetProperty(ref _Connected, value); }
}
private bool _Successful;
///
/// 读写成功
///
[NotMapped]
public bool Successful
{
get { return _Successful; }
set { SetProperty(ref _Successful, value); }
}
private bool _Online;
///
/// 在线
///
[NotMapped]
public bool Online
{
get { return _Online; }
set { SetProperty(ref _Online, value); }
}
private string _ReceiveInfo = "";
[NotMapped]
public string ReceiveInfo
{
get { return _ReceiveInfo; }
set { SetProperty(ref _ReceiveInfo, value); }
}
private byte[] _ReceiveData;
[NotMapped]
public byte[] ReceiveData
{
get { return _ReceiveData; }
set { SetProperty(ref _ReceiveData, value); }
}
private string _SendInfo;
[NotMapped]
public string SendInfo
{
get { return _SendInfo; }
set { SetProperty(ref _SendInfo, value); }
}
///
/// 告警信息
///
[NotMapped]
public string ErrInfo { get; set; } = "无异常";
///
/// 序列化Params
///
[Column("Params")]
public string SerializedParams
{
get => JsonConvert.SerializeObject(Params); // 自动序列化
set => Params = JsonConvert.DeserializeObject(value); // 自动反序列化
}
private ObservableCollection _DataItems = [];
///
/// 数据Items
///
[NotMapped]
public ObservableCollection DataItems
{
get => _DataItems;
set => SetProperty(ref _DataItems, value);
}
///
/// 序列化数据Items
///
[Column("DataItems")]
public string SerializedDataItems
{
get => JsonConvert.SerializeObject(DataItems); // 自动序列化
set => DataItems = value != null ? JsonConvert.DeserializeObject>(value) : []; // 自动反序列化
}
private bool _PollEnabled = true;
/// 是否启用轮询
[NotMapped]
public bool PollEnabled
{
get => _PollEnabled;
set => SetProperty(ref _PollEnabled, value);
}
private int _PollIntervalMs = 1000;
/// 轮询间隔(毫秒)
[NotMapped]
public int PollIntervalMs
{
get => _PollIntervalMs;
set
{
if (value < 100) value = 100;
if (value > 60000) value = 60000;
SetProperty(ref _PollIntervalMs, value);
}
}
private ConnectParams _Params;
///
/// 参数集合
///
[NotMapped]
public ConnectParams Params
{
get
{
_Params ??= new ConnectParams();
return _Params;
}
set
{
SetProperty(ref _Params, value);
}
}
private ObservableCollection _Clients = [];
///
/// Clients
///
[NotMapped]
public ObservableCollection Clients
{
get { return _Clients; }
set { SetProperty(ref _Clients, value); }
}
///
/// 序列化Clients
///
[Column("Clients")]
public string SerializedClients
{
get => JsonConvert.SerializeObject(Clients); // 自动序列化
set => Clients = JsonConvert.DeserializeObject>(value); // 自动反序列化
}
///
/// 打开
///
public virtual void Open() { }
///
/// 关闭
///
public virtual void Close() { }
///
/// 日志Queue
///
[NotMapped]
public ConcurrentQueue LogQueue { get; set; } = [];
///
/// 日志
///
/// 日志
public void Log(string log)
{
if (LogSwitch)
{
LogQueue.Enqueue(log);
if (LogQueue.Count > 1000)
LogQueue.TryDequeue(out _);
RaisePropertyChanged(nameof(LogQueue));
}
}
#endregion
///
/// HexStringToBytes
///
/// hexString
/// bytes
/// format
/// 返回布尔值
public static bool HexStringToBytes(string hexString, out List bytes, out string format)
{
format = hexString;
bytes = [];
var sendMsg = hexString.Replace(" ", "").Replace("-", "").Replace("\n", "").Replace("\r", "");
if (sendMsg.Length % 2 != 0)
{
sendMsg = "0" + sendMsg;
}
sendMsg = sendMsg.ToUpper();
bool isMatch = Regex.IsMatch(sendMsg, @"^[0-9A-Fa-f]+$");
if (isMatch)
{
StringBuilder sb = new();
for (int i = 0; i < sendMsg.Length; i++)
{
if (i > 0 && i % 2 == 0)
sb.Append(' '); // 每隔两位插入空格
sb.Append(sendMsg[i]);
}
format = sb.ToString();
var split = format.Split(" ");
for (int i = 0; i < split.Length; i++)
{
bytes.Add(byte.Parse(split[i], NumberStyles.HexNumber));
}
return true;
}
else
{
return false;
}
}
///
/// 发送Async
///
/// msg
/// 返回结果
public virtual async Task SendAsync(string msg)
{
if (Params.DataType == CommunicationDataType.String)
{
return await SendMsgAsync(msg);
}
else
{
if (HexStringToBytes(msg, out List bytes, out string format))
{
SendInfo = format;
return await SendDataAsync([.. bytes]);
}
else
{
ErrInfo = "请输入正确的十六进制字符串";
Log(ErrInfo);
return false;
}
}
}
///
/// 发送Async
///
/// msg
/// 客户端名称
/// 返回结果
public virtual async Task SendAsync(string msg, string clientName)
{
if (this is SocketServer server)
{
if (Params.DataType == CommunicationDataType.String)
{
return await server.SendMsgAsync(msg, clientName);
}
else
{
{
if (HexStringToBytes(msg, out List bytes, out string format))
{
SendInfo = format;
return await server.SendDataAsync([.. bytes], clientName);
}
else
{
ErrInfo = "请输入正确的十六进制字符串";
Log(ErrInfo);
return false;
}
}
}
}
else
{
ErrInfo = "此连接不是服务器";
Log(ErrInfo);
return false;
}
}
///
/// 发送HexMsgAsync
///
/// msg
/// 返回结果
public virtual async Task SendHexMsgAsync(string msg)
{
if (string.IsNullOrEmpty(msg))
{
Log($"{DateTime.Now:HH:mm:ss:fff} 消息为空,未发送");
return false;
}
byte[] bytes = Encoding.UTF8.GetBytes(msg);
return await SendDataAsync(bytes);
}
///
/// 发送MsgAsync
///
/// msg
/// 返回结果
public virtual async Task SendMsgAsync(string msg)
{
if (string.IsNullOrEmpty(msg))
{
ErrInfo = "消息为空,未发送";
Log($"{DateTime.Now:HH:mm:ss:fff} 消息为空,未发送");
return false;
}
byte[] bytes = Encoding.UTF8.GetBytes(msg);
return await SendDataAsync(bytes);
}
///
/// 发送数据Async
///
/// bytes
/// is日志
/// 返回结果
public virtual async Task SendDataAsync(byte[] bytes, bool isLog = true)
{
await Task.Delay(10);
return false;
}
///
/// 连接Params
///
public class ConnectParams : BindableBase
{
private CommunicationDataType _DataType;
///
/// 连接配置
///
public CommunicationDataType DataType
{
get { return _DataType; }
set
{
if (_DataType != value)
{
Prompt = "已修改,请保存";
}
SetProperty(ref _DataType, value);
}
}
private string _Prompt;
///
/// 提示
///
[JsonIgnore]
public string Prompt
{
get { return _Prompt; }
set { SetProperty(ref _Prompt, value); }
}
private byte _UnitId = 1;
///
/// UnitId
///
public byte UnitId
{
get => _UnitId;
set => SetProperty(ref _UnitId, value);
}
// ─── 串口参数 ───
private int _BaudRate = 9600;
///
/// BaudRate
///
public int BaudRate
{
get => _BaudRate;
set => SetProperty(ref _BaudRate, value);
}
private int _DataBits = 8;
///
/// 数据Bits
///
public int DataBits
{
get => _DataBits;
set => SetProperty(ref _DataBits, value);
}
private System.IO.Ports.StopBits _StopBits = System.IO.Ports.StopBits.One;
///
/// 停止Bits值
///
public System.IO.Ports.StopBits StopBitsValue
{
get => _StopBits;
set => SetProperty(ref _StopBits, value);
}
private System.IO.Ports.Parity _Parity = System.IO.Ports.Parity.None;
///
/// Parity值
///
public System.IO.Ports.Parity ParityValue
{
get => _Parity;
set => SetProperty(ref _Parity, value);
}
}
public enum StateEnum
{
Init,
Receive,
Sleep
}
}
}