Skip to content

Commit

Permalink
升级基础组件,使用最新IPacket,其中Modbus还需要优化
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Dec 10, 2024
1 parent 4a3531d commit b8f3124
Show file tree
Hide file tree
Showing 14 changed files with 646 additions and 637 deletions.
16 changes: 8 additions & 8 deletions XCoder/CrazyCoder.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -62,32 +62,32 @@
<Content Include="数据库命名规范.txt" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="NewLife.Map" Version="2.6.2024.801" />
<PackageReference Include="NewLife.Map" Version="2.6.2024.1102" />
<PackageReference Include="NewLife.ModbusRTU" Version="1.8.2024.426-beta1011" />
<PackageReference Include="NewLife.Remoting" Version="3.0.2024.902" />
<PackageReference Include="NewLife.Remoting" Version="3.2.2024.1206" />
<PackageReference Include="System.Speech" Version="8.0.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0" />
<PackageReference Include="Microsoft.VisualBasic" Version="10.3.0" />
<PackageReference Include="NewLife.Core">
<Version>10.10.2024.902</Version>
<Version>11.1.2024.1206</Version>
</PackageReference>
<PackageReference Include="NewLife.MQTT">
<Version>2.0.2024.708</Version>
</PackageReference>
<PackageReference Include="NewLife.Net">
<Version>4.3.2024.903-beta0724</Version>
<Version>4.4.2024.1202</Version>
</PackageReference>
<PackageReference Include="NewLife.Redis">
<Version>5.7.2024.801</Version>
<Version>6.0.2024.1205</Version>
</PackageReference>
<PackageReference Include="NewLife.Stardust">
<Version>3.0.2024.902</Version>
<Version>3.2.2024.1203</Version>
</PackageReference>
<PackageReference Include="NewLife.XCode">
<Version>11.15.2024.902</Version>
<Version>11.16.2024.1202</Version>
</PackageReference>
<PackageReference Include="SSH.NET">
<Version>2024.1.0</Version>
<Version>2024.2.0</Version>
</PackageReference>
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
<PackageReference Include="System.Management" Version="8.0.0" />
Expand Down
56 changes: 26 additions & 30 deletions XCoder/XApi/MyApiController.cs
Original file line number Diff line number Diff line change
@@ -1,43 +1,39 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Text;
using NewLife;
using NewLife.Data;
using NewLife.Remoting;
using NewLife.Security;

namespace XApi
namespace XApi;

/// <summary>API控制器</summary>
//[AllowAnonymous]
public class MyApiController
{
/// <summary>API控制器</summary>
//[AllowAnonymous]
public class MyApiController
/// <summary>获取指定种类的环境信息</summary>
/// <param name="kind"></param>
/// <returns></returns>
public String Info(String kind)
{
/// <summary>获取指定种类的环境信息</summary>
/// <param name="kind"></param>
/// <returns></returns>
public String Info(String kind)
switch ((kind + "").ToLower())
{
switch ((kind + "").ToLower())
{
case "machine": return Environment.MachineName;
case "user": return Environment.UserName;
case "ip": return NetHelper.MyIP() + "";
case "time": return DateTime.Now.ToFullString();
default:
throw new ApiException(505, "不支持类型" + kind);
}
case "machine": return Environment.MachineName;
case "user": return Environment.UserName;
case "ip": return NetHelper.MyIP() + "";
case "time": return DateTime.Now.ToFullString();
default:
throw new ApiException(505, "不支持类型" + kind);
}
}

/// <summary>加密数据</summary>
/// <param name="data"></param>
/// <returns></returns>
public Packet Encrypt(Packet data)
{
//Log.XTrace.WriteLine("加密数据{0:n0}字节", data.Total);
/// <summary>加密数据</summary>
/// <param name="data"></param>
/// <returns></returns>
public IPacket Encrypt(IPacket data)
{
//Log.XTrace.WriteLine("加密数据{0:n0}字节", data.Total);

var buf = data.ToArray().RC4("NewLife".GetBytes());
var buf = data.ReadBytes().RC4("NewLife".GetBytes());

return buf;
}
return (ArrayPacket)buf;
}
}
1 change: 1 addition & 0 deletions XCoder/XCom/SerialPortList.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.ComponentModel;
using System.IO.Ports;
using System.Text;
using NewLife.Data;
using NewLife.Log;
using NewLife.Net;
using NewLife.Threading;
Expand Down
48 changes: 35 additions & 13 deletions XCoder/XCom/SerialTransport.cs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public virtual Boolean Close()
#region 发送
/// <summary>写入数据</summary>
/// <param name="pk">数据包</param>
public virtual Int32 Send(Packet pk)
public virtual Int32 Send(IPacket pk)
{
if (!Open()) return -1;

Expand All @@ -174,46 +174,66 @@ public virtual Int32 Send(Packet pk)
var sp = Serial;
lock (sp)
{
sp.Write(pk.Data, pk.Offset, pk.Count);
if (pk.TryGetArray(out var seg))
sp.Write(seg.Array, seg.Offset, seg.Count);
else
{
var buf = pk.ReadBytes();
sp.Write(buf, 0, buf.Length);
}
}

return pk.Total;
}

