feat: 实现拨动开关的数字孪生
This commit is contained in:
65
server/src/Peripherals/SwitchClient.cs
Normal file
65
server/src/Peripherals/SwitchClient.cs
Normal file
@@ -0,0 +1,65 @@
|
||||
using System.Collections;
|
||||
using System.Net;
|
||||
using DotNext;
|
||||
|
||||
namespace Peripherals.SwitchClient;
|
||||
|
||||
class SwitchCtrlAddr
|
||||
{
|
||||
public const UInt32 BASE = 0xB0_00_00_20;
|
||||
|
||||
public const UInt32 ENABLE = BASE;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 矩阵键盘外设类,用于控制和管理矩阵键盘的功能。
|
||||
/// </summary>
|
||||
public class SwitchCtrl
|
||||
{
|
||||
private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
readonly int timeout = 500;
|
||||
readonly int taskID;
|
||||
readonly int port;
|
||||
readonly string address;
|
||||
private IPEndPoint ep;
|
||||
|
||||
public SwitchCtrl(string address, int port, int taskID, int timeout = 500)
|
||||
{
|
||||
if (timeout < 0)
|
||||
throw new ArgumentException("Timeout couldn't be negative", nameof(timeout));
|
||||
this.address = address;
|
||||
this.port = port;
|
||||
this.ep = new IPEndPoint(IPAddress.Parse(address), port);
|
||||
this.taskID = taskID;
|
||||
this.timeout = timeout;
|
||||
}
|
||||
|
||||
public async ValueTask<Result<bool>> SetEnable(bool enable)
|
||||
{
|
||||
if (MsgBus.IsRunning)
|
||||
MsgBus.UDPServer.ClearUDPData(this.address, this.taskID);
|
||||
else return new(new Exception("Message Bus not work!"));
|
||||
|
||||
var ret = await UDPClientPool.WriteAddr(
|
||||
this.ep, this.taskID, SwitchCtrlAddr.ENABLE, enable ? 0x1U : 0x0U, this.timeout);
|
||||
if (!ret.IsSuccessful) return new(ret.Error);
|
||||
return ret.Value;
|
||||
}
|
||||
|
||||
public async ValueTask<Result<bool>> SetSwitchOnOff(int num, bool onOff)
|
||||
{
|
||||
if (MsgBus.IsRunning)
|
||||
MsgBus.UDPServer.ClearUDPData(this.address, this.taskID);
|
||||
else return new(new Exception("Message Bus not work!"));
|
||||
|
||||
var ret = await UDPClientPool.WriteAddr(
|
||||
this.ep, this.taskID, SwitchCtrlAddr.BASE + (UInt32)num, onOff ? 0x1U : 0x0U, this.timeout);
|
||||
if (!ret.IsSuccessful)
|
||||
{
|
||||
logger.Error($"Set Switch {onOff} failed: {ret.Error}");
|
||||
return new(ret.Error);
|
||||
}
|
||||
return ret.Value;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user