充电机做客户端

master
wyy 6 days ago
parent f0aa89d43b
commit c63be21955

@ -10,6 +10,7 @@ using Service.Charger.Client;
using Service.Charger.Msg.Charger.Req;
using Service.Charger.Msg.Charger.Resp;
using Service.Charger.Msg.Host.Req;
using Service.Charger.Server;
using Service.Init;
using SqlSugar;
@ -44,7 +45,7 @@ public class ChargerService
return Result<bool>.Fail(@"充电仓未配置充电机编号");
}
ChargerClient? chargerClient = ClientMgr.GetBySn(binInfo.ChargerNo);
ChargerClient? chargerClient = ServerMgr.GetBySn(binInfo.ChargerNo);
if (chargerClient == null || !chargerClient.Connected)
{
return Result<bool>.Fail(@"充电机未连接");
@ -85,7 +86,7 @@ public class ChargerService
return Result<bool>.Fail(@"充电仓未配置充电机编号");
}
ChargerClient? chargerClient = ClientMgr.GetBySn(binInfo.ChargerNo);
ChargerClient? chargerClient = ServerMgr.GetBySn(binInfo.ChargerNo);
if (chargerClient == null || !chargerClient.Connected)
{
return Result<bool>.Fail(@"充电机未连接");
@ -103,7 +104,7 @@ public class ChargerService
/// <returns></returns>
public Result<bool> DistributeElecPriceForCharge(int version)
{
ConcurrentDictionary<string, ChargerClient> chargerClients = ClientMgr.Dictionary;
ConcurrentDictionary<string, ChargerClient> chargerClients = ServerMgr.Dictionary;
if (chargerClients.Values.Count <= 0)
{
return Result<bool>.Fail();
@ -200,7 +201,7 @@ public class ChargerService
public Result<BatteryInfoResp> BatteryInfo(string chargeSn)
{
var chargerClient = ClientMgr.GetBySn(chargeSn);
var chargerClient = ServerMgr.GetBySn(chargeSn);
BatteryInfoResp batteryInfoResp = new();
if (chargerClient != null)
{

@ -1,6 +1,7 @@
using System.Collections.Concurrent;
using System.Reflection;
using Autofac;
using DotNetty.Transport.Channels;
using Entity.DbModel.Station;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Autofac.Attribute;
@ -22,6 +23,7 @@ using Service.Charger.Msg.Charger.Resp;
using Service.Charger.Msg.Host.Req;
using Service.Charger.Msg.Host.Req.Bms;
using Service.Charger.Msg.Host.Req.OutCharger.Req;
using Service.Charger.Server;
using Service.Init;
using SqlSugar;
@ -31,7 +33,7 @@ namespace Service.Charger.Client;
/// 示例程序
/// </summary>
[Scope("InstancePerDependency")]
public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
public class ChargerClient
{
#region 属性
@ -39,6 +41,12 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
/// 充电机编号
/// </summary>
public string Sn { get; set; }
public IChannel Channel { get; set; }
/// <summary>
/// 充电机是否连接
/// </summary>
public bool Connected { get; set; }
public readonly string Gun1 = "1";
public readonly string Gun2 = "2";
@ -433,26 +441,12 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
Auth auth = new Auth(IncreAuthTimes(), authCodes, authCodeKey);
CurrentCmd = JsonConvert.SerializeObject(auth, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(auth.ToBytes());
this.Channel.WriteAndFlushAsync(auth);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(auth);
try
{
Log().Info("Auth after send SetPeakValleyTime");
ConcurrentDictionary<string, ChargerClient> chargerClients = ClientMgr.Dictionary;
if (chargerClients.Values.Count <= 0)
{
return Result<bool>.Fail();
}
foreach (var chargerClientsValue in chargerClients.Values)
{
if (chargerClientsValue.Connected)
{
Thread.Sleep(3000);
chargerClientsValue.SendSetPeakValleyTime(BulidSetPeakValleyTimeObj(StaticStationInfo.Ceid));
}
}
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(BulidSetPeakValleyTimeObj(StaticStationInfo.Ceid));
}
catch (Exception e)
{
@ -486,7 +480,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
var remoteStartCharging = new RemoteStartCharging(socLimit, changePowerCmdType, changePower, chargeOrderNo);
CurrentCmd = JsonConvert.SerializeObject(remoteStartCharging, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(remoteStartCharging.ToBytes());
this.Channel.WriteAndFlushAsync(remoteStartCharging);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(remoteStartCharging);
return Result<string>.Success(chargeOrderNo);
}
@ -505,7 +499,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
RemoteStopCharging remoteStopCharging = new RemoteStopCharging(reason);
CurrentCmd = JsonConvert.SerializeObject(remoteStopCharging, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(remoteStopCharging.ToBytes());
this.Channel.WriteAndFlushAsync(remoteStopCharging);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(remoteStopCharging);
return Result<bool>.Success();
}
@ -521,7 +515,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
}
PowerRegulation powerRegulation = new PowerRegulation(expectedOperatingPower);
this.Channel.WriteAndFlushAsync(powerRegulation);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(powerRegulation);
return Result<bool>.Success();
}
@ -537,7 +531,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
}
AdjustChargeRate adjustChargeRate = new AdjustChargeRate(rate);
this.Channel.WriteAndFlushAsync(adjustChargeRate);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(adjustChargeRate);
return Result<bool>.Success();
}
@ -555,7 +549,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
AuxiliaryPower auxiliaryPower = new AuxiliaryPower(openFlag);
CurrentCmd = JsonConvert.SerializeObject(auxiliaryPower, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(auxiliaryPower.ToBytes());
this.Channel.WriteAndFlushAsync(auxiliaryPower);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(auxiliaryPower);
return Result<bool>.Success();
}
@ -575,7 +569,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
BatteryHolderStatus batteryHolderStatus = new BatteryHolderStatus(battery, connectionState, waterCondition);
CurrentCmd = JsonConvert.SerializeObject(batteryHolderStatus, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(batteryHolderStatus.ToBytes());
this.Channel.WriteAndFlushAsync(batteryHolderStatus);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(batteryHolderStatus);
return Result<bool>.Success();
}
@ -592,7 +586,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
}
AuthenticationVIN authenticationVIN = new AuthenticationVIN(vinresult);
this.Channel.WriteAndFlushAsync(authenticationVIN);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(authenticationVIN);
return Result<bool>.Success();
}
@ -616,7 +610,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
UpgradeRequest upgradeRequest = new UpgradeRequest(executionControl, downloadTimeout, versionNumber, fileName,
fileSize, mD5Verification, url);
this.Channel.WriteAndFlushAsync(upgradeRequest);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(upgradeRequest);
return Result<bool>.Success();
}
@ -641,7 +635,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
CurrentCmd = JsonConvert.SerializeObject(setPeakValleyTime, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(setPeakValleyTime.ToBytes());
this.Channel.WriteAndFlushAsync(setPeakValleyTime);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(setPeakValleyTime);
Log().Info($"SendSetPeakValleyTime{CurrentCmd} to chargeOrderNo={BinNo}");
@ -662,7 +656,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
OfflineStopCharging offlineStopCharging = new OfflineStopCharging(enabled);
CurrentCmd = JsonConvert.SerializeObject(offlineStopCharging, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(offlineStopCharging.ToBytes());
this.Channel.WriteAndFlushAsync(offlineStopCharging);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(offlineStopCharging);
return Result<bool>.Success();
}
@ -678,7 +672,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
}
ChangeChargeMode req = new ChangeChargeMode(chargeMode);
this.Channel.WriteAndFlushAsync(req);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(req);
return Result<bool>.Success();
}
@ -711,7 +705,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
PileStartCharge pileStartCharge =
new PileStartCharge(pn, socValue, changePowerCmdType, changePower, chargeOrderNo);
this.Channel.WriteAndFlushAsync(pileStartCharge);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(pileStartCharge);
return Result<string>.Success(chargeOrderNo);
}
@ -732,7 +726,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
Log().Info(
$"SendStartOutCharger pn={pn}, stopReason={stopReason}");
PileStopCharge pileStopCharge = new PileStopCharge(pn, stopReason);
this.Channel.WriteAndFlushAsync(pileStopCharge);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(pileStopCharge);
return Result<bool>.Success();
}
@ -751,7 +745,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
}
PileAdjustPower powerRegulation = new PileAdjustPower(pn, expectedOperatingPower);
this.Channel.WriteAndFlushAsync(powerRegulation);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(powerRegulation);
return Result<bool>.Success();
}
@ -768,7 +762,7 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
QueryBattery queryBattery = new QueryBattery(ChargerConst.BatteryNo);
CurrentCmd = JsonConvert.SerializeObject(queryBattery, Formatting.Indented) + "\r\n" +
BitUtls.BytesToHexStr(queryBattery.ToBytes());
this.Channel.WriteAndFlushAsync(queryBattery);
ServerMgr.Server.SessionMgr.GetSession(Sn).Send(queryBattery);
return Result<bool>.Success();
}
@ -857,16 +851,6 @@ public class ChargerClient : TcpClient<IBaseHandler, Decoder, Encoder>
#endregion
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool Connect()
{
base.BaseConnect();
Log().Info($"charger {Sn} connect succeed");
return Connected;
}
/// <summary>
///