public Int32 Send(Byte[] buf) => Send((ArrayPacket)buf);

/// <summary>异步发送数据并等待响应</summary>
/// <param name="pk"></param>
/// <returns></returns>
public virtual async Task<Packet> SendAsync(Packet pk)
public virtual async Task<IOwnerPacket> SendAsync(IPacket pk)
{
if (!Open()) return null;

//if (Packet == null) Packet = new PacketProvider();

//var task = Packet.Add(pk, null, Timeout);

_Source = new TaskCompletionSource<Packet>();
_Source = new TaskCompletionSource<IOwnerPacket>();

if (pk != null)
{
WriteLog("SendAsync:{0}", pk.ToHex());

// 发送数据
Serial.Write(pk.Data, pk.Offset, pk.Count);
//Serial.Write(pk.Data, pk.Offset, pk.Count);
var sp = Serial;
if (pk.TryGetArray(out var seg))
sp.Write(seg.Array, seg.Offset, seg.Count);
else
{
var buf = pk.ReadBytes();
sp.Write(buf, 0, buf.Length);
}
}

return await _Source.Task;
}

/// <summary>接收数据</summary>
/// <returns></returns>
public virtual Packet Receive()
public virtual IOwnerPacket Receive()
{
if (!Open()) return null;

var task = SendAsync(null);
if (Timeout > 0 && !task.Wait(Timeout)) return null;

return task.Result;
//return task.Result;
var rs = task.ConfigureAwait(false).GetAwaiter().GetResult();
if (rs is OwnerPacket op) return op;

return rs;
}
#endregion

Expand All @@ -227,12 +247,14 @@ void DataReceived(Object sender, SerialDataReceivedEventArgs e)
WaitMore();
if (sp.BytesToRead > 0)
{
var buf = new Byte[sp.BytesToRead];
//var buf = new Byte[sp.BytesToRead];
var pk = new OwnerPacket(sp.BytesToRead);

var count = sp.Read(buf, 0, buf.Length);
var count = sp.Read(pk.Buffer, 0, pk.Length);
//if (count != buf.Length) buf = buf.ReadBytes(0, count);
//var ms = new MemoryStream(buf, 0, count, false);
var pk = new Packet(buf, 0, count);
//var pk = new ArrayPacket(buf, 0, count);
pk.Resize(count);

ProcessReceive(pk);
}
Expand Down Expand Up @@ -263,7 +285,7 @@ void WaitMore()
}
}

void ProcessReceive(Packet pk)
void ProcessReceive(IOwnerPacket pk)
{
try
{
Expand All @@ -284,10 +306,10 @@ void ProcessReceive(Packet pk)
}
}

