94 lines
2.4 KiB
C#
94 lines
2.4 KiB
C#
|
|
using System;
|
|||
|
|
using System.Collections.Generic;
|
|||
|
|
using System.Linq;
|
|||
|
|
using System.Text;
|
|||
|
|
using System.Threading.Tasks;
|
|||
|
|
using AutomaticApp.Common;
|
|||
|
|
using Communication;
|
|||
|
|
using Communication.Modbus;
|
|||
|
|
|
|||
|
|
namespace AutomaticApp.Models
|
|||
|
|
{
|
|||
|
|
//串口通信类
|
|||
|
|
public class ComModel : NotifyBase
|
|||
|
|
{
|
|||
|
|
RTU rtuInstance = null;
|
|||
|
|
|
|||
|
|
private BeiDouModel BeiDouModel { get; set; } = new BeiDouModel();
|
|||
|
|
|
|||
|
|
private SerialInfo serialInfo = new SerialInfo()
|
|||
|
|
{
|
|||
|
|
PortName = tools.GetAppSetting("PortName").Trim(),//端口号
|
|||
|
|
BaudRate = Convert.ToInt32(tools.GetAppSetting("BaudRate").Trim()),
|
|||
|
|
DataBit = 8,
|
|||
|
|
Parity = System.IO.Ports.Parity.None,
|
|||
|
|
StopBits = System.IO.Ports.StopBits.One
|
|||
|
|
};
|
|||
|
|
/// <summary>
|
|||
|
|
/// 串口连接信息1
|
|||
|
|
/// </summary>
|
|||
|
|
//public SerialInfo SerialInfo
|
|||
|
|
//{
|
|||
|
|
// get { return serialInfo; }
|
|||
|
|
// set { serialInfo = value; this.DoNotify(); }
|
|||
|
|
//}
|
|||
|
|
|
|||
|
|
|
|||
|
|
private bool isConnected;
|
|||
|
|
/// <summary>
|
|||
|
|
/// 是否连接
|
|||
|
|
/// </summary>
|
|||
|
|
public bool IsConnected
|
|||
|
|
{
|
|||
|
|
get { return isConnected; }
|
|||
|
|
set { isConnected = value; this.DoNotify(); }
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 建立连接
|
|||
|
|
/// </summary>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public bool DoConnect(SerialInfo serialInfo)
|
|||
|
|
{
|
|||
|
|
rtuInstance = RTU.GetInstance(serialInfo);
|
|||
|
|
rtuInstance.ResponseData = new Action<List<byte>>(BeiDouModel.ParsingData);
|
|||
|
|
IsConnected = rtuInstance.Connection();
|
|||
|
|
return IsConnected;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
/// <summary>
|
|||
|
|
/// 断开连接
|
|||
|
|
/// </summary>
|
|||
|
|
/// <returns></returns>
|
|||
|
|
public bool DisConnect()
|
|||
|
|
{
|
|||
|
|
rtuInstance.Dispose();
|
|||
|
|
IsConnected = false;
|
|||
|
|
return IsConnected;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
public bool SendMessage(byte[] _send)
|
|||
|
|
{
|
|||
|
|
if (_send.Length == 0)
|
|||
|
|
return false;
|
|||
|
|
try
|
|||
|
|
{
|
|||
|
|
if (IsConnected)
|
|||
|
|
{
|
|||
|
|
rtuInstance.Send(_send);
|
|||
|
|
return true;
|
|||
|
|
}
|
|||
|
|
else
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
catch (Exception ex)
|
|||
|
|
{
|
|||
|
|
return false;
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
}
|