using HslCommunication.Profinet.Melsec;
using HslCommunication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HslCommunication.Profinet.Siemens;
using HslCommunication.Core;
using Seyounth.Extensions.Plc;
using Seyounth.Auto.Plc.Helper;
namespace Seyounth.Auto.Plc.Business
{
public class SycSiemensS7Net : IPlc
{
public SiemensS7Net Melse;
///
/// 型号
///
public SiemensPLCS siemensPLCS;
///
/// 数据格式
///
public DataFormat dataFormat;
public string Host { get; }
public int Port { get; }
public bool IsConnected { get; }
public int ConnectTimeOut = 1500;
///
/// 构造函数
///
public SycSiemensS7Net(string Ip, int Port, SiemensPLCS siemensPLCType = SiemensPLCS.S1200, DataFormat dataFormat = DataFormat.ABCD)
{
Host = Ip;
this.Port = Port;
this.siemensPLCS = siemensPLCType;
this.dataFormat = dataFormat;
}
public async Task ConnectAsync()
{
if (string.IsNullOrWhiteSpace(Host)) return;
if (Host == default || Port == default) return;
Melse = new SiemensS7Net(siemensPLCS, Host);
Melse.Port = Port;
//Melse.SetPersistentConnection();
Melse.ConnectTimeOut = ConnectTimeOut;
await Melse.ConnectServerAsync();
}
public async Task DisconnectAsync()
{
await Melse.ConnectCloseAsync();
Melse.Dispose();
}
public async Task ReadAsync(string address, int count)
{
T[] result = new T[count];
var structName = typeof(T).ToString();
var ReadByteLength = AnalysisHelper.TructToByteCount(structName: structName);
var ReadRegLength = AnalysisHelper.TructToRegCount(structName: structName);
var operateResult = await Melse.ReadAsync(address, (ushort)(count * ReadRegLength));
if (!operateResult.IsSuccess)
{
throw new Exception(operateResult.Message);
}
for (int i = 0; i < count; i++)
{
T item = AnalysisHelper.ConvertBytes(operateResult.Content, Melse, i * ReadByteLength);
result[i] = item;
}
return result;
}
public async Task ReadStringAsync(string address, int length)
{
var operateResult = await Melse.ReadAsync(address, (ushort)length);
if (operateResult != null && operateResult.IsSuccess)
{
return Encoding.ASCII.GetString(operateResult.Content).Replace("\0", "").Trim();
}
return string.Empty;
}
public async Task ReadStringAsync(string address, int length, Encoding encoding)
{
var operateResult = await Melse.ReadAsync(address, (ushort)length);
if (operateResult != null && operateResult.IsSuccess)
{
return encoding.GetString(operateResult.Content).Replace("\0", "").Trim();
}
return string.Empty;
}
public Task WriteAsync(string address, params T[] values)
{
throw new NotImplementedException();
}
public async Task WriteStringAsync(string address, string value)
{
byte[] bytes = Encoding.ASCII.GetBytes(value);
await Melse.WriteAsync(address, bytes);
}
public async Task WriteStringAsync(string address, string value, Encoding encoding)
{
byte[] bytes = encoding.GetBytes(value);
await Melse.WriteAsync(address, bytes);
}
}
}