LoadingBalanceService.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. using Dapper;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.Configuration;
  6. using System.Data;
  7. using System.Data.SqlClient;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace EVCB_OCPP.WSServer.Service
  12. {
  13. public class LoadBalanceSetting
  14. {
  15. public int StationId { set; get; }
  16. public int LBMode { set; get; }
  17. public int LBCurrent { set; get; }
  18. }
  19. public class LoadingBalanceService
  20. {
  21. string mainConnectionString = ConfigurationManager.ConnectionStrings["MainDBContext"].ConnectionString;
  22. string webConnectionString = ConfigurationManager.ConnectionStrings["WebDBContext"].ConnectionString;
  23. ConcurrentDictionary<int, object> _lockDic = new ConcurrentDictionary<int, object>();
  24. public LoadingBalanceService()
  25. {
  26. }
  27. public int GetStationIdByMachineId(string machineId)
  28. {
  29. int stationId = 0;
  30. using (SqlConnection conn = new SqlConnection(webConnectionString))
  31. {
  32. var parameters = new DynamicParameters();
  33. parameters.Add("@MachineId", machineId, DbType.String, ParameterDirection.Input);
  34. string strSql = "Select StationId from [dbo].[StationMachine] where MachineId=@MachineId ; ";
  35. stationId = conn.ExecuteScalar<Int32>(strSql, parameters);
  36. }
  37. return stationId;
  38. }
  39. public bool IsNeedtoCancelSetting(int stationId, string machineId, string chargeBoxId)
  40. {
  41. var setting = GetLoadBalance(stationId);
  42. if (setting == null) return false;
  43. lock (GetLock(stationId))
  44. {
  45. if (setting.LBMode > 0 && setting.LBMode < 3 && !IsStillInTransactions(chargeBoxId))
  46. {
  47. // renew table
  48. UpdateLoadbalanceRecord(stationId, machineId, 0, DateTime.UtcNow);
  49. return true;
  50. }
  51. if (setting.LBMode >= 3 || setting.LBMode < 1)
  52. {
  53. CloseLoadbalanceRecord(stationId);
  54. }
  55. }
  56. return false;
  57. }
  58. private object GetLock(int stationId)
  59. {
  60. if (!_lockDic.ContainsKey(stationId))
  61. {
  62. _lockDic.TryAdd(stationId, new object());
  63. }
  64. return _lockDic[stationId];
  65. }
  66. private void CloseLoadbalanceRecord(int stationId)
  67. {
  68. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  69. {
  70. var parameters = new DynamicParameters();
  71. parameters.Add("@StationId", stationId, DbType.Int32, ParameterDirection.Input);
  72. parameters.Add("@FinishedOn", DateTime.UtcNow, DbType.DateTime, ParameterDirection.Input);
  73. string strSql = "Update [dbo].[LoadingBalance] SET FinishedOn=@FinishedOn where StationId=@StationId and FinishedOn='1991/01/01'; ";
  74. conn.Execute(strSql, parameters);
  75. }
  76. }
  77. private void UpdateLoadbalanceRecord(int stationId, string machineId, decimal power, DateTime? finishedOn, bool keepgoing = false)
  78. {
  79. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  80. {
  81. if (finishedOn.HasValue)
  82. {
  83. var parameters = new DynamicParameters();
  84. parameters.Add("@MachineId", machineId, DbType.String, ParameterDirection.Input);
  85. parameters.Add("@FinishedOn", finishedOn.Value, DbType.DateTime, ParameterDirection.Input);
  86. string strSql = "Update [dbo].[LoadingBalance] SET FinishedOn=@FinishedOn where MachineId=@MachineId and FinishedOn='1991/01/01'; ";
  87. conn.Execute(strSql, parameters);
  88. }
  89. else
  90. {
  91. if (keepgoing)
  92. {
  93. var parameters = new DynamicParameters();
  94. parameters.Add("@MachineId", machineId, DbType.String, ParameterDirection.Input);
  95. parameters.Add("@Power", power, DbType.Decimal, ParameterDirection.Input);
  96. string strSql = "Update [dbo].[LoadingBalance] SET Power=@Power where MachineId=@MachineId and FinishedOn='1991/01/01'; ";
  97. conn.Execute(strSql, parameters);
  98. }
  99. else
  100. {
  101. var parameters = new DynamicParameters();
  102. parameters.Add("@StationId", stationId, DbType.Int32, ParameterDirection.Input);
  103. parameters.Add("@MachineId", machineId, DbType.String, ParameterDirection.Input);
  104. parameters.Add("@Power", power, DbType.Decimal, ParameterDirection.Input);
  105. parameters.Add("@CreatedOn", DateTime.UtcNow, DbType.DateTime, ParameterDirection.Input);
  106. parameters.Add("@FinishedOn", new DateTime(1991, 1, 1, 0, 0, 0, DateTimeKind.Utc), DbType.DateTime, ParameterDirection.Input);
  107. string strSql = "INSERT INTO [dbo].[LoadingBalance] " +
  108. "([StationId],[MachineId],[Power],[CreatedOn],[FinishedOn]) " +
  109. "VALUES(@StationId,@MachineId,@Power,@CreatedOn,@FinishedOn);";
  110. conn.Execute(strSql, parameters);
  111. }
  112. }
  113. }
  114. }
  115. private bool IsStillInTransactions(string chargeBoxId)
  116. {
  117. bool result = false;
  118. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  119. {
  120. var parameters = new DynamicParameters();
  121. parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input);
  122. string strSql = "Select count(*) from [dbo].[TransactionRecord] where ChargeBoxId=@ChargeBoxId and StopTime='1991/01/01'; ";
  123. result = conn.ExecuteScalar<bool>(strSql, parameters);
  124. }
  125. return result;
  126. }
  127. private decimal? GetCurrentSetting(string machineId)
  128. {
  129. decimal? result = (decimal?)null;
  130. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  131. {
  132. var parameters = new DynamicParameters();
  133. parameters.Add("@MachineId", machineId, DbType.String, ParameterDirection.Input);
  134. string strSql = "Select Power from [dbo].[LoadingBalance] where MachineId=@MachineId and FinishedOn='1991/01/01'; ";
  135. result = conn.ExecuteScalar<decimal>(strSql, parameters);
  136. }
  137. return result;
  138. }
  139. public Dictionary<string, decimal?> GetRerangeSettingPower(int stationId)
  140. {
  141. Dictionary<string, decimal?> dic = new Dictionary<string, decimal?>();
  142. var setting = GetLoadBalance(stationId);
  143. if (setting == null) return null;
  144. lock (GetLock(stationId))
  145. {
  146. if (setting != null && setting.LBMode == 2)
  147. {
  148. string machineId = string.Empty;
  149. decimal ratedPower = GetRatedPower(machineId);
  150. //找站內最早要充電的交易 下發充電Power & 填寫新給的Power
  151. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  152. {
  153. var parameters = new DynamicParameters();
  154. parameters.Add("@StationId", stationId, DbType.Int32, ParameterDirection.Input);
  155. string strSql = "Select M.Id from [dbo].[LoadingBalance] LB, [dbo].[Machine] M where LB.StationId=@StationId and LB.MachineId=M.Id and LB.Power < M.RatedPower and LB.FinishedOn='1991/01/01' order by LB.Id asc; ";
  156. machineId = conn.ExecuteScalar<string>(strSql, parameters);
  157. }
  158. if (!string.IsNullOrEmpty(machineId))
  159. {
  160. decimal estimatedPwerValue = GetFCFSPower(stationId, machineId, setting.LBCurrent);
  161. // renew table
  162. UpdateLoadbalanceRecord(stationId, machineId, estimatedPwerValue, null, true);
  163. // UpdateLoadbalanceRecord(stationId, machineId, estimatedPwerValue, null);
  164. dic.Add(machineId, estimatedPwerValue);
  165. }
  166. }
  167. if (setting != null && setting.LBMode == 1)
  168. {
  169. dic = GetAveragePower(stationId, setting.LBCurrent);
  170. foreach (var kv in dic)
  171. {
  172. if (kv.Value.HasValue)
  173. {
  174. UpdateLoadbalanceRecord(stationId, kv.Key, 0, DateTime.UtcNow);
  175. UpdateLoadbalanceRecord(stationId, kv.Key, kv.Value.Value, null);
  176. }
  177. }
  178. }
  179. }
  180. return dic;
  181. }
  182. public Dictionary<string, decimal?> GetSettingPower(int stationId, string machineId)
  183. {
  184. Dictionary<string, decimal?> dic = new Dictionary<string, decimal?>();
  185. var setting = GetLoadBalance(stationId);
  186. if (setting == null) return null;
  187. lock (GetLock(stationId))
  188. {
  189. if (setting != null)
  190. {
  191. if (setting.LBMode == 1)
  192. {
  193. dic = GetAveragePower(stationId, setting.LBCurrent, machineId);
  194. foreach (var kv in dic)
  195. {
  196. if (kv.Value.HasValue)
  197. {
  198. UpdateLoadbalanceRecord(stationId, kv.Key, 0, DateTime.UtcNow);
  199. UpdateLoadbalanceRecord(stationId, kv.Key, kv.Value.Value, null);
  200. }
  201. }
  202. }
  203. else if (setting.LBMode == 2)
  204. {
  205. dic.Add(machineId, GetFCFSPower(stationId, machineId, setting.LBCurrent));
  206. UpdateLoadbalanceRecord(stationId, machineId, 0, DateTime.UtcNow);
  207. UpdateLoadbalanceRecord(stationId, machineId, dic[machineId].Value, null);
  208. }
  209. else
  210. {
  211. // 把LB TABLE 關閉
  212. CloseLoadbalanceRecord(stationId);
  213. }
  214. }
  215. }
  216. return dic;
  217. }
  218. public LoadBalanceSetting GetLoadBalance(int stationId)
  219. {
  220. LoadBalanceSetting setting = null;
  221. using (SqlConnection conn = new SqlConnection(webConnectionString))
  222. {
  223. var parameters = new DynamicParameters();
  224. parameters.Add("@StationId", stationId, DbType.Int32, ParameterDirection.Input);
  225. string strSql = "Select LBMode,LBCurrent from [dbo].[Station] where Id=@StationId ; ";
  226. setting = conn.Query<LoadBalanceSetting>(strSql, parameters).FirstOrDefault();
  227. }
  228. return setting;
  229. }
  230. private List<string> GetIdsbyStationId(int stationId)
  231. {
  232. List<string> machineIds = new List<string>();
  233. using (SqlConnection conn = new SqlConnection(webConnectionString))
  234. {
  235. var parameters = new DynamicParameters();
  236. parameters.Add("@StationId", stationId, DbType.Int16, ParameterDirection.Input);
  237. string strSql = "Select MachineId from [dbo].[StationMachine] where StationId=@StationId; ";
  238. machineIds = conn.Query<String>(strSql, parameters).ToList();
  239. }
  240. return machineIds;
  241. }
  242. private Dictionary<string, decimal?> GetAveragePower(int stationId, int availableCapacity, string machineId = "")
  243. {
  244. Dictionary<string, decimal?> dic = new Dictionary<string, decimal?>();
  245. //總量 * 該樁的額定功率/該站充電中樁的總額定功率
  246. List<string> _MachineIds = new List<string>();
  247. int skipCount = 0;
  248. int size = 200;
  249. int takeCount = 0;
  250. int totalRatePower = 0;
  251. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  252. {
  253. var parameters = new DynamicParameters();
  254. parameters.Add("@StationId", stationId, DbType.Int32, ParameterDirection.Input);
  255. string strSql = "Select MachineId from [dbo].[LoadingBalance] where StationId=@StationId and FinishedOn='1991/01/01'; ";
  256. _MachineIds = conn.Query<string>(strSql, parameters).ToList();
  257. }
  258. if (!string.IsNullOrEmpty(machineId) && !_MachineIds.Contains(machineId))
  259. {
  260. _MachineIds.Add(machineId);
  261. }
  262. while (skipCount < _MachineIds.Count())
  263. {
  264. takeCount = _MachineIds.Count() - skipCount > size ? size : _MachineIds.Count() - skipCount;
  265. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  266. {
  267. string strSql = "Select Sum(RatedPower) from [dbo].[Machine] where Id in @machineIds and [Online]=1; ";
  268. totalRatePower += conn.ExecuteScalar<Int32>(strSql, new { machineIds = _MachineIds.ToArray() });
  269. skipCount += takeCount;
  270. }
  271. }
  272. foreach (var id in _MachineIds)
  273. {
  274. int singleRatePower = (int)GetRatedPower(id);
  275. var value = totalRatePower == 0 ? 0 : availableCapacity * singleRatePower / totalRatePower;
  276. dic.Add(id, value);
  277. }
  278. return dic;
  279. }
  280. private decimal GetRatedPower(string machineId)
  281. {
  282. decimal ratedPower = 0;
  283. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  284. {
  285. var parameters = new DynamicParameters();
  286. parameters.Add("@machineId", machineId, DbType.String, ParameterDirection.Input);
  287. string strSql = "Select RatedPower from [dbo].[Machine] where Id=@machineId; ";
  288. ratedPower = conn.ExecuteScalar<Int32>(strSql, parameters);
  289. }
  290. return ratedPower;
  291. }
  292. private decimal GetFCFSPower(int stationId, string machineId, int availableCapacity)
  293. {
  294. decimal ongoingPower = 0;
  295. decimal singleRatePower = GetRatedPower(machineId);
  296. //先找LB 裡面目前下發的Power
  297. decimal? currentPower = GetCurrentSetting(machineId);
  298. if (!currentPower.HasValue) currentPower = 0;
  299. //總量 - 所有正在進行的Power
  300. using (SqlConnection conn = new SqlConnection(mainConnectionString))
  301. {
  302. var parameters = new DynamicParameters();
  303. parameters.Add("@StationId", stationId, DbType.Int32, ParameterDirection.Input);
  304. string strSql = "Select Sum(Power) from [dbo].[LoadingBalance] where StationId=@StationId and FinishedOn='1991/01/01'; ";
  305. ongoingPower = conn.ExecuteScalar<Int32>(strSql, parameters);
  306. }
  307. return availableCapacity - (ongoingPower - currentPower.Value) > singleRatePower ? singleRatePower :
  308. (availableCapacity - (ongoingPower - currentPower.Value) > 0 ? availableCapacity - (ongoingPower - currentPower.Value) : 0);
  309. }
  310. }
  311. }