20240301_JSEQ_upperpc/JiangsuEarthquakeNowUI/JiangsuEarthquake/Models/RTUModel2.cs

135 lines
3.5 KiB
C#
Raw Permalink Normal View History

2024-11-01 07:54:08 +00:00
using JiangsuEarthquake.Common;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JiangsuEarthquake.Models
{
public class RTUModel2 : NotifyBase
{
//委托
public Action<List<byte>> ResponseData;
private static RTUModel2 _instance;
private static SerialInfo _serialInfo { get; set; }
private SerialPort _serialPort;
//是否忙
bool _isBusing = false;
//当前的从栈地址
int _currentSlave;
//功能码
int _funcCode;
//从栈长度
int _wordLen;
//起始地址
int _startAddr;
//私有实例化
public RTUModel2(SerialInfo serialInfo)
{
_serialPort = new SerialPort();
_serialInfo = serialInfo;
}
public static RTUModel2 GetInstance(SerialInfo serialInfo)
{
lock ("rtu")
{
if (_instance == null)
_instance = new RTUModel2(serialInfo);
return _instance;
}
}
//进行连接
public bool Connection()
{
try
{
if (_serialPort.IsOpen)
_serialPort.Close();
_serialPort.PortName = _serialInfo.PortName;
_serialPort.BaudRate = _serialInfo.BaudRate;
_serialPort.DataBits = _serialInfo.DataBit;
_serialPort.Parity = _serialInfo.Parity;
_serialPort.StopBits = _serialInfo.StopBits;
_serialPort.ReceivedBytesThreshold = 1;
_serialPort.DataReceived += _serialPort_DataReceived;
_serialPort.Open();
}
catch
{
return false;
}
return true;
}
public void Dispose()
{
if (_serialPort.IsOpen)
{
_serialPort.Close();
_serialPort.Dispose();
_serialPort = null;
_instance = null;
}
}
private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//将两秒没接收的数据作为1组
System.Threading.Thread.Sleep(2000);
//将缓冲区内字节数大小设置为数组大小
byte[] byteRead = new byte[_serialPort.BytesToRead];
//将缓冲区内数据写入字节数组中
_serialPort.Read(byteRead, 0, byteRead.Length);
//返回数据
ResponseData?.Invoke(new List<byte>(byteRead));
//清除输入缓冲区
_serialPort.DiscardInBuffer();
}
public async Task<bool> Send(byte[] _send)
{
try
{
//如果发送在忙 就通过_isBusing 把它卡在这个地方
while (_isBusing)
{
}
//每次请求的时候把它置成0
//_receiveByteCount = 0;
//设置当前状态为忙
_isBusing = true;
//发送到第八个字节
_serialPort.Write(_send, 0, _send.Length);
//设置当前状态为不忙
_isBusing = false;
await Task.Delay(1000);
}
catch (Exception)
{
return false;
}
return true;
}
}
}