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.WaterCool.Client;
///
/// 水冷连接管理
///
[Scope]
public class WaterCoolClientMgr
{
public static readonly ConcurrentDictionary Dictionary = new();
private static readonly ILog Log = LogManager.GetLogger(typeof(WaterCoolClientMgr));
///
///
///
///
///
public static WaterCoolClient? GetBySn(string sn)
{
Dictionary.TryGetValue(sn, out var o);
return o;
}
///
/// 通过channel获取client
///
///
///
/// 获取不到,client则为空
///
public static bool TryGetClient(IChannel channel, out string sn, out WaterCoolClient? client)
{
string? snt = ChannelUtils.GetAttr(channel, ChargerConst.WaterCoolSn);
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, WaterCoolClient client)
{
Dictionary[sn] = client;
}
public static void InitClient()
{
EquipInfoRepository equipInfoRepository = AppInfo.Container.Resolve();
EquipNetInfoRepository netInfoRepository = AppInfo.Container.Resolve();
BinInfoRepository binInfoRepository = AppInfo.Container.Resolve();
List equipInfos =
equipInfoRepository.QueryListByClause(it => it.TypeCode == (int)EquipmentType.WaterCool);
if (equipInfos.Count > 0)
{
Dictionary set = equipInfos.ToDictionary(it => it.Code, it => it);
List equipNetInfos = netInfoRepository.QueryListByClause(it => set.Keys.Contains(it.Code));
Dictionary 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}");
WaterCoolClient client = AppInfo.Container.Resolve();
client.AutoReconnect = true;
client.Sn = netInfo.Code;
client.LogName = "WaterCool" + netInfo.Code;
client.ConnectedEventHandler += (sender, b) => { client.SessionAttr(netInfo.Code, netInfo.DestAddr); };
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}");
}
}