private TaskCompletionSource<Packet> _Source;
private TaskCompletionSource<IOwnerPacket> _Source;
/// <summary>处理收到的数据。默认匹配同步接收委托</summary>
/// <param name="pk"></param>
internal virtual void OnReceive(Packet pk)
internal virtual void OnReceive(IOwnerPacket pk)
{
//// 同步匹配
//if (Packet != null && Packet.Match(pk, null)) return;
Expand Down
6 changes: 2 additions & 4 deletions XCoder/XNet/BenchHelper.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Threading.Tasks;
using NewLife.Data;
using NewLife.Data;
using NewLife.Net;

namespace XCoder.XNet;
Expand All @@ -13,7 +11,7 @@ static class BenchHelper
/// <param name="times">次数</param>
/// <param name="msInterval">间隔</param>
/// <returns></returns>
public static Task SendConcurrency(this ISocketRemote session, Packet pk, Int32 times, Int32 msInterval)
public static Task SendConcurrency(this ISocketRemote session, IPacket pk, Int32 times, Int32 msInterval)
{
var task = Task.Run(async () =>
{
Expand Down
1 change: 1 addition & 0 deletions XCoder/XNet/FrmApiDiscover.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Net;
using System.Runtime.Serialization;
using NewLife;
using NewLife.Data;
using NewLife.Log;
using NewLife.Net;
using NewLife.Remoting;
Expand Down
2 changes: 1 addition & 1 deletion XCoder/XNet/FrmMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ private void btnSend_Click(Object sender, EventArgs e)
for (var i = 0; i < count && _Server != null; i++)
{
var sw = Stopwatch.StartNew();
var cs = await _Server.SendAllAsync(buf);
var cs = await _Server.SendAllAsync(pk);
sw.Stop();
BizLog.Info("{3}/{4} 已向[{0}]个客户端发送[{1}]数据 {2:n0}ms", cs, buf.Length, sw.ElapsedMilliseconds, i + 1, count);
if (sleep > 0) await Task.Delay(sleep);
Expand Down
5 changes: 4 additions & 1 deletion XCoder/XNet/FrmModbusSlave.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.ComponentModel;
using NewLife;
using NewLife.Data;
using NewLife.IoT.Protocols;
using NewLife.Log;
using NewLife.Net;
Expand Down Expand Up @@ -265,7 +266,9 @@ private void OnReceived(Object sender, ReceivedEventArgs e)
var session = sender as NetSession;
if (session == null) return;

var msg = ModbusIpMessage.Read(e.Packet);
var pk = e.Packet as Packet;
if (pk == null) pk = new Packet(e.Packet.ReadBytes());
var msg = ModbusIpMessage.Read(pk);
if (msg == null) return;

session.Log?.Info("<= {0}", msg);
Expand Down
92 changes: 45 additions & 47 deletions XCoder/XNet/IPPacket.cs
Original file line number Diff line number Diff line change
@@ -1,54 +1,52 @@
using System;
using System.Net;
using System.Net;
using System.Net.Sockets;
using NewLife.Data;

namespace XCoder.XNet
namespace XCoder.XNet;

/// <summary>IP包</summary>
public class IPPacket
{
/// <summary>IP包</summary>
public class IPPacket
public Byte Version;
public Byte Length;
public Byte DiffServices;
public UInt16 DataLength;
public UInt16 Identification;
public Byte Flag;
public UInt16 Excursion;
public Byte TTL;
public ProtocolType Protocol;
public UInt16 CheckSum;
public IPAddress SrcAddr;
public IPAddress DestAddr;
public Byte[] Option;
public IPacket Data;

public IPPacket(IPacket pk)
{
public Byte Version;
public Byte Length;
public Byte DiffServices;
public UInt16 DataLength;
public UInt16 Identification;
public Byte Flag;
public UInt16 Excursion;
public Byte TTL;
public ProtocolType Protocol;
public UInt16 CheckSum;
public IPAddress SrcAddr;
public IPAddress DestAddr;
public Byte[] Option;
public Packet Data;

public IPPacket(Packet pk)
{
if (pk == null) throw new ArgumentNullException(nameof(pk));

var data = pk.ReadBytes(0, 20);

Version = (Byte)((data[0] & 0xF0) >> 4);
Length = (Byte)((data[0] & 0x0F) * 4);
DiffServices = data[1];
DataLength = (UInt16)((data[2] << 8) + data[3]);
Identification = (UInt16)((data[4] << 8) + data[5]);
Flag = (Byte)(data[6] >> 5);
Excursion = (UInt16)(((data[6] & 0x1F) << 8) + data[7]);
TTL = data[8];
Protocol = (ProtocolType)data[9];
CheckSum = (UInt16)((data[10] << 8) + data[11]);

SrcAddr = new IPAddress(pk.ReadBytes(12, 4));
DestAddr = new IPAddress(pk.ReadBytes(16, 4));

// 可选项
if (Length > 20) Option = pk.ReadBytes(20, Length - 20);

Data = pk.Slice(Length, DataLength);
}

public override String ToString() => $"{SrcAddr} => {DestAddr} [{DataLength}]";
if (pk == null) throw new ArgumentNullException(nameof(pk));

var data = pk.ReadBytes(0, 20);

Version = (Byte)((data[0] & 0xF0) >> 4);
Length = (Byte)((data[0] & 0x0F) * 4);
DiffServices = data[1];
DataLength = (UInt16)((data[2] << 8) + data[3]);
Identification = (UInt16)((data[4] << 8) + data[5]);
Flag = (Byte)(data[6] >> 5);
Excursion = (UInt16)(((data[6] & 0x1F) << 8) + data[7]);
TTL = data[8];
Protocol = (ProtocolType)data[9];
CheckSum = (UInt16)((data[10] << 8) + data[11]);

SrcAddr = new IPAddress(pk.ReadBytes(12, 4));
DestAddr = new IPAddress(pk.ReadBytes(16, 4));

// 可选项
if (Length > 20) Option = pk.ReadBytes(20, Length - 20);

Data = pk.Slice(Length, DataLength);
}

public override String ToString() => $"{SrcAddr} => {DestAddr} [{DataLength}]";
}
Loading

0 comments on commit b8f3124

Please sign in to comment.