@ -1,115 +0,0 @@
using System.Collections.Concurrent;
using Autofac;
using Common.Const;
using DotNetty.Transport.Channels;
using Entity.DbModel.Station;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.Session;
using log4net;
using Repository.Station;
using Service.Charger.Common;
namespace Service.Charger.Client;
/// <summary>
/// 示例程序
/// </summary>
[Scope]
public static class ClientMgr
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ClientMgr));
public static readonly ConcurrentDictionary<string, ChargerClient> Dictionary = new();
public static ChargerClient? GetBySn(string sn)
{
Dictionary.TryGetValue(sn, out var o);
return o;
}
/// <summary>
/// 通过channel获取client
/// </summary>
/// <param name="channel"></param>
/// <param name="sn"></param>
/// <param name="client">获取不到client则为空</param>
/// <returns></returns>
public static bool TryGetClient(IChannel channel, out string sn, out ChargerClient? client)
{
string? snt = ChannelUtils.GetAttr(channel, ChargerConst.ChargerSn);
if (!string.IsNullOrWhiteSpace(snt))
{
var chargerClient = GetBySn(snt);
if (chargerClient != null)
{
sn = snt;
client = chargerClient;
return true;
}
}
sn = string.Empty;
client = null;
return false;
}
public static void AddBySn(string sn, ChargerClient client)
{
Dictionary[sn] = client;
}
//TODO 连接、鉴权,开始充电,结束充电,设置尖峰平谷,读取尖峰平谷,发送功率调节指令,发送辅助源控制指令,下发掉线停止充电,
public static void InitClient()
{
EquipInfoRepository equipInfoRepository = AppInfo.Container.Resolve<EquipInfoRepository>();
EquipNetInfoRepository netInfoRepository = AppInfo.Container.Resolve<EquipNetInfoRepository>();
BinInfoRepository binInfoRepository = AppInfo.Container.Resolve<BinInfoRepository>();
List<EquipInfo> equipInfos =
equipInfoRepository.QueryListByClause(it => it.TypeCode == (int)EquipmentType.Charger);
if (equipInfos.Count > 0)
{
Dictionary<string, EquipInfo> set = equipInfos.ToDictionary(it => it.Code, it => it);
List<EquipNetInfo> equipNetInfos = netInfoRepository.QueryListByClause(it => set.Keys.Contains(it.Code));
Dictionary<string, BinInfo> binInfoMap = binInfoRepository
.QueryListByClause(it => set.Keys.Contains(it.ChargerNo))
.ToDictionary(it => it.ChargerNo, it => it);
foreach (EquipNetInfo netInfo in equipNetInfos)
{
Task.Run(() =>
{
binInfoMap.TryGetValue(netInfo.Code, out var binInfo);
ConnClient(netInfo, binInfo);
});
}
}
}
private static void ConnClient(EquipNetInfo netInfo, BinInfo? binInfo)
{
Log.Info($"begin to connect {netInfo.Code} {netInfo.NetAddr}:{netInfo.NetPort}");
ChargerClient client = AppInfo.Container.Resolve<ChargerClient>();
client.AutoReconnect = true;
client.Sn = netInfo.Code;
client.BinNo = binInfo?.No;
client.BatteryNo = binInfo?.BatteryNo;
client.LogName = "Charger" + netInfo.Code;
client.ConnectedEventHandler += (sender, b) =>
{
client.SessionAttr(netInfo.Code, netInfo.DestAddr);
client.SendAuth();
};
client.InitBootstrap(netInfo.NetAddr, int.Parse(netInfo.NetPort));
Task.Run(() =>
{
client.Connect();
client.SessionAttr(netInfo.Code, netInfo.DestAddr);
Log.Info($"succeed to connect {netInfo.Code} {netInfo.NetAddr}:{netInfo.NetPort}");
});
AddBySn(netInfo.Code, client);
Log.Info($"begin to connect {netInfo.Code} {netInfo.NetAddr}:{netInfo.NetPort}");
}
}

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Service.Charger.Server;
namespace Service.Charger.Handler
{
@ -19,7 +20,7 @@ namespace Service.Charger.Handler
protected override void ChannelRead0(IChannelHandlerContext ctx, BasicParameter msg)
{
if (ClientMgr.TryGetClient(ctx.Channel, out string sn, out var client))
if (ServerMgr.TryGetClient(ctx.Channel, out string sn, out var client))
{
Log.Info($"receive {msg} from {sn}");
client.BasicParameter = msg;

@ -3,6 +3,7 @@ using log4net;
using Repository.Station;
using Service.Charger.Client;
using Service.Charger.Msg.Charger.Resp;
using Service.Charger.Server;
namespace Service.Charger.Handler;
@ -15,7 +16,7 @@ public class BatteryBaseInfoHandler : SimpleChannelInboundHandler<BatteryBaseInf
public BinInfoRepository BinInfoRepository { get; set; }
protected override void ChannelRead0(IChannelHandlerContext ctx, BatteryBaseInfo msg)
{
if (ClientMgr.TryGetClient(ctx.Channel, out string sn, out var client))
if (ServerMgr.TryGetClient(ctx.Channel, out string sn, out var client))
{
Log.Info($"receive {msg} from {sn}");
client.BatteryBaseInfo = msg;

@ -0,0 +1,26 @@
using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkDriver.TcpServer;
using Service.Charger.Codec;
using Service.Charger.Handler;
using Service.Charger.Msg;
using Service.Charger.Msg.Host.Req;
namespace Service.Charger.Server;
[Scope]
public class ChargerServer : TcpServer<IBaseHandler, Decoder, Encoder>
{
#region send
/// <summary>
/// 发送
/// </summary>
/// <param name="sn">充电机编号</param>
/// <param name="msg">消息</param>
public void SendShapParametersReq(string sn, APCI msg)
{
SessionMgr.GetSession(sn).Send(msg);
}
#endregion
}

@ -0,0 +1,72 @@
using System.Collections.Concurrent;
using Autofac;
using DotNetty.Transport.Channels;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkDriver.Session;
using Service.Charger.Client;
using Service.Charger.Common;
namespace Service.Charger.Server;
public class ServerMgr
{
public static readonly ConcurrentDictionary<string, ChargerClient> Dictionary = new();
public static ChargerServer? Server;
public static void InitServer(int port)
{
Server = AppInfo.Container.Resolve<ChargerServer>();
Server.Start(port);
}
/// <summary>
/// 通过channel获取server
/// </summary>
/// <param name="channel"></param>
/// <param name="sn"></param>
/// <param name="server">获取不到client则为空</param>
/// <returns></returns>
public static bool TryGetClient(IChannel channel, out string sn, out ChargerClient? server)
{
string? snt = ChannelUtils.GetAttr(channel, ChargerConst.ChargerSn);
if (!string.IsNullOrWhiteSpace(snt))
{
var chargerServer = GetBySn(snt);
if (chargerServer != null)
{
sn = snt;
server = chargerServer;
return true;
}
}
sn = string.Empty;
server = null;
return false;
}
public static void AddBySn(string sn, ChargerClient server)
{
if (Dictionary.ContainsKey(sn))
{
Dictionary[sn] = server;
}
else
{
Dictionary.TryAdd(sn, server);
}
}
public static ChargerClient? GetBySn(string sn)
{
//return Dictionary[sn];
Dictionary.TryGetValue(sn, out var o);
return o;
}
}

@ -5,6 +5,7 @@ using HybirdFrameworkCore.Autofac.Attribute;
using HybirdFrameworkCore.Entity;
using Repository.Station;
using Service.Charger.Client;
using Service.Charger.Server;
namespace Service.Station;
@ -35,7 +36,7 @@ public class BinInfoService : BaseServices<BinInfo>
// 功率赋值
foreach (var binInfoResp in binInfoList)
{
ChargerClient? chargerClient = ClientMgr.GetBySn(binInfoResp.ChargerNo);
ChargerClient? chargerClient = ServerMgr.GetBySn(binInfoResp.ChargerNo);
if (chargerClient != null)
{
binInfoResp.power = chargerClient.RealTimeChargePower;

Loading…
Cancel
Save