initial commit
This commit is contained in:
134
Lab505.Sim/ApiModels.cs
Normal file
134
Lab505.Sim/ApiModels.cs
Normal file
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
|
||||
#region API Models
|
||||
|
||||
/// <summary>
|
||||
/// Base API result
|
||||
/// </summary>
|
||||
public class ApiResult
|
||||
{
|
||||
public bool IsSuccess { get; set; }
|
||||
public string Message { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Robot state result
|
||||
/// </summary>
|
||||
public class RobotStateResult : ApiResult
|
||||
{
|
||||
public RobotStateData? Data { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Robot state data
|
||||
/// </summary>
|
||||
public class RobotStateData
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public Guid MapId { get; set; }
|
||||
public bool IsOnline { get; set; }
|
||||
public string State { get; set; } = string.Empty;
|
||||
public VdaStateMsg StateMsg { get; set; } = new();
|
||||
public VdaVisualizationMsg VisualizationMsg { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VDA5050 State message
|
||||
/// </summary>
|
||||
public class VdaStateMsg
|
||||
{
|
||||
public uint HeaderId { get; set; }
|
||||
public string? Timestamp { get; set; }
|
||||
public string? Version { get; set; }
|
||||
public string? Manufacturer { get; set; }
|
||||
public string? SerialNumber { get; set; }
|
||||
public string? OrderId { get; set; }
|
||||
public int OrderUpdateId { get; set; }
|
||||
public string? LastNodeId { get; set; }
|
||||
public int LastNodeSequenceId { get; set; }
|
||||
public bool Driving { get; set; }
|
||||
public bool Paused { get; set; }
|
||||
public bool NewBaseRequest { get; set; }
|
||||
public double DistanceSinceLastNode { get; set; }
|
||||
public string? OperatingMode { get; set; }
|
||||
public VdaAgvPosition AgvPosition { get; set; } = new();
|
||||
public VdaActionState[] ActionStates { get; set; } = [];
|
||||
public VdaError[] Errors { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VDA5050 Visualization message
|
||||
/// </summary>
|
||||
public class VdaVisualizationMsg
|
||||
{
|
||||
public uint HeaderId { get; set; }
|
||||
public string? Timestamp { get; set; }
|
||||
public string? Version { get; set; }
|
||||
public string? Manufacturer { get; set; }
|
||||
public string? SerialNumber { get; set; }
|
||||
public VdaAgvPosition AgvPosition { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// AGV Position
|
||||
/// </summary>
|
||||
public class VdaAgvPosition
|
||||
{
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Theta { get; set; }
|
||||
public string? MapId { get; set; }
|
||||
public bool PositionInitialized { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Action state
|
||||
/// </summary>
|
||||
public class VdaActionState
|
||||
{
|
||||
// VDA5050 field name là "actionId" (camelCase) — robot báo về với key này.
|
||||
[JsonPropertyName("actionId")]
|
||||
public string ActionID { get; set; } = string.Empty;
|
||||
public string ActionType { get; set; } = string.Empty;
|
||||
public string? ActionDescription { get; set; }
|
||||
public string ActionStatus { get; set; } = string.Empty; // WAITING, INITIALIZING, RUNNING, FINISHED, FAILED, PAUSED
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// VDA Error
|
||||
/// </summary>
|
||||
public class VdaError
|
||||
{
|
||||
public string ErrorType { get; set; } = string.Empty;
|
||||
public string? ErrorDescription { get; set; }
|
||||
public string ErrorLevel { get; set; } = string.Empty; // WARNING, FATAL
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Instant action request
|
||||
/// </summary>
|
||||
public class VdaInstantAction
|
||||
{
|
||||
public string ActionId { get; set; } = string.Empty;
|
||||
public string ActionType { get; set; } = string.Empty;
|
||||
public string ActionDescription { get; set; } = string.Empty;
|
||||
public string BlockingType { get; set; } = "NONE";
|
||||
public List<VdaActionParameter> ActionParameters { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Action parameter
|
||||
/// </summary>
|
||||
public class VdaActionParameter
|
||||
{
|
||||
public string Key { get; set; } = string.Empty;
|
||||
public string Value { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
#endregion
|
||||
451
Lab505.Sim/ConveyorModbusServer.cs
Normal file
451
Lab505.Sim/ConveyorModbusServer.cs
Normal file
@@ -0,0 +1,451 @@
|
||||
using Lab505.Shared;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class ConveyorModbusServer(int port = 503) : IDisposable
|
||||
{
|
||||
private TcpListener? _listener;
|
||||
private CancellationTokenSource? _cts;
|
||||
private readonly bool[] Coils = new bool[70000];
|
||||
private readonly ushort[] HoldingRegisters = new ushort[70000];
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Dictionary<ushort, CancellationTokenSource> _autoOffMap = [];
|
||||
private bool _isRunning;
|
||||
// Rising-edge tracking — only fire sensor task when a coil transitions false→true
|
||||
private bool _prevC1Active;
|
||||
private bool _prevC2Active;
|
||||
|
||||
public int Port { get; } = port;
|
||||
public bool IsRunning => _isRunning;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Already running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_listener = new TcpListener(IPAddress.Any, Port);
|
||||
_listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
_listener.Start();
|
||||
_isRunning = true;
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Server started");
|
||||
|
||||
// NReady = true by default (conveyor ready to receive)
|
||||
Coils[(ushort)ConveyorCoilAddress.C1Ready] = true;
|
||||
Coils[(ushort)ConveyorCoilAddress.C2Ready] = true;
|
||||
|
||||
// Start sensor simulation tasks
|
||||
StartSensorSimulation();
|
||||
|
||||
Task.Run(async () =>
|
||||
{
|
||||
while (!_cts.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync(_cts.Token);
|
||||
_ = Task.Run(() => HandleClient(client));
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch { }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void StartSensorSimulation()
|
||||
{
|
||||
// Simulate C1 sensors
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
while (!_cts?.IsCancellationRequested ?? false)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
SimulateC1Sensors();
|
||||
}
|
||||
});
|
||||
|
||||
// Simulate C2 sensors
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
while (!_cts?.IsCancellationRequested ?? false)
|
||||
{
|
||||
await Task.Delay(100);
|
||||
SimulateC2Sensors();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SimulateC1Sensors()
|
||||
{
|
||||
bool c1Active = GetCoil(ConveyorCoilAddress.C1In)
|
||||
|| GetCoil(ConveyorCoilAddress.C1Out)
|
||||
|| GetCoil(ConveyorCoilAddress.C1IMRin)
|
||||
|| GetCoil(ConveyorCoilAddress.C1IMRout);
|
||||
|
||||
// Only fire once per rising edge (false → true) to avoid spawning duplicate tasks
|
||||
bool risingEdge = c1Active && !_prevC1Active;
|
||||
_prevC1Active = c1Active;
|
||||
|
||||
if (!risingEdge) return;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C1HasGoods] = true;
|
||||
Coils[(ushort)ConveyorCoilAddress.C1NotGoods] = false;
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C1HasGoods] = false;
|
||||
Coils[(ushort)ConveyorCoilAddress.C1NotGoods] = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void SimulateC2Sensors()
|
||||
{
|
||||
bool c2Active = GetCoil(ConveyorCoilAddress.C2In)
|
||||
|| GetCoil(ConveyorCoilAddress.C2Out);
|
||||
|
||||
// Only fire once per rising edge (false → true) to avoid spawning duplicate tasks
|
||||
bool risingEdge = c2Active && !_prevC2Active;
|
||||
_prevC2Active = c2Active;
|
||||
|
||||
if (!risingEdge) return;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C2HasGoods] = true;
|
||||
Coils[(ushort)ConveyorCoilAddress.C2NotGoods] = false;
|
||||
}
|
||||
|
||||
await Task.Delay(5000);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[(ushort)ConveyorCoilAddress.C2HasGoods] = false;
|
||||
Coils[(ushort)ConveyorCoilAddress.C2NotGoods] = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ScheduleAutoOff(ushort addr, int ms = 5000)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_autoOffMap.TryGetValue(addr, out var old))
|
||||
old.Cancel();
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
_autoOffMap[addr] = cts;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(ms, cts.Token);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = false;
|
||||
_autoOffMap.Remove(addr);
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Auto-off coil 0x{addr:X4}");
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Not running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
try
|
||||
{
|
||||
_listener?.Stop();
|
||||
_listener?.Server?.Close();
|
||||
_listener?.Server?.Dispose();
|
||||
}
|
||||
catch { }
|
||||
_listener = null;
|
||||
|
||||
_isRunning = false;
|
||||
//Console.WriteLine($"[Conveyor ModbusSim:{Port}] Server stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public void SetCoil(ushort addr, bool val)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = val;
|
||||
|
||||
if (val)
|
||||
{
|
||||
// Check if this coil should auto-off
|
||||
if (ShouldAutoOff(addr))
|
||||
{
|
||||
ScheduleAutoOff(addr, 5000);
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"[Conveyor ModbusSim:{Port}] Set coil 0x{addr:X4} = TRUE (persistent)");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Cancel auto-off nếu đang chờ
|
||||
if (_autoOffMap.TryGetValue(addr, out var cts))
|
||||
{
|
||||
cts.Cancel();
|
||||
_autoOffMap.Remove(addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Kiểm tra coil có cần auto-off không
|
||||
/// Loại trừ: HasGoods, NotGoods, NReady, C2Out
|
||||
/// </summary>
|
||||
private static bool ShouldAutoOff(ushort addr)
|
||||
{
|
||||
return addr switch
|
||||
{
|
||||
// C1 - Không auto-off
|
||||
(ushort)ConveyorCoilAddress.C1HasGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C1NotGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C1Ready => false,
|
||||
|
||||
// C2 - Không auto-off
|
||||
(ushort)ConveyorCoilAddress.C2Out => false,
|
||||
(ushort)ConveyorCoilAddress.C2HasGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C2NotGoods => false,
|
||||
(ushort)ConveyorCoilAddress.C2Ready => false,
|
||||
|
||||
// Tất cả các coil khác đều auto-off
|
||||
_ => true
|
||||
};
|
||||
}
|
||||
|
||||
public void SetCoil(ConveyorCoilAddress addr, bool val) => SetCoil((ushort)addr, val);
|
||||
public bool GetCoil(ushort addr) { lock (_lock) return Coils[addr]; }
|
||||
public bool GetCoil(ConveyorCoilAddress addr) => GetCoil((ushort)addr);
|
||||
public void SetRegister(ushort addr, ushort val) { lock (_lock) HoldingRegisters[addr] = val; }
|
||||
public ushort GetRegister(ushort addr) { lock (_lock) return HoldingRegisters[addr]; }
|
||||
|
||||
private void HandleClient(TcpClient client)
|
||||
{
|
||||
using var stream = client.GetStream();
|
||||
var buf = new byte[260];
|
||||
|
||||
try
|
||||
{
|
||||
while (client.Connected)
|
||||
{
|
||||
int len = stream.Read(buf, 0, buf.Length);
|
||||
if (len <= 0) break;
|
||||
if (len < 8) continue;
|
||||
|
||||
byte fc = buf[7];
|
||||
byte[] res;
|
||||
|
||||
try
|
||||
{
|
||||
res = fc switch
|
||||
{
|
||||
0x01 => HandleReadCoils(buf),
|
||||
0x02 => HandleReadCoils(buf),
|
||||
0x03 => HandleReadRegisters(buf),
|
||||
0x04 => HandleReadRegisters(buf),
|
||||
0x05 => HandleWriteSingleCoil(buf),
|
||||
0x06 => HandleWriteSingleRegister(buf),
|
||||
0x0F => HandleWriteMultiCoils(buf),
|
||||
0x10 => HandleWriteMultiRegisters(buf),
|
||||
_ => BuildException(buf, 0x01)
|
||||
};
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
res = BuildException(buf, 0x04);
|
||||
}
|
||||
|
||||
stream.Write(res);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[Conveyor ModbusSim:{Port}] Client error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] HandleReadCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
int byteCount = (qty + 7) / 8;
|
||||
var payload = new byte[byteCount];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort addr = (ushort)(start + i);
|
||||
bool value = Coils[addr];
|
||||
|
||||
if (value)
|
||||
payload[i / 8] |= (byte)(1 << (i % 8));
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleReadRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
var payload = new byte[qty * 2];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort val = HoldingRegisters[start + i];
|
||||
payload[i * 2] = (byte)(val >> 8);
|
||||
payload[i * 2 + 1] = (byte)(val & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleCoil(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
bool val = req[10] == 0xFF;
|
||||
|
||||
SetCoil(addr, val);
|
||||
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleRegister(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort val = (ushort)(req[10] << 8 | req[11]);
|
||||
lock (_lock) HoldingRegisters[addr] = val;
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
int mask = 1 << (i % 8);
|
||||
int byteIndex = 13 + i / 8;
|
||||
bool val = (req[byteIndex] & mask) != 0;
|
||||
SetCoil((ushort)(start + i), val);
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort v = (ushort)(req[13 + i * 2] << 8 | req[14 + i * 2]);
|
||||
HoldingRegisters[start + i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private static byte[] BuildResponse(byte[] req, byte[] data)
|
||||
{
|
||||
byte[] res = new byte[9 + data.Length];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
|
||||
int length = 1 + 1 + 1 + data.Length;
|
||||
res[4] = (byte)(length >> 8);
|
||||
res[5] = (byte)(length & 0xFF);
|
||||
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
res[8] = (byte)data.Length;
|
||||
|
||||
Buffer.BlockCopy(data, 0, res, 9, data.Length);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private static byte[] EchoWithCorrectLength(byte[] req)
|
||||
{
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 12);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
return res;
|
||||
}
|
||||
|
||||
private static byte[] BuildException(byte[] req, byte code)
|
||||
{
|
||||
return
|
||||
[
|
||||
req[0], req[1],
|
||||
0x00, 0x00,
|
||||
0x00, 0x03,
|
||||
req[6],
|
||||
(byte)(req[7] | 0x80),
|
||||
code
|
||||
];
|
||||
}
|
||||
}
|
||||
25
Lab505.Sim/Lab505.Sim.csproj
Normal file
25
Lab505.Sim/Lab505.Sim.csproj
Normal file
@@ -0,0 +1,25 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<RuntimeIdentifiers>linux-x64</RuntimeIdentifiers>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<UseAppHost>false</UseAppHost>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.6" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.6" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Configuration" Version="1.5.378.134" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Core" Version="1.5.378.134" />
|
||||
<PackageReference Include="OPCFoundation.NetStandard.Opc.Ua.Server" Version="1.5.378.134" />
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.6" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\Lab505.Shared\Lab505.Shared.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
62
Lab505.Sim/ModbusSimulationHostedService.cs
Normal file
62
Lab505.Sim/ModbusSimulationHostedService.cs
Normal file
@@ -0,0 +1,62 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Hosted service để start/stop các Modbus simulation servers
|
||||
/// Port 502: ASRS
|
||||
/// Port 503: Conveyor
|
||||
/// </summary>
|
||||
public class ModbusSimulationHostedService : IHostedService
|
||||
{
|
||||
private readonly ModbusSimulationServer_ASRS _asrsServer;
|
||||
private readonly ConveyorModbusServer _conveyorServer;
|
||||
private readonly ILogger<ModbusSimulationHostedService> _logger;
|
||||
|
||||
public ModbusSimulationHostedService(ILogger<ModbusSimulationHostedService> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_asrsServer = new ModbusSimulationServer_ASRS(502);
|
||||
_conveyorServer = new ConveyorModbusServer(503);
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Starting Modbus Simulation Servers...");
|
||||
|
||||
try
|
||||
{
|
||||
_asrsServer.Start();
|
||||
_logger.LogInformation("✅ ASRS Modbus Simulation Server started on port 502");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "❌ Failed to start ASRS Modbus server on port 502");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_conveyorServer.Start();
|
||||
_logger.LogInformation("✅ Conveyor Modbus Simulation Server started on port 503");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "❌ Failed to start Conveyor Modbus server on port 503");
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Stopping Modbus Simulation Servers...");
|
||||
|
||||
_asrsServer.Stop();
|
||||
_conveyorServer.Stop();
|
||||
|
||||
_logger.LogInformation("✅ All Modbus Simulation Servers stopped");
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
557
Lab505.Sim/ModbusSimulationServer.cs
Normal file
557
Lab505.Sim/ModbusSimulationServer.cs
Normal file
@@ -0,0 +1,557 @@
|
||||
using Lab505.Shared;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class ModbusSimulationServer_ASRS : IDisposable
|
||||
{
|
||||
private TcpListener? _listener;
|
||||
private CancellationTokenSource? _cts;
|
||||
private readonly bool[] Coils = new bool[70000];
|
||||
private readonly ushort[] HoldingRegisters = new ushort[70000];
|
||||
private readonly Lock _lock = new();
|
||||
private readonly Dictionary<ushort, CancellationTokenSource> _autoOffMap = [];
|
||||
private bool _isRunning;
|
||||
|
||||
public int Port { get; }
|
||||
public bool IsRunning => _isRunning;
|
||||
|
||||
public ModbusSimulationServer_ASRS(int port = 502) => Port = port;
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Already running");
|
||||
return;
|
||||
}
|
||||
|
||||
// Initialize safety mode (required for operations)
|
||||
SetCoil((ushort)AsrsCoilAddress.SAFETY_MODE, true);
|
||||
|
||||
// Initialize all trays as FULL by default
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, true);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, true);
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_listener = new TcpListener(IPAddress.Any, Port);
|
||||
_listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
||||
_listener.Start();
|
||||
_isRunning = true;
|
||||
|
||||
Task.Run(async () =>
|
||||
{
|
||||
while (!_cts.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = await _listener.AcceptTcpClientAsync(_cts.Token);
|
||||
_ = Task.Run(() => HandleClient(client));
|
||||
}
|
||||
catch (OperationCanceledException) { break; }
|
||||
catch { }
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void ScheduleAutoOff(ushort addr, int ms = 5000)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_autoOffMap.TryGetValue(addr, out var old))
|
||||
old.Cancel();
|
||||
|
||||
var cts = new CancellationTokenSource();
|
||||
_autoOffMap[addr] = cts;
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(ms, cts.Token);
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = false;
|
||||
_autoOffMap.Remove(addr);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) { }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Not running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
try
|
||||
{
|
||||
_listener?.Stop();
|
||||
_listener?.Server?.Close();
|
||||
_listener?.Server?.Dispose();
|
||||
}
|
||||
catch { }
|
||||
_listener = null;
|
||||
|
||||
_isRunning = false;
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
public void SetCoil(ushort addr, bool val)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Coils[addr] = val;
|
||||
|
||||
if (val)
|
||||
{
|
||||
if (IsPulseCoil(addr))
|
||||
{
|
||||
ScheduleAutoOff(addr, 5000);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (_autoOffMap.TryGetValue(addr, out var cts))
|
||||
{
|
||||
cts.Cancel();
|
||||
_autoOffMap.Remove(addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void SetCoil(AsrsCoilAddress addr, bool val) => SetCoil((ushort)addr, val);
|
||||
public bool GetCoil(ushort addr) { lock (_lock) return Coils[addr]; }
|
||||
public bool GetCoil(AsrsCoilAddress addr) => GetCoil((ushort)addr);
|
||||
public void SetRegister(ushort addr, ushort val) { lock (_lock) HoldingRegisters[addr] = val; }
|
||||
public ushort GetRegister(ushort addr) { lock (_lock) return HoldingRegisters[addr]; }
|
||||
|
||||
private void HandleClient(TcpClient client)
|
||||
{
|
||||
using var stream = client.GetStream();
|
||||
var buf = new byte[260];
|
||||
|
||||
try
|
||||
{
|
||||
while (client.Connected)
|
||||
{
|
||||
int len = stream.Read(buf, 0, buf.Length);
|
||||
if (len <= 0) break;
|
||||
if (len < 8) continue;
|
||||
|
||||
byte fc = buf[7];
|
||||
byte[] res;
|
||||
|
||||
try
|
||||
{
|
||||
res = fc switch
|
||||
{
|
||||
0x01 => HandleReadCoils(buf),
|
||||
0x02 => HandleReadCoils(buf),
|
||||
0x03 => HandleReadRegisters(buf),
|
||||
0x04 => HandleReadRegisters(buf),
|
||||
0x05 => HandleWriteSingleCoil(buf),
|
||||
0x06 => HandleWriteSingleRegister(buf),
|
||||
0x0F => HandleWriteMultiCoils(buf),
|
||||
0x10 => HandleWriteMultiRegisters(buf),
|
||||
_ => BuildException(buf, 0x01)
|
||||
};
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
res = BuildException(buf, 0x04);
|
||||
}
|
||||
|
||||
stream.Write(res);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[ASRS ModbusSim:{Port}] Client error: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] HandleReadCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
int byteCount = (qty + 7) / 8;
|
||||
var payload = new byte[byteCount];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort addr = (ushort)(start + i);
|
||||
bool value = Coils[addr];
|
||||
|
||||
if (value)
|
||||
payload[i / 8] |= (byte)(1 << (i % 8));
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleReadRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
var payload = new byte[qty * 2];
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort val = HoldingRegisters[start + i];
|
||||
payload[i * 2] = (byte)(val >> 8);
|
||||
payload[i * 2 + 1] = (byte)(val & 0xFF);
|
||||
}
|
||||
}
|
||||
|
||||
return BuildResponse(req, payload);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleCoil(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
bool val = req[10] == 0xFF;
|
||||
|
||||
SetCoil(addr, val);
|
||||
|
||||
// ASRS TRIGGER HANDLING
|
||||
if (val)
|
||||
{
|
||||
bool mode_S12 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_EMPTY_BOX_1_2);
|
||||
bool mode_S34 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_EMPTY_BOX_3_4);
|
||||
bool mode_R12 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_FROM_CONVEYOR_1_2);
|
||||
bool mode_R43 = GetCoil((ushort)AsrsCoilAddress.MODE_PICK_FROM_CONVEYOR_3_4);
|
||||
|
||||
if (addr == (ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X1)
|
||||
{
|
||||
if (mode_S12) Trigger_X1_S12();
|
||||
if (mode_S34) Trigger_X1_S34();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X2)
|
||||
{
|
||||
if (mode_S12) Trigger_X2_S12();
|
||||
if (mode_S34) Trigger_X2_S34();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X3)
|
||||
{
|
||||
if (mode_S12) Trigger_X3_S12();
|
||||
if (mode_S34) Trigger_X3_S34();
|
||||
}
|
||||
|
||||
if (addr == (ushort)AsrsCoilAddress.RETURN_TRAY_X1)
|
||||
{
|
||||
if (mode_R12) Trigger_X1_R12();
|
||||
if (mode_R43) Trigger_X1_R43();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.RETURN_TRAY_X2)
|
||||
{
|
||||
if (mode_R12) Trigger_X2_R12();
|
||||
if (mode_R43) Trigger_X2_R43();
|
||||
}
|
||||
if (addr == (ushort)AsrsCoilAddress.RETURN_TRAY_X3)
|
||||
{
|
||||
if (mode_R12) Trigger_X3_R12();
|
||||
if (mode_R43) Trigger_X3_R43();
|
||||
}
|
||||
|
||||
// SYSTEM HOMING
|
||||
if (addr == (ushort)AsrsCoilAddress.SYSTEM_HOMING)
|
||||
{
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(1000);
|
||||
SetCoil((ushort)AsrsCoilAddress.SYSTEM_HOMING_SUCCESS, true);
|
||||
});
|
||||
}
|
||||
|
||||
// RESET FULL TRAY ALERTS
|
||||
if (addr == (ushort)AsrsCoilAddress.RESET_FULL_TRAY_ALERT)
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, false);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, false);
|
||||
}
|
||||
}
|
||||
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteSingleRegister(byte[] req)
|
||||
{
|
||||
ushort addr = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort val = (ushort)(req[10] << 8 | req[11]);
|
||||
lock (_lock) HoldingRegisters[addr] = val;
|
||||
return EchoWithCorrectLength(req);
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiCoils(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
int mask = 1 << (i % 8);
|
||||
int byteIndex = 13 + i / 8;
|
||||
bool val = (req[byteIndex] & mask) != 0;
|
||||
SetCoil((ushort)(start + i), val);
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] HandleWriteMultiRegisters(byte[] req)
|
||||
{
|
||||
ushort start = (ushort)(req[8] << 8 | req[9]);
|
||||
ushort qty = (ushort)(req[10] << 8 | req[11]);
|
||||
|
||||
lock (_lock)
|
||||
{
|
||||
for (int i = 0; i < qty; i++)
|
||||
{
|
||||
ushort v = (ushort)(req[13 + i * 2] << 8 | req[14 + i * 2]);
|
||||
HoldingRegisters[start + i] = v;
|
||||
}
|
||||
}
|
||||
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
Buffer.BlockCopy(req, 8, res, 8, 4);
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] BuildResponse(byte[] req, byte[] data)
|
||||
{
|
||||
byte[] res = new byte[9 + data.Length];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 6);
|
||||
|
||||
int length = 1 + 1 + 1 + data.Length;
|
||||
res[4] = (byte)(length >> 8);
|
||||
res[5] = (byte)(length & 0xFF);
|
||||
|
||||
res[6] = req[6];
|
||||
res[7] = req[7];
|
||||
res[8] = (byte)data.Length;
|
||||
|
||||
Buffer.BlockCopy(data, 0, res, 9, data.Length);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] EchoWithCorrectLength(byte[] req)
|
||||
{
|
||||
var res = new byte[12];
|
||||
Buffer.BlockCopy(req, 0, res, 0, 12);
|
||||
res[4] = 0x00;
|
||||
res[5] = 0x06;
|
||||
return res;
|
||||
}
|
||||
|
||||
private byte[] BuildException(byte[] req, byte code)
|
||||
{
|
||||
return new byte[]
|
||||
{
|
||||
req[0], req[1],
|
||||
0x00, 0x00,
|
||||
0x00, 0x03,
|
||||
req[6],
|
||||
(byte)(req[7] | 0x80),
|
||||
code
|
||||
};
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// PICK OPERATIONS - S12 (Shelf 1-2)
|
||||
// ============================================================
|
||||
private Task Run_X1_S12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S12: X21 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S12: X11 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_S12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S12: X22 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S12: X12 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_S12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S12: X23 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S12: X13 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// PICK OPERATIONS - S34 (Shelf 3-4)
|
||||
// ============================================================
|
||||
private Task Run_X1_S34() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S34: X41 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, false);
|
||||
Console.WriteLine("[ASRS Sim] X1_S34: X31 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_S34() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S34: X42 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, false);
|
||||
Console.WriteLine("[ASRS Sim] X2_S34: X32 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_S34() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S34: X43 → EMPTY");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, false);
|
||||
Console.WriteLine("[ASRS Sim] X3_S34: X33 → EMPTY (Complete)");
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// RETURN OPERATIONS - R12 (Return to Shelf 1-2)
|
||||
// ============================================================
|
||||
private Task Run_X1_R12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_21, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R12: X21 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_11, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R12: X11 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_R12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_22, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R12: X22 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_12, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R12: X12 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_R12() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_23, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R12: X23 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_13, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R12: X13 → FULL (Complete)");
|
||||
});
|
||||
|
||||
// ============================================================
|
||||
// RETURN OPERATIONS - R43 (Return to Shelf 3-4)
|
||||
// ============================================================
|
||||
private Task Run_X1_R43() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_41, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R43: X41 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_31, true);
|
||||
Console.WriteLine("[ASRS Sim] X1_R43: X31 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X2_R43() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_42, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R43: X42 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_32, true);
|
||||
Console.WriteLine("[ASRS Sim] X2_R43: X32 → FULL (Complete)");
|
||||
});
|
||||
|
||||
private Task Run_X3_R43() => Task.Run(async () =>
|
||||
{
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_43, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R43: X43 → FULL");
|
||||
await Task.Delay(5000);
|
||||
SetCoil((ushort)AsrsCoilAddress.FULL_TRAY_ALERT_33, true);
|
||||
Console.WriteLine("[ASRS Sim] X3_R43: X33 → FULL (Complete)");
|
||||
});
|
||||
|
||||
public void Trigger_X1_S12() { _ = Run_X1_S12(); }
|
||||
public void Trigger_X2_S12() { _ = Run_X2_S12(); }
|
||||
public void Trigger_X3_S12() { _ = Run_X3_S12(); }
|
||||
public void Trigger_X1_S34() { _ = Run_X1_S34(); }
|
||||
public void Trigger_X2_S34() { _ = Run_X2_S34(); }
|
||||
public void Trigger_X3_S34() { _ = Run_X3_S34(); }
|
||||
public void Trigger_X1_R12() { _ = Run_X1_R12(); }
|
||||
public void Trigger_X2_R12() { _ = Run_X2_R12(); }
|
||||
public void Trigger_X3_R12() { _ = Run_X3_R12(); }
|
||||
public void Trigger_X1_R43() { _ = Run_X1_R43(); }
|
||||
public void Trigger_X2_R43() { _ = Run_X2_R43(); }
|
||||
public void Trigger_X3_R43() { _ = Run_X3_R43(); }
|
||||
|
||||
private bool IsPulseCoil(ushort addr) => addr switch
|
||||
{
|
||||
(ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X1 => true,
|
||||
(ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X2 => true,
|
||||
(ushort)AsrsCoilAddress.PICK_EMPTY_BOX_X3 => true,
|
||||
(ushort)AsrsCoilAddress.RETURN_TRAY_X1 => true,
|
||||
(ushort)AsrsCoilAddress.RETURN_TRAY_X2 => true,
|
||||
(ushort)AsrsCoilAddress.RETURN_TRAY_X3 => true,
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
38
Lab505.Sim/OpcUaHostedService.cs
Normal file
38
Lab505.Sim/OpcUaHostedService.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class OpcUaHostedService : IHostedService
|
||||
{
|
||||
private readonly OpcUaSimulationServer _server;
|
||||
private readonly ILogger<OpcUaHostedService> _logger;
|
||||
|
||||
public OpcUaHostedService(
|
||||
OpcUaSimulationServer server,
|
||||
ILogger<OpcUaHostedService> logger)
|
||||
{
|
||||
_server = server;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Starting OPC UA Simulation Server on port 4840");
|
||||
try
|
||||
{
|
||||
await _server.StartAsync();
|
||||
_logger.LogInformation("OPC UA Simulation Server started on port 4840");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning("OPC UA Simulation Server failed to start (port 4840 may already be in use): {Message}", ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Stopping OPC UA Simulation Server");
|
||||
await _server.StopAsync();
|
||||
}
|
||||
}
|
||||
104
Lab505.Sim/OpcUaSimulationServer.cs
Normal file
104
Lab505.Sim/OpcUaSimulationServer.cs
Normal file
@@ -0,0 +1,104 @@
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Configuration;
|
||||
using Opc.Ua.Server;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
public class OpcUaSimulationServer : IDisposable
|
||||
{
|
||||
private ApplicationInstance? _app;
|
||||
private bool _isRunning;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get { lock (_lock) return _isRunning; }
|
||||
}
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
Console.WriteLine("[OpcUaSim:4840] Already running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#pragma warning disable CS0618
|
||||
_app = new ApplicationInstance
|
||||
{
|
||||
ApplicationName = "Lab505OpcUaSim",
|
||||
ApplicationType = ApplicationType.Server,
|
||||
ConfigSectionName = "OpcUaClient"
|
||||
};
|
||||
#pragma warning restore CS0618
|
||||
|
||||
// Load XML
|
||||
await _app.LoadApplicationConfigurationAsync("Quickstarts.ReferenceServer.Config.xml", false);
|
||||
|
||||
// Không cần certificate khi security = None
|
||||
await _app.CheckApplicationInstanceCertificatesAsync(silent: true);
|
||||
|
||||
// Start server custom
|
||||
await _app.StartAsync(new SimulationServer());
|
||||
|
||||
lock (_lock) _isRunning = true;
|
||||
Console.WriteLine("[OpcUaSim:4840] Server started");
|
||||
}
|
||||
|
||||
public async Task StopAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
Console.WriteLine("[OpcUaSim:4840] Not running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_app != null)
|
||||
{
|
||||
await _app.StopAsync();
|
||||
|
||||
// Give the server time to fully release the port
|
||||
await Task.Delay(500);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[OpcUaSim:4840] Error stopping: {ex.Message}");
|
||||
}
|
||||
|
||||
_app = null;
|
||||
lock (_lock) _isRunning = false;
|
||||
Console.WriteLine("[OpcUaSim:4840] Server stopped");
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
StopAsync().GetAwaiter().GetResult();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
public class SimulationServer : StandardServer
|
||||
{
|
||||
protected override MasterNodeManager CreateMasterNodeManager(
|
||||
IServerInternal server,
|
||||
ApplicationConfiguration config)
|
||||
{
|
||||
return new MasterNodeManager(
|
||||
server,
|
||||
config,
|
||||
null,
|
||||
[
|
||||
new RcsNodeManager(server, config)
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
34
Lab505.Sim/Program.cs
Normal file
34
Lab505.Sim/Program.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
Console.WriteLine("=== Lab505 WAS Simulators ===");
|
||||
Console.WriteLine("Starting VDA5050 API Simulator...\n");
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
// Add logging
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddConsole();
|
||||
builder.Logging.SetMinimumLevel(LogLevel.Information);
|
||||
|
||||
// Register simulator
|
||||
|
||||
var host = builder.Build();
|
||||
|
||||
// Wait for cancellation
|
||||
var cts = new CancellationTokenSource();
|
||||
Console.CancelKeyPress += (s, e) =>
|
||||
{
|
||||
e.Cancel = true;
|
||||
cts.Cancel();
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, cts.Token);
|
||||
}
|
||||
catch (TaskCanceledException)
|
||||
{
|
||||
Console.WriteLine("\nShutting down...");
|
||||
}
|
||||
1005
Lab505.Sim/RcsNodeManager.cs
Normal file
1005
Lab505.Sim/RcsNodeManager.cs
Normal file
File diff suppressed because it is too large
Load Diff
157
Lab505.Sim/SimulationManager.cs
Normal file
157
Lab505.Sim/SimulationManager.cs
Normal file
@@ -0,0 +1,157 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Quản lý tất cả simulation services - có thể start/stop tại runtime
|
||||
/// </summary>
|
||||
public interface ISimulationManager
|
||||
{
|
||||
bool IsRunning { get; }
|
||||
Task StartAllAsync();
|
||||
Task StopAllAsync();
|
||||
}
|
||||
|
||||
public class SimulationManager : ISimulationManager
|
||||
{
|
||||
private readonly ILogger<SimulationManager> _logger;
|
||||
private readonly VdaSimulationHostedService? _vdaServer;
|
||||
private readonly OpcUaSimulationServer? _opcUaServer;
|
||||
private readonly ModbusSimulationServer_ASRS? _asrsServer;
|
||||
private readonly ConveyorModbusServer? _conveyorServer;
|
||||
|
||||
private bool _isRunning;
|
||||
private readonly object _lock = new();
|
||||
|
||||
public bool IsRunning
|
||||
{
|
||||
get { lock (_lock) return _isRunning; }
|
||||
}
|
||||
|
||||
public SimulationManager(
|
||||
ILogger<SimulationManager> logger,
|
||||
VdaSimulationHostedService? vdaServer = null,
|
||||
OpcUaSimulationServer? opcUaServer = null,
|
||||
ModbusSimulationServer_ASRS? asrsServer = null,
|
||||
ConveyorModbusServer? conveyorServer = null)
|
||||
{
|
||||
_logger = logger;
|
||||
_vdaServer = vdaServer;
|
||||
_opcUaServer = opcUaServer;
|
||||
_asrsServer = asrsServer;
|
||||
_conveyorServer = conveyorServer;
|
||||
}
|
||||
|
||||
public async Task StartAllAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
_logger.LogWarning("Simulation services already running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Starting all simulation services...");
|
||||
|
||||
try
|
||||
{
|
||||
// Start Modbus servers
|
||||
if (_asrsServer != null)
|
||||
{
|
||||
_asrsServer.Start();
|
||||
_logger.LogInformation("✅ ASRS Modbus Simulation Server started");
|
||||
}
|
||||
|
||||
if (_conveyorServer != null)
|
||||
{
|
||||
_conveyorServer.Start();
|
||||
_logger.LogInformation("✅ Conveyor Modbus Simulation Server started");
|
||||
}
|
||||
|
||||
// Start OPC UA server
|
||||
if (_opcUaServer != null)
|
||||
{
|
||||
await _opcUaServer.StartAsync();
|
||||
_logger.LogInformation("✅ OPC UA Simulation Server started");
|
||||
}
|
||||
|
||||
// Start VDA server
|
||||
if (_vdaServer != null)
|
||||
{
|
||||
_vdaServer.Start();
|
||||
_logger.LogInformation("✅ VDA Mock Server started");
|
||||
}
|
||||
|
||||
lock (_lock) _isRunning = true;
|
||||
_logger.LogInformation("All simulation services started successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to start simulation services");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task StopAllAsync()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
_logger.LogWarning("Simulation services not running");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Stopping all simulation services...");
|
||||
|
||||
try
|
||||
{
|
||||
// Stop VDA server
|
||||
if (_vdaServer != null)
|
||||
{
|
||||
_vdaServer.Stop();
|
||||
_logger.LogInformation("✅ VDA Mock Server stopped");
|
||||
}
|
||||
|
||||
// Stop OPC UA server
|
||||
if (_opcUaServer != null)
|
||||
{
|
||||
await _opcUaServer.StopAsync();
|
||||
_logger.LogInformation("✅ OPC UA Simulation Server stopped");
|
||||
}
|
||||
|
||||
// Stop Modbus servers
|
||||
if (_conveyorServer != null)
|
||||
{
|
||||
_conveyorServer.Stop();
|
||||
_logger.LogInformation("✅ Conveyor Modbus Simulation Server stopped");
|
||||
}
|
||||
|
||||
if (_asrsServer != null)
|
||||
{
|
||||
_asrsServer.Stop();
|
||||
_logger.LogInformation("✅ ASRS Modbus Simulation Server stopped");
|
||||
}
|
||||
|
||||
lock (_lock) _isRunning = false;
|
||||
_logger.LogInformation("All simulation services stopped successfully");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error stopping simulation services");
|
||||
lock (_lock) _isRunning = false;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stub dùng khi tắt toàn bộ simulation servers.</summary>
|
||||
public class NullSimulationManager : ISimulationManager
|
||||
{
|
||||
public bool IsRunning => false;
|
||||
public Task StartAllAsync() => Task.CompletedTask;
|
||||
public Task StopAllAsync() => Task.CompletedTask;
|
||||
}
|
||||
632
Lab505.Sim/VdaSimulationHostedService.cs
Normal file
632
Lab505.Sim/VdaSimulationHostedService.cs
Normal file
@@ -0,0 +1,632 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using static Lab505.Shared.RobotPositions;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Mock HTTP Server mô phỏng VDA5050 API
|
||||
/// </summary>
|
||||
public class VdaSimulationHostedService : IHostedService, IDisposable
|
||||
{
|
||||
private HttpListener? _listener;
|
||||
private readonly ILogger<VdaSimulationHostedService> _logger;
|
||||
private readonly Dictionary<string, RobotState> _robots;
|
||||
private readonly JsonSerializerOptions _jsonOptions;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _serverTask;
|
||||
private readonly int _port;
|
||||
private bool _isRunning;
|
||||
|
||||
public bool IsRunning => _isRunning;
|
||||
|
||||
public VdaSimulationHostedService(ILogger<VdaSimulationHostedService> logger, int port = 7333)
|
||||
{
|
||||
_logger = logger;
|
||||
_port = port;
|
||||
|
||||
_jsonOptions = new JsonSerializerOptions
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
// Initialize mock robots with their default positions
|
||||
_robots = new Dictionary<string, RobotState>
|
||||
{
|
||||
["AMR2WS"] = new RobotState
|
||||
{
|
||||
RobotId = "AMR2WS",
|
||||
X = AMR_CAP2_X,
|
||||
Y = AMR_CAP2_Y,
|
||||
Theta = 0,
|
||||
IsOnline = true,
|
||||
NewBaseRequest = true
|
||||
},
|
||||
["IMR"] = new RobotState
|
||||
{
|
||||
RobotId = "IMR",
|
||||
X = IMR_C1_X,
|
||||
Y = IMR_C1_Y,
|
||||
Theta = 0,
|
||||
IsOnline = true,
|
||||
NewBaseRequest = true
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken) { Start(); return Task.CompletedTask; }
|
||||
public Task StopAsync(CancellationToken cancellationToken) { Stop(); return Task.CompletedTask; }
|
||||
|
||||
public void Start()
|
||||
{
|
||||
if (_isRunning)
|
||||
{
|
||||
_logger.LogWarning("VDA Mock Server already running");
|
||||
return;
|
||||
}
|
||||
|
||||
_listener = new HttpListener();
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{_port}/");
|
||||
_listener.Start();
|
||||
_cts = new CancellationTokenSource();
|
||||
_serverTask = Task.Run(() => HandleRequestsAsync(_cts.Token));
|
||||
_isRunning = true;
|
||||
_logger.LogInformation("VDA Mock Server started on {Prefixes}",
|
||||
string.Join(", ", _listener.Prefixes));
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
if (!_isRunning)
|
||||
{
|
||||
_logger.LogWarning("VDA Mock Server not running");
|
||||
return;
|
||||
}
|
||||
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
|
||||
_serverTask?.Wait(TimeSpan.FromSeconds(5));
|
||||
_serverTask = null;
|
||||
|
||||
try
|
||||
{
|
||||
_listener?.Stop();
|
||||
_listener?.Close();
|
||||
}
|
||||
catch { }
|
||||
_listener = null;
|
||||
|
||||
_isRunning = false;
|
||||
_logger.LogInformation("VDA Mock Server stopped");
|
||||
}
|
||||
|
||||
private async Task HandleRequestsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (!cancellationToken.IsCancellationRequested && _listener != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var context = await _listener.GetContextAsync();
|
||||
_ = Task.Run(() => ProcessRequestAsync(context), cancellationToken);
|
||||
}
|
||||
catch (HttpListenerException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (!cancellationToken.IsCancellationRequested)
|
||||
_logger.LogError(ex, "Error accepting request");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ProcessRequestAsync(HttpListenerContext context)
|
||||
{
|
||||
var request = context.Request;
|
||||
var response = context.Response;
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("{Method} {Url}", request.HttpMethod, request.Url?.PathAndQuery);
|
||||
|
||||
var path = request.Url?.AbsolutePath ?? "";
|
||||
var method = request.HttpMethod;
|
||||
|
||||
object? result = null;
|
||||
|
||||
// Route handling
|
||||
if (method == "GET" && path.StartsWith("/api/robotmanager/State/"))
|
||||
{
|
||||
var robotId = path.Split('/').Last();
|
||||
result = HandleGetState(robotId);
|
||||
}
|
||||
else if (method == "POST" && path == "/api/AWC200/MoveTo")
|
||||
{
|
||||
var body = await ReadRequestBodyAsync(request);
|
||||
result = await HandleMoveToAsync(body);
|
||||
}
|
||||
else if (method == "POST" && path == "/api/robotmanager/instantactions")
|
||||
{
|
||||
var body = await ReadRequestBodyAsync(request);
|
||||
result = await HandleInstantActionAsync(body);
|
||||
}
|
||||
else if (method == "DELETE" && path.StartsWith("/api/AWC200/MoveTo/"))
|
||||
{
|
||||
var robotId = path.Split('/').Last();
|
||||
result = HandleCancel(robotId);
|
||||
}
|
||||
else
|
||||
{
|
||||
response.StatusCode = 404;
|
||||
result = new { error = "Endpoint not found" };
|
||||
}
|
||||
|
||||
// Send response
|
||||
if (result != null)
|
||||
{
|
||||
response.ContentType = "application/json";
|
||||
response.StatusCode = response.StatusCode == 0 ? 200 : response.StatusCode;
|
||||
|
||||
var json = JsonSerializer.Serialize(result, _jsonOptions);
|
||||
var buffer = Encoding.UTF8.GetBytes(json);
|
||||
|
||||
response.ContentLength64 = buffer.Length;
|
||||
await response.OutputStream.WriteAsync(buffer);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error processing request");
|
||||
response.StatusCode = 500;
|
||||
|
||||
var error = new { error = ex.Message };
|
||||
var json = JsonSerializer.Serialize(error, _jsonOptions);
|
||||
var buffer = Encoding.UTF8.GetBytes(json);
|
||||
|
||||
response.ContentLength64 = buffer.Length;
|
||||
await response.OutputStream.WriteAsync(buffer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
response.Close();
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string> ReadRequestBodyAsync(HttpListenerRequest request)
|
||||
{
|
||||
using var reader = new StreamReader(request.InputStream, request.ContentEncoding);
|
||||
return await reader.ReadToEndAsync();
|
||||
}
|
||||
|
||||
#region Handlers
|
||||
|
||||
private object HandleGetState(string robotId)
|
||||
{
|
||||
if (!_robots.TryGetValue(robotId, out var state))
|
||||
{
|
||||
return new ApiResult
|
||||
{
|
||||
IsSuccess = false,
|
||||
Message = $"Robot {robotId} not found"
|
||||
};
|
||||
}
|
||||
|
||||
// Snapshot dưới lock — tránh "Collection was modified" khi task nền Add/Remove
|
||||
// đúng lúc poller đọc state.
|
||||
VdaActionState[] actionStatesSnapshot;
|
||||
lock (state.ActionStates)
|
||||
actionStatesSnapshot = state.ActionStates.ToArray();
|
||||
|
||||
return new RobotStateResult
|
||||
{
|
||||
IsSuccess = true,
|
||||
Message = "OK",
|
||||
Data = new RobotStateData
|
||||
{
|
||||
RobotId = robotId,
|
||||
MapId = Guid.NewGuid(),
|
||||
IsOnline = state.IsOnline,
|
||||
State = "READY",
|
||||
StateMsg = new VdaStateMsg
|
||||
{
|
||||
HeaderId = (uint)DateTime.UtcNow.Ticks,
|
||||
Timestamp = DateTime.UtcNow.ToString("o"),
|
||||
Version = "2.0",
|
||||
Manufacturer = "MockManufacturer",
|
||||
SerialNumber = robotId,
|
||||
OrderId = state.CurrentOrderId,
|
||||
OrderUpdateId = state.OrderUpdateId,
|
||||
LastNodeId = state.LastNodeId,
|
||||
LastNodeSequenceId = 0,
|
||||
Driving = state.IsDriving,
|
||||
Paused = state.Paused,
|
||||
NewBaseRequest = state.NewBaseRequest,
|
||||
DistanceSinceLastNode = 0,
|
||||
OperatingMode = "AUTOMATIC",
|
||||
AgvPosition = new VdaAgvPosition
|
||||
{
|
||||
X = state.X,
|
||||
Y = state.Y,
|
||||
Theta = state.Theta,
|
||||
MapId = "map001",
|
||||
PositionInitialized = true
|
||||
},
|
||||
ActionStates = actionStatesSnapshot,
|
||||
Errors = []
|
||||
},
|
||||
VisualizationMsg = new VdaVisualizationMsg
|
||||
{
|
||||
HeaderId = (uint)DateTime.UtcNow.Ticks,
|
||||
Timestamp = DateTime.UtcNow.ToString("o"),
|
||||
Version = "2.0",
|
||||
Manufacturer = "MockManufacturer",
|
||||
SerialNumber = robotId,
|
||||
AgvPosition = new VdaAgvPosition
|
||||
{
|
||||
X = state.X,
|
||||
Y = state.Y,
|
||||
Theta = state.Theta,
|
||||
MapId = "map001",
|
||||
PositionInitialized = true
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<object> HandleMoveToAsync(string requestBody)
|
||||
{
|
||||
var request = JsonSerializer.Deserialize<MoveToRequest>(requestBody, _jsonOptions);
|
||||
|
||||
if (request == null || string.IsNullOrEmpty(request.RobotId))
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = "Invalid request" };
|
||||
}
|
||||
|
||||
if (!_robots.TryGetValue(request.RobotId, out var state))
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = $"Robot {request.RobotId} not found" };
|
||||
}
|
||||
|
||||
_logger.LogInformation("Mock: Moving {RobotId} to {Target}", request.RobotId, request.RoomName);
|
||||
|
||||
// VDA5050: NewBaseRequest = false when movement starts (robot busy)
|
||||
state.NewBaseRequest = false;
|
||||
state.CurrentOrderId = Guid.NewGuid().ToString();
|
||||
state.OrderUpdateId++;
|
||||
state.LastNodeId = request.RoomName;
|
||||
state.IsDriving = true;
|
||||
|
||||
// Simulate movement (~3s total)
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
// Get target position from robot-specific predefined locations
|
||||
var (targetX, targetY) = GetLocationCoordinates(request.RoomName, request.RobotId);
|
||||
|
||||
// Simulate gradual movement over ~10 seconds
|
||||
var steps = 100;
|
||||
for (int i = 0; i < steps; i++)
|
||||
{
|
||||
await Task.Delay(100); // 100 x 100ms = 10s
|
||||
|
||||
// Pause (startPause): đóng băng vị trí, không tiến bước cho tới khi resume.
|
||||
// Thoát nếu bị cancel (HandleCancel đặt IsDriving=false / Paused=false).
|
||||
while (state.Paused && state.IsDriving)
|
||||
await Task.Delay(100);
|
||||
|
||||
// Cancel: dừng tại chỗ, không snap tới đích (HandleCancel đã set NBR=true).
|
||||
if (!state.IsDriving)
|
||||
return;
|
||||
|
||||
state.X = state.X + (targetX - state.X) / (steps - i);
|
||||
state.Y = state.Y + (targetY - state.Y) / (steps - i);
|
||||
}
|
||||
|
||||
state.X = targetX;
|
||||
state.Y = targetY;
|
||||
state.IsDriving = false;
|
||||
|
||||
// VDA5050: NewBaseRequest = true when movement complete (robot ready)
|
||||
state.NewBaseRequest = true;
|
||||
|
||||
_logger.LogInformation("Mock: {RobotId} arrived at {Target} ({X}, {Y}), NewBaseRequest=true",
|
||||
request.RobotId, request.RoomName, targetX, targetY);
|
||||
});
|
||||
|
||||
return new ApiResult { IsSuccess = true, Message = "MoveTo command accepted" };
|
||||
}
|
||||
|
||||
private async Task<object> HandleInstantActionAsync(string requestBody)
|
||||
{
|
||||
var request = JsonSerializer.Deserialize<InstantActionRequest>(requestBody, _jsonOptions);
|
||||
|
||||
if (request == null || string.IsNullOrEmpty(request.RobotId) || request.Action == null)
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = "Invalid request" };
|
||||
}
|
||||
|
||||
if (!_robots.TryGetValue(request.RobotId, out var state))
|
||||
{
|
||||
return new ApiResult { IsSuccess = false, Message = $"Robot {request.RobotId} not found" };
|
||||
}
|
||||
|
||||
var action = request.Action;
|
||||
_logger.LogInformation("Mock: {RobotId} executing {ActionType}", request.RobotId, action.ActionType);
|
||||
|
||||
// VDA5050: NewBaseRequest stays TRUE during WAITING and INITIALIZING.
|
||||
// Only movement-type actions (UnDockFromStation) set it FALSE during RUNNING.
|
||||
// Station-type actions (Load, UnLoad, DockToStation, PickUp, MutedSafety) keep it TRUE.
|
||||
|
||||
// Movement actions: robot physically moves → blocks new base requests during RUNNING
|
||||
static bool IsMovementAction(string actionType) => actionType is
|
||||
"UnDockFromStation" or "UndockFromStation";
|
||||
|
||||
var actionState = new VdaActionState
|
||||
{
|
||||
ActionID = action.ActionId,
|
||||
ActionType = action.ActionType,
|
||||
ActionDescription = action.ActionDescription,
|
||||
ActionStatus = "WAITING"
|
||||
};
|
||||
|
||||
lock (state.ActionStates)
|
||||
state.ActionStates.Add(actionState);
|
||||
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(200);
|
||||
actionState.ActionStatus = "INITIALIZING";
|
||||
// NewBaseRequest still TRUE here — robot is preparing but not yet blocking
|
||||
|
||||
await Task.Delay(300);
|
||||
actionState.ActionStatus = "RUNNING";
|
||||
|
||||
// Only movement actions set NewBaseRequest = false during RUNNING
|
||||
if (IsMovementAction(action.ActionType))
|
||||
state.NewBaseRequest = false;
|
||||
|
||||
switch (action.ActionType)
|
||||
{
|
||||
case "UnDockFromStation":
|
||||
case "UndockFromStation":
|
||||
// IMR: dùng distance param (lùi theo trục X, Theta=0)
|
||||
// AMR: dùng vị trí undock được định nghĩa sẵn theo trạm đang đậu
|
||||
// (tránh sai hướng do Theta=0 cố định trong sim)
|
||||
if (request.RobotId == "IMR")
|
||||
{
|
||||
var distance = GetActionParameter(action, "distance", -0.5);
|
||||
state.X += distance * Math.Cos(state.Theta);
|
||||
state.Y += distance * Math.Sin(state.Theta);
|
||||
}
|
||||
else // AMR
|
||||
{
|
||||
if (Math.Abs(state.X - AMR_CAP1_X) < POS_TOL && Math.Abs(state.Y - AMR_CAP1_Y) < POS_TOL)
|
||||
{ state.X = AMR_UNDOCK_CAP1_X; state.Y = AMR_UNDOCK_CAP1_Y; }
|
||||
else if (Math.Abs(state.X - AMR_CAP2_X) < POS_TOL && Math.Abs(state.Y - AMR_CAP2_Y) < POS_TOL)
|
||||
{ state.X = AMR_UNDOCK_CAP2_X; state.Y = AMR_UNDOCK_CAP2_Y; }
|
||||
else
|
||||
{
|
||||
// Vị trí không xác định — fallback theta-based
|
||||
var distance = GetActionParameter(action, "distance", -0.5);
|
||||
state.X += distance * Math.Cos(state.Theta);
|
||||
state.Y += distance * Math.Sin(state.Theta);
|
||||
}
|
||||
}
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
|
||||
case "DockToStation":
|
||||
// Robot drives forward by 'distance' meters (reverse of undock)
|
||||
var dockDist = GetActionParameter(action, "distance", 1.2);
|
||||
state.X += dockDist * Math.Cos(state.Theta);
|
||||
state.Y += dockDist * Math.Sin(state.Theta);
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
|
||||
case "startPause":
|
||||
// Robot tạm dừng — đặt cờ Paused, hoàn thành nhanh
|
||||
state.Paused = true;
|
||||
await Task.Delay(200);
|
||||
break;
|
||||
|
||||
case "stopPause":
|
||||
// Robot tiếp tục — bỏ cờ Paused, hoàn thành nhanh
|
||||
state.Paused = false;
|
||||
await Task.Delay(200);
|
||||
break;
|
||||
|
||||
case "initPosition":
|
||||
// Đặt lại pose (x, y, theta) tức thì
|
||||
state.X = GetActionParameter(action, "x", state.X);
|
||||
state.Y = GetActionParameter(action, "y", state.Y);
|
||||
state.Theta = GetActionParameter(action, "theta", state.Theta);
|
||||
await Task.Delay(200);
|
||||
break;
|
||||
|
||||
case "Load":
|
||||
case "UpLoad":
|
||||
case "UnLoad":
|
||||
case "PickUp":
|
||||
case "MutedSafety":
|
||||
case "Muted Safety":
|
||||
case "MuteOn":
|
||||
case "MuteOff":
|
||||
// Station actions — robot stays put, NewBaseRequest stays TRUE
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
|
||||
default:
|
||||
await Task.Delay(9500);
|
||||
break;
|
||||
}
|
||||
|
||||
actionState.ActionStatus = "FINISHED";
|
||||
state.NewBaseRequest = true;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Mock: {RobotId} {ActionType} FINISHED, NewBaseRequest=true",
|
||||
request.RobotId, action.ActionType);
|
||||
|
||||
// Keep FINISHED state long enough for the 300 ms VDA poller to catch it
|
||||
await Task.Delay(5000);
|
||||
lock (state.ActionStates)
|
||||
state.ActionStates.Remove(actionState);
|
||||
});
|
||||
|
||||
return new ApiResult { IsSuccess = true, Message = $"{action.ActionType} command accepted" };
|
||||
}
|
||||
|
||||
private object HandleCancel(string robotId)
|
||||
{
|
||||
if (!_robots.TryGetValue(robotId, out var state))
|
||||
return new ApiResult { IsSuccess = false, Message = $"Robot {robotId} not found" };
|
||||
|
||||
_logger.LogInformation("Mock: Canceling order for {RobotId}", robotId);
|
||||
|
||||
// VDA5050: chuyển tất cả action đang active → ABORTED
|
||||
// DualCommandMonitor đang chờ sẽ nhận được ABORTED trong lần poll tiếp theo (~300ms)
|
||||
lock (state.ActionStates)
|
||||
{
|
||||
foreach (var a in state.ActionStates)
|
||||
{
|
||||
if (a.ActionStatus is "WAITING" or "INITIALIZING" or "RUNNING")
|
||||
a.ActionStatus = "ABORTED";
|
||||
}
|
||||
}
|
||||
|
||||
state.IsDriving = false;
|
||||
state.CurrentOrderId = null;
|
||||
state.NewBaseRequest = true;
|
||||
state.Paused = false; // hủy lệnh thì bỏ luôn trạng thái pause
|
||||
|
||||
// Xóa action ABORTED sau 2s — đủ để VDA poller (300ms) đọc được vài lần
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(2000);
|
||||
lock (state.ActionStates)
|
||||
state.ActionStates.RemoveAll(a => a.ActionStatus == "ABORTED");
|
||||
});
|
||||
|
||||
return new ApiResult { IsSuccess = true, Message = "Order cancelled" };
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Helpers
|
||||
|
||||
/// <summary>
|
||||
/// AMR specific positions — must match FlowService constants
|
||||
/// AMR_CAP1_X=6.0, AMR_CAP1_Y=0.23 | AMR_CAP2_X=-0.7, AMR_CAP2_Y=-3.19
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, (double X, double Y)> AmrLocations = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Cap1"] = (AMR_CAP1_X, AMR_CAP1_Y),
|
||||
["Cap2"] = (AMR_CAP2_X, AMR_CAP2_Y),
|
||||
["Home"] = (0.0, 0.0)
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, (double X, double Y)> ImrLocations = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["Bt1"] = (IMR_C1_X, IMR_C1_Y),
|
||||
["BT1"] = (IMR_C1_X, IMR_C1_Y),
|
||||
["Abb"] = (IMR_ABB_X, IMR_ABB_Y),
|
||||
["ABB"] = (IMR_ABB_X, IMR_ABB_Y),
|
||||
["Home"] = (0.0, 0.0),
|
||||
["HOME"] = (0.0, 0.0)
|
||||
};
|
||||
|
||||
private (double X, double Y) GetLocationCoordinates(string locationName, string? robotId = null)
|
||||
{
|
||||
// Try robot-specific locations first
|
||||
if (!string.IsNullOrEmpty(robotId))
|
||||
{
|
||||
if (robotId.Equals("AMR2WS", StringComparison.OrdinalIgnoreCase) ||
|
||||
robotId.StartsWith("AMR", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (AmrLocations.TryGetValue(locationName, out var amrCoords))
|
||||
return amrCoords;
|
||||
}
|
||||
else if (robotId.Equals("IMR", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
if (ImrLocations.TryGetValue(locationName, out var imrCoords))
|
||||
return imrCoords;
|
||||
}
|
||||
}
|
||||
|
||||
// Try AMR locations (case insensitive)
|
||||
if (AmrLocations.TryGetValue(locationName, out var coords))
|
||||
return coords;
|
||||
|
||||
// Try IMR locations (case insensitive)
|
||||
if (ImrLocations.TryGetValue(locationName, out coords))
|
||||
return coords;
|
||||
|
||||
// Default to (0, 0) for unknown locations
|
||||
_logger.LogWarning("Unknown location '{Location}' for robot '{RobotId}', defaulting to (0,0)", locationName, robotId);
|
||||
return (0, 0);
|
||||
}
|
||||
|
||||
private double GetActionParameter(VdaInstantAction action, string key, double defaultValue)
|
||||
{
|
||||
var param = action.ActionParameters?.FirstOrDefault(p => p.Key == key);
|
||||
// VDA5050 dùng dấu chấm thập phân — parse InvariantCulture để khớp với driver,
|
||||
// không phụ thuộc locale máy chạy sim.
|
||||
if (param != null && double.TryParse(param.Value,
|
||||
NumberStyles.Float, CultureInfo.InvariantCulture, out var value))
|
||||
return value;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Stop();
|
||||
_cts?.Dispose();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
#region Mock Models
|
||||
|
||||
internal class RobotState
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public double X { get; set; }
|
||||
public double Y { get; set; }
|
||||
public double Theta { get; set; }
|
||||
public bool IsOnline { get; set; }
|
||||
public bool NewBaseRequest { get; set; }
|
||||
public bool IsDriving { get; set; }
|
||||
public bool Paused { get; set; }
|
||||
public string? CurrentOrderId { get; set; }
|
||||
public int OrderUpdateId { get; set; }
|
||||
public string? LastNodeId { get; set; }
|
||||
public List<VdaActionState> ActionStates { get; set; } = new();
|
||||
}
|
||||
|
||||
internal class MoveToRequest
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public string RoomName { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
internal class InstantActionRequest
|
||||
{
|
||||
public string RobotId { get; set; } = string.Empty;
|
||||
public VdaInstantAction? Action { get; set; }
|
||||
}
|
||||
|
||||
#endregion
|
||||
53
Lab505.Sim/VdaSimulationServer.cs
Normal file
53
Lab505.Sim/VdaSimulationServer.cs
Normal file
@@ -0,0 +1,53 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Lab505.Sim;
|
||||
|
||||
/// <summary>
|
||||
/// Hosted Service để chạy VDA Mock Server ở background
|
||||
/// </summary>
|
||||
public class VdaSimulationServer : IHostedService
|
||||
{
|
||||
private readonly VdaSimulationHostedService _server;
|
||||
private readonly ILogger<VdaSimulationServer> _logger;
|
||||
|
||||
public VdaSimulationServer(
|
||||
VdaSimulationHostedService server,
|
||||
ILogger<VdaSimulationServer> logger)
|
||||
{
|
||||
_server = server ?? throw new ArgumentNullException(nameof(server));
|
||||
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Starting VDA Simulation Hosted Service");
|
||||
_server.Start();
|
||||
_logger.LogInformation("VDA Simulation Hosted Service started successfully");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to start VDA Simulation Hosted Service");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Stopping VDA Simulation Hosted Service");
|
||||
_server.Stop();
|
||||
_logger.LogInformation("VDA Simulation Hosted Service stopped successfully");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error stopping VDA Simulation Hosted Service");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user