MainDbService.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. using Dapper;
  2. using EVCB_OCPP.Domain;
  3. using EVCB_OCPP.Domain.ConnectionFactory;
  4. using EVCB_OCPP.Domain.Models.MainDb;
  5. using EVCB_OCPP.Packet.Features;
  6. using EVCB_OCPP.Packet.Messages.Core;
  7. using EVCB_OCPP.Packet.Messages.FirmwareManagement;
  8. using EVCB_OCPP.Packet.Messages.LocalAuthListManagement;
  9. using EVCB_OCPP.Packet.Messages.RemoteTrigger;
  10. using EVCB_OCPP.Packet.Messages.Reservation;
  11. using EVCB_OCPP.Packet.Messages.Security;
  12. using EVCB_OCPP.Packet.Messages.SmartCharging;
  13. using EVCB_OCPP.WSServer.Helper;
  14. using EVCB_OCPP.WSServer.Message;
  15. using Microsoft.AspNetCore.Connections;
  16. using Microsoft.Data.SqlClient;
  17. using Microsoft.EntityFrameworkCore;
  18. using Microsoft.Extensions.Caching.Memory;
  19. using Microsoft.Extensions.Configuration;
  20. using Microsoft.Extensions.Hosting;
  21. using Microsoft.Extensions.Logging;
  22. using Newtonsoft.Json;
  23. using OCPPPackage.Profiles;
  24. using System.Data;
  25. namespace EVCB_OCPP.WSServer.Service.DbService;
  26. public interface IMainDbService
  27. {
  28. Task<string> GetMachineAuthorizationKey(string ChargeBoxId, CancellationToken token = default);
  29. Task<string> GetMachineConfiguration(string ChargeBoxId, string configName, CancellationToken token = default);
  30. Task<string> GetMachineHeartbeatInterval(string ChargeBoxId);
  31. Task<MachineAndCustomerInfo> GetMachineIdAndCustomerInfo(string ChargeBoxId, CancellationToken token = default);
  32. Task<string> GetMachineSecurityProfile(string ChargeBoxId, CancellationToken token = default);
  33. Task UpdateMachineBasicInfo(string ChargeBoxId, Machine machine);
  34. Task AddOCMF(Ocmf oCMF);
  35. ValueTask<ConnectorStatus> GetConnectorStatus(string ChargeBoxId, int ConnectorId);
  36. Task UpdateConnectorStatus(string Id, ConnectorStatus connectorStatus);
  37. ValueTask AddConnectorStatus(string ChargeBoxId, byte ConnectorId, DateTime CreatedOn, int Status,
  38. int ChargePointErrorCodeId, string ErrorInfo, string VendorId, string VendorErrorCode);
  39. Task<string> AddServerMessage(ServerMessage message);
  40. Task<string> AddServerMessage(string ChargeBoxId, string OutAction, object OutRequest, string CreatedBy = "", DateTime? CreatedOn = null, string SerialNo = "", string InMessage = "");
  41. ValueTask AddMachineError(byte ConnectorId, DateTime CreatedOn, int Status, string ChargeBoxId, int ErrorCodeId, string ErrorInfo, int PreStatus, string VendorErrorCode, string VendorId);
  42. ValueTask<Customer> GetCustomer(string id, CancellationToken token = default);
  43. ValueTask<Customer> GetCustomer(Guid id, CancellationToken token = default);
  44. Task<Guid> GetCustomerIdByChargeBoxId(string chargeboxId);
  45. Task<int?> TryGetDuplicatedTransactionId(string chargeBoxId, Guid customerId, int connectorId, DateTime timestamp);
  46. Task<int> AddNewTransactionRecord(TransactionRecord newTransaction);
  47. Task<TransactionRecord> GetTransactionForStopTransaction(int transactionId, string chargeBoxId);
  48. Task UpdateTransaction(int transactionId, int meterStop, DateTime stopTime, int stopReasonId, string stopReason, string stopIdTag, string receipt, int cost);
  49. Task<bool> UpdateHeartBeats(IEnumerable<Machine> heartBeatsData);
  50. Task<bool> UpdateHeartBeats(List<string> machineIds);
  51. Task UpdateTransactionSOC(int id, string startsoc, string stopsoc);
  52. Task UpdateMachineConnectionType(string chargeBoxId, int v);
  53. Task<string> GetMachineConnectorType(string chargeBoxId, CancellationToken token = default);
  54. Task SetMachineConnectionType(string chargeBoxId, int connectionType, CancellationToken token = default);
  55. Task UpdateServerMessageUpdateTime(int table_id);
  56. Task AddMachineConfiguration(string chargeBoxId, string key, string value, bool isReadOnly, bool isExist = true);
  57. Task UpdateMachineConfiguration(string chargeBoxId, string item, string empty, bool v, bool isExists = true);
  58. Task<List<MachineConfigurations>> GetMachineConfiguration(string chargeBoxId);
  59. Task<object> TryGetResponseFromDb(string msgId, CancellationToken token = default);
  60. }
  61. public class MainDbService : IMainDbService
  62. {
  63. public MainDbService(
  64. IDbContextFactory<MainDBContext> contextFactory,
  65. ISqlConnectionFactory<MainDBContext> sqlConnectionFactory,
  66. IMemoryCache memoryCache,
  67. IConfiguration configuration,
  68. ILoggerFactory loggerFactory,
  69. ILogger<MainDbService> logger)
  70. {
  71. this.contextFactory = contextFactory;
  72. this.sqlConnectionFactory = sqlConnectionFactory;
  73. this.memoryCache = memoryCache;
  74. this.loggerFactory = loggerFactory;
  75. this.logger = logger;
  76. var startupLimit = GetStartupLimit(configuration);
  77. //this.connectionString = configuration.GetConnectionString("MainDBContext");
  78. startupSemaphore = new(startupLimit);
  79. var opLimit = GetOpLimit(configuration);
  80. opSemaphore = new SemaphoreSlim(opLimit);
  81. InitUpdateConnectorStatusHandler();
  82. InitUpdateMachineBasicInfoHandler();
  83. InitAddServerMessageHandler();
  84. InitUpdateServerMessageUpdateOnHandler();
  85. InitGetMachineConfigurationHandler();
  86. }
  87. private const string CustomerMemCacheKeyFromat = "Customer_{0}";
  88. //private const string ChargeBoxConnectorIdMemCacheKeyFromat = "Connector_{0}{1}";
  89. private readonly IDbContextFactory<MainDBContext> contextFactory;
  90. private readonly ISqlConnectionFactory<MainDBContext> sqlConnectionFactory;
  91. private readonly IMemoryCache memoryCache;
  92. private readonly ILoggerFactory loggerFactory;
  93. private readonly ILogger<MainDbService> logger;
  94. //private string connectionString;
  95. private readonly QueueSemaphore startupSemaphore;
  96. private readonly SemaphoreSlim opSemaphore;
  97. private GroupHandler<StatusNotificationParam> statusNotificationHandler;
  98. private GroupHandler<UpdateMachineBasicInfoParam> updateMachineBasicInfoHandler;
  99. private GroupHandler<ServerMessage, string> addServerMessageHandler;
  100. private GroupHandler<int> updateServerMessageUpdateOnHandler;
  101. private GroupHandler<string, List<MachineConfigurations>> getMachineConfigurationHandler;
  102. public async Task<MachineAndCustomerInfo> GetMachineIdAndCustomerInfo(string ChargeBoxId, CancellationToken token = default)
  103. {
  104. using var semaphoreWrapper = await startupSemaphore.GetToken();
  105. using var db = await contextFactory.CreateDbContextAsync(token);
  106. var machine = await db.Machine.Where(x => x.ChargeBoxId == ChargeBoxId && x.IsDelete == false).Select(x => new { x.CustomerId, x.Id }).AsNoTracking().FirstOrDefaultAsync(token);
  107. if (machine == null)
  108. {
  109. return new MachineAndCustomerInfo(string.Empty, Guid.Empty, "Unknown");
  110. }
  111. //var customerName = await db.Customer.Where(x => x.Id == machine.CustomerId).Select(x => x.Name).FirstOrDefaultAsync();
  112. var customer = await GetCustomer(machine.CustomerId, token);
  113. var customerName = customer?.Name;
  114. return new MachineAndCustomerInfo(machine.Id, machine.CustomerId, customerName);
  115. }
  116. public Task<List<MachineConfigurations>> GetMachineConfiguration(string chargeBoxId)
  117. {
  118. return getMachineConfigurationHandler.HandleAsync(chargeBoxId);
  119. }
  120. public async Task<string> GetMachineConfiguration(string ChargeBoxId, string configName, CancellationToken token = default)
  121. {
  122. using var semaphoreWrapper = await startupSemaphore.GetToken();
  123. using var db = await contextFactory.CreateDbContextAsync(token);
  124. return await db.MachineConfigurations
  125. .Where(x => x.ChargeBoxId == ChargeBoxId && x.ConfigureName == configName)
  126. .Select(x => x.ConfigureSetting).FirstOrDefaultAsync(token);
  127. }
  128. public Task<string> GetMachineSecurityProfile(string ChargeBoxId, CancellationToken token = default)
  129. {
  130. return GetMachineConfiguration(ChargeBoxId, StandardConfiguration.SecurityProfile, token);
  131. }
  132. public Task<string> GetMachineAuthorizationKey(string ChargeBoxId, CancellationToken token = default)
  133. {
  134. return GetMachineConfiguration(ChargeBoxId, StandardConfiguration.AuthorizationKey, token);
  135. }
  136. public Task<string> GetMachineHeartbeatInterval(string ChargeBoxId)
  137. {
  138. return GetMachineConfiguration(ChargeBoxId, StandardConfiguration.HeartbeatInterval);
  139. }
  140. public Task UpdateMachineBasicInfo(string ChargeBoxId, Machine machine)
  141. {
  142. //return UpdateMachineBasicInfoEF(ChargeBoxId, machine);
  143. return updateMachineBasicInfoHandler.HandleAsync(new UpdateMachineBasicInfoParam(ChargeBoxId, machine));
  144. }
  145. public async Task AddOCMF(Ocmf oCMF)
  146. {
  147. using var db = await contextFactory.CreateDbContextAsync();
  148. await db.Ocmf.AddAsync(oCMF);
  149. await db.SaveChangesAsync();
  150. }
  151. public async ValueTask AddConnectorStatus(
  152. string ChargeBoxId, byte ConnectorId, DateTime CreatedOn, int Status,
  153. int ChargePointErrorCodeId, string ErrorInfo, string VendorId, string VendorErrorCode)
  154. {
  155. using var db = await contextFactory.CreateDbContextAsync();
  156. var _currentStatus = new ConnectorStatus()
  157. {
  158. ChargeBoxId = ChargeBoxId,
  159. ConnectorId = ConnectorId,
  160. CreatedOn = CreatedOn,
  161. Status = Status,
  162. ChargePointErrorCodeId = ChargePointErrorCodeId,
  163. ErrorInfo = ErrorInfo,
  164. VendorId = VendorId,
  165. VendorErrorCode = VendorErrorCode,
  166. Id = Guid.NewGuid().ToString()
  167. };
  168. await db.ConnectorStatus.AddAsync(_currentStatus);
  169. await db.SaveChangesAsync();
  170. //memoryCache.Set(
  171. // string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, ChargeBoxId, ConnectorId)
  172. // , _currentStatus, TimeSpan.FromHours(12));
  173. }
  174. public async ValueTask<ConnectorStatus> GetConnectorStatus(string ChargeBoxId, int ConnectorId)
  175. {
  176. //var key = string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, ChargeBoxId, ConnectorId);
  177. //if (memoryCache.TryGetValue<ConnectorStatus>(key, out var status))
  178. //{
  179. // return status;
  180. //}
  181. using var db = await contextFactory.CreateDbContextAsync();
  182. var statusFromDb = await db.ConnectorStatus.Where(x => x.ChargeBoxId == ChargeBoxId
  183. && x.ConnectorId == ConnectorId).AsNoTracking().FirstOrDefaultAsync();
  184. //memoryCache.Set(key, statusFromDb, TimeSpan.FromHours(12));
  185. return statusFromDb;
  186. }
  187. public async Task UpdateConnectorStatus(string Id, ConnectorStatus Status)
  188. {
  189. //await statusNotificationHandler.HandleAsync(new StatusNotificationParam(Id, Status));
  190. //await UpdateConnectorStatusEF(Id, Status);
  191. await UpdateConnectorStatusDapper(Id, Status);
  192. //var key = string.Format(ChargeBoxConnectorIdMemCacheKeyFromat, Status.ChargeBoxId, Status.ConnectorId);
  193. //memoryCache.Set(key, Status, TimeSpan.FromHours(12));
  194. return;
  195. }
  196. public Task<Guid> GetCustomerIdByChargeBoxId(string chargeboxId)
  197. {
  198. //return GetCustomerIdByChargeBoxIdEF(chargeboxId);
  199. return GetCustomerIdByChargeBoxIdDapper(chargeboxId);
  200. }
  201. public Task<int?> TryGetDuplicatedTransactionId(string chargeBoxId, Guid customerId, int connectorId, DateTime timestamp)
  202. {
  203. //return TryGetDuplicatedTransactionIdEF(chargeBoxId, customerId, connectorId, timestamp);
  204. return TryGetDuplicatedTransactionIdDapper(chargeBoxId, customerId, connectorId, timestamp);
  205. }
  206. public ValueTask AddMachineError(byte ConnectorId, DateTime CreatedOn, int Status, string ChargeBoxId,
  207. int ErrorCodeId, string ErrorInfo, int PreStatus, string VendorErrorCode, string VendorId)
  208. {
  209. //return AddMachineErrorEF(ConnectorId, CreatedOn, Status, ChargeBoxId, ErrorCodeId, ErrorInfo, PreStatus, VendorErrorCode, VendorId);
  210. return AddMachineErrorDapper(ConnectorId, CreatedOn, Status, ChargeBoxId, ErrorCodeId, ErrorInfo, PreStatus, VendorErrorCode, VendorId);
  211. }
  212. public async Task<string> AddServerMessage(string ChargeBoxId, string OutAction, object OutRequest, string CreatedBy, DateTime? CreatedOn = null, string SerialNo = "", string InMessage = "")
  213. {
  214. if (string.IsNullOrEmpty(CreatedBy))
  215. {
  216. CreatedBy = "Server";
  217. }
  218. if (string.IsNullOrEmpty(SerialNo))
  219. {
  220. SerialNo = Guid.NewGuid().ToString();
  221. }
  222. var _CreatedOn = CreatedOn ?? DateTime.UtcNow;
  223. string _OutRequest = "";
  224. if (OutRequest is not null)
  225. {
  226. _OutRequest = JsonConvert.SerializeObject(
  227. OutRequest,
  228. new JsonSerializerSettings()
  229. {
  230. NullValueHandling = NullValueHandling.Ignore,
  231. Formatting = Formatting.None
  232. });
  233. }
  234. var data = new ServerMessage()
  235. {
  236. ChargeBoxId = ChargeBoxId,
  237. CreatedBy = CreatedBy,
  238. CreatedOn = _CreatedOn,
  239. OutAction = OutAction,
  240. OutRequest = _OutRequest,
  241. SerialNo = SerialNo,
  242. InMessage = InMessage
  243. };
  244. await AddServerMessage(data);
  245. return SerialNo;
  246. }
  247. public Task<string> AddServerMessage(ServerMessage message)
  248. {
  249. //return AddServerMessageEF(message);
  250. return addServerMessageHandler.HandleAsync(message);
  251. //var id = message.SerialNo;
  252. //await AddServerMessageDapper(message);
  253. //return id;
  254. }
  255. public ValueTask<Customer> GetCustomer(string id, CancellationToken token = default)
  256. => GetCustomer(new Guid(id), token);
  257. public async ValueTask<Customer> GetCustomer(Guid id, CancellationToken token = default)
  258. {
  259. var key = string.Format(CustomerMemCacheKeyFromat, id);
  260. if (memoryCache.TryGetValue<Customer>(key, out var customer))
  261. {
  262. return customer;
  263. }
  264. Customer toReturn = null;
  265. using (var db = await contextFactory.CreateDbContextAsync(token))
  266. {
  267. toReturn = await db.Customer.FirstOrDefaultAsync(x => x.Id == id, token);
  268. }
  269. if (toReturn is not null)
  270. {
  271. memoryCache.Set(key, toReturn, TimeSpan.FromSeconds(15));
  272. }
  273. return toReturn;
  274. }
  275. public Task<int> AddNewTransactionRecord(TransactionRecord newTransaction)
  276. {
  277. //return AddNewTransactionRecordEF(newTransaction);
  278. return AddNewTransactionRecordDapper(newTransaction);
  279. }
  280. public Task<TransactionRecord> GetTransactionForStopTransaction(int transactionId, string chargeBoxId)
  281. {
  282. //return GetTransactionForStopTransactionEF(transactionId, chargeBoxId);
  283. return GetTransactionForStopTransactionDapper(transactionId, chargeBoxId);
  284. }
  285. public Task UpdateTransaction(int transactionId, int meterStop, DateTime stopTime, int stopReasonId, string stopReason, string stopIdTag, string receipt, int cost)
  286. {
  287. //return UpdateTransactionEF(transactionId, meterStop, stopTime, stopReasonId, stopReason, stopIdTag, receipt, cost);
  288. return UpdateTransactionDapper(transactionId, meterStop, stopTime, stopReasonId, stopReason, stopIdTag, receipt, cost);
  289. }
  290. public async Task UpdateTransactionSOC(int id, string startSOC, string stopSOC)
  291. {
  292. var parameters = new DynamicParameters();
  293. parameters.Add("@TransactionId", id, DbType.Int32, ParameterDirection.Input);
  294. parameters.Add("@StartSOC", startSOC, DbType.String, ParameterDirection.Input, 3);
  295. parameters.Add("@StopSOC", stopSOC, DbType.String, ParameterDirection.Input, 3);
  296. using var conn = await sqlConnectionFactory.CreateAsync();
  297. var resultCnt = await conn.ExecuteAsync("""
  298. UPDATE TransactionRecord
  299. SET StartSOC = @StartSOC, StopSOC = @StopSOC
  300. WHERE Id = @TransactionId
  301. """, parameters);
  302. if (resultCnt != 1)
  303. {
  304. throw new Exception("Update over one columes");
  305. }
  306. return;
  307. }
  308. public Task UpdateServerMessageUpdateTime(int table_id)
  309. {
  310. return updateServerMessageUpdateOnHandler.HandleAsync(table_id);
  311. }
  312. public async Task AddMachineConfiguration(string chargeBoxId, string key, string value, bool isReadOnly, bool isExists = true)
  313. {
  314. using var db = await contextFactory.CreateDbContextAsync();
  315. await db.MachineConfigurations.AddAsync(new MachineConfigurations()
  316. {
  317. ChargeBoxId = chargeBoxId,
  318. ConfigureName = key,
  319. ReadOnly = isReadOnly,
  320. ConfigureSetting = string.IsNullOrEmpty(value) ? string.Empty : value,
  321. Exists = isExists
  322. });
  323. await db.SaveChangesAsync();
  324. }
  325. private async Task UpdateTransactionEF(int transactionId, int meterStop, DateTime stopTime, int stopReasonId, string stopReason, string stopIdTag, string receipt, int cost)
  326. {
  327. using var db = await contextFactory.CreateDbContextAsync();
  328. var _transaction = db.TransactionRecord.Where(x => x.Id == transactionId //&& x.ChargeBoxId == session.ChargeBoxId
  329. ).FirstOrDefault();
  330. _transaction.MeterStop = meterStop;
  331. _transaction.StopTime = stopTime;
  332. _transaction.StopReasonId = stopReasonId;
  333. _transaction.StopReason = stopReason;
  334. _transaction.StopIdTag = stopIdTag;
  335. _transaction.Receipt = receipt;
  336. _transaction.Cost = cost;
  337. //await db.SaveChangesAsync();
  338. await db.SaveChangesAsync();
  339. }
  340. public async Task UpdateMachineConfiguration(string chargeBoxId, string item, string value, bool isReadonly, bool isExists = true)
  341. {
  342. using var db = await contextFactory.CreateDbContextAsync();
  343. var config = await db.MachineConfigurations.FirstOrDefaultAsync(x => x.ChargeBoxId == chargeBoxId && x.ConfigureName == item);
  344. if (config is null)
  345. {
  346. return;
  347. }
  348. config.ConfigureSetting = value;
  349. config.ReadOnly = isReadonly;
  350. config.Exists = isExists;
  351. await db.SaveChangesAsync();
  352. }
  353. private async Task UpdateTransactionDapper(int transactionId, int meterStop, DateTime stopTime, int stopReasonId, string stopReason, string stopIdTag, string receipt, int cost)
  354. {
  355. var parameters = new DynamicParameters();
  356. parameters.Add("@TransactionId", transactionId, DbType.Int32, ParameterDirection.Input);
  357. parameters.Add("@MeterStop", meterStop, DbType.Decimal, ParameterDirection.Input, precision: 18, scale: 2);
  358. parameters.Add("@StopTime", stopTime, DbType.DateTime, ParameterDirection.Input);
  359. parameters.Add("@StopReasonId", stopReasonId, DbType.Int32, ParameterDirection.Input);
  360. parameters.Add("@StopReason", stopReason, DbType.String, ParameterDirection.Input, 60);
  361. parameters.Add("@StopIdTag", stopIdTag, DbType.String, ParameterDirection.Input, 20);
  362. parameters.Add("@Receipt", receipt, DbType.String, ParameterDirection.Input, 3000);
  363. parameters.Add("@Cost", cost, DbType.Decimal, ParameterDirection.Input, precision: 18, scale: 2);
  364. using var conn = await sqlConnectionFactory.CreateAsync();
  365. var resultCnt = await conn.ExecuteAsync("""
  366. UPDATE TransactionRecord
  367. SET MeterStop = @MeterStop, StopTime = @StopTime, StopReasonId = @StopReasonId,
  368. StopReason = @StopReason, StopIdTag = @StopIdTag, Receipt = @Receipt, Cost = @Cost
  369. WHERE Id = @TransactionId
  370. """, parameters);
  371. if (resultCnt != 1)
  372. {
  373. throw new Exception("Update over one columes");
  374. }
  375. return;
  376. }
  377. public Task<bool> UpdateHeartBeats(IEnumerable<Machine> heartBeatsData)
  378. {
  379. //return UpdateHeartBeatsEF(heartBeatsData);
  380. return UpdateHeartBeatsDapper(heartBeatsData);
  381. }
  382. public Task<bool> UpdateHeartBeats(List<string> machineIds)
  383. {
  384. return UpdateHeartBeatsDapper(machineIds);
  385. }
  386. public async Task UpdateMachineConnectionType(string chargeBoxId, int connectionType)
  387. {
  388. using var semaphoreWrapper = await startupSemaphore.GetToken();
  389. using var db = await contextFactory.CreateDbContextAsync();
  390. var machine = await db.Machine.Where(x => x.ChargeBoxId == chargeBoxId).FirstOrDefaultAsync();
  391. if (machine != null)
  392. {
  393. machine.ConnectionType = connectionType;
  394. await db.SaveChangesAsync();
  395. }
  396. }
  397. public async Task<object> TryGetResponseFromDb(string msgId, CancellationToken token = default)
  398. {
  399. var parameters = new DynamicParameters();
  400. parameters.Add("@MID", msgId, DbType.String, size: 36);
  401. parameters.Add("@MT", DateTime.UtcNow.AddSeconds(-5), DbType.DateTime);
  402. var sql = """
  403. SELECT [OutAction],[InMessage]
  404. FROM [ServerMessage]
  405. WHERE [SerialNo] = @MID AND CreatedOn > @MT
  406. """;
  407. using var conn = await sqlConnectionFactory.CreateAsync();
  408. ServerMessage item = null;
  409. item = await conn.QueryFirstOrDefaultAsync<ServerMessage>(new CommandDefinition(sql, parameters: parameters, cancellationToken: token));
  410. Actions action = Actions.None;
  411. if (item is null ||
  412. !Enum.TryParse(item.OutAction, out action))
  413. {
  414. return null;
  415. }
  416. switch (action)
  417. {
  418. case Actions.GetConfiguration:
  419. return JsonConvert.DeserializeObject<GetConfigurationConfirmation>(item.InMessage);
  420. case Actions.ChangeConfiguration:
  421. return JsonConvert.DeserializeObject<ChangeConfigurationConfirmation>(item.InMessage);
  422. case Actions.RemoteStartTransaction:
  423. return JsonConvert.DeserializeObject<RemoteStartTransactionConfirmation>(item.InMessage);
  424. case Actions.RemoteStopTransaction:
  425. return JsonConvert.DeserializeObject<RemoteStopTransactionConfirmation>(item.InMessage);
  426. case Actions.ChangeAvailability:
  427. return JsonConvert.DeserializeObject<ChangeAvailabilityConfirmation>(item.InMessage);
  428. case Actions.ClearCache:
  429. return JsonConvert.DeserializeObject<ClearCacheConfirmation>(item.InMessage);
  430. case Actions.DataTransfer:
  431. return JsonConvert.DeserializeObject<DataTransferConfirmation>(item.InMessage);
  432. case Actions.Reset:
  433. return JsonConvert.DeserializeObject<ResetConfirmation>(item.InMessage);
  434. case Actions.UnlockConnector:
  435. return JsonConvert.DeserializeObject<UnlockConnectorConfirmation>(item.InMessage);
  436. case Actions.TriggerMessage:
  437. return JsonConvert.DeserializeObject<TriggerMessageConfirmation>(item.InMessage);
  438. case Actions.GetDiagnostics:
  439. return JsonConvert.DeserializeObject<GetDiagnosticsConfirmation>(item.InMessage);
  440. case Actions.UpdateFirmware:
  441. return JsonConvert.DeserializeObject<UpdateFirmwareConfirmation>(item.InMessage);
  442. case Actions.GetLocalListVersion:
  443. return JsonConvert.DeserializeObject<GetLocalListVersionConfirmation>(item.InMessage);
  444. case Actions.SendLocalList:
  445. return JsonConvert.DeserializeObject<SendLocalListConfirmation>(item.InMessage);
  446. case Actions.SetChargingProfile:
  447. return JsonConvert.DeserializeObject<SetChargingProfileConfirmation>(item.InMessage);
  448. case Actions.ClearChargingProfile:
  449. return JsonConvert.DeserializeObject<ClearChargingProfileConfirmation>(item.InMessage);
  450. case Actions.GetCompositeSchedule:
  451. return JsonConvert.DeserializeObject<GetCompositeScheduleConfirmation>(item.InMessage);
  452. case Actions.ReserveNow:
  453. return JsonConvert.DeserializeObject<ReserveNowConfirmation>(item.InMessage);
  454. case Actions.CancelReservation:
  455. return JsonConvert.DeserializeObject<CancelReservationConfirmation>(item.InMessage);
  456. case Actions.ExtendedTriggerMessage:
  457. return JsonConvert.DeserializeObject<ExtendedTriggerMessageConfirmation>(item.InMessage);
  458. default:
  459. return null;
  460. }
  461. }
  462. private void InitUpdateConnectorStatusHandler()
  463. {
  464. if (statusNotificationHandler is not null)
  465. {
  466. throw new Exception($"{nameof(InitUpdateConnectorStatusHandler)} should only called once");
  467. }
  468. statusNotificationHandler = new GroupHandler<StatusNotificationParam>(
  469. handleFunc: BundleUpdateConnectorStatusDapper,
  470. logger: loggerFactory.CreateLogger("StatusNotificationHandler"),
  471. workerCnt: 1);
  472. }
  473. private void InitAddServerMessageHandler()
  474. {
  475. if (addServerMessageHandler is not null)
  476. {
  477. throw new Exception($"{nameof(InitAddServerMessageHandler)} should only called once");
  478. }
  479. addServerMessageHandler = new GroupHandler<ServerMessage, string>(
  480. handleFunc: BundleAddServerMessage,
  481. logger: loggerFactory.CreateLogger("AddServerMessageHandler"));
  482. }
  483. private void InitUpdateMachineBasicInfoHandler()
  484. {
  485. if (updateMachineBasicInfoHandler is not null)
  486. {
  487. throw new Exception($"{nameof(InitUpdateMachineBasicInfoHandler)} should only called once");
  488. }
  489. updateMachineBasicInfoHandler = new GroupHandler<UpdateMachineBasicInfoParam>(
  490. handleFunc: BundelUpdateMachineBasicInfo,
  491. logger: loggerFactory.CreateLogger("UpdateMachineBasicInfoHandler"),
  492. workerCnt: 1);
  493. }
  494. private void InitUpdateServerMessageUpdateOnHandler()
  495. {
  496. if (updateServerMessageUpdateOnHandler is not null)
  497. {
  498. throw new Exception($"{nameof(InitUpdateMachineBasicInfoHandler)} should only called once");
  499. }
  500. updateServerMessageUpdateOnHandler = new GroupHandler<int>(
  501. handleFunc: BundelUpdateServerMessageUpdateOn,
  502. logger: loggerFactory.CreateLogger("UpdateServerMessageUpdateOnHandler"),
  503. workerCnt: 10);
  504. }
  505. private void InitGetMachineConfigurationHandler()
  506. {
  507. if (getMachineConfigurationHandler is not null)
  508. {
  509. throw new Exception($"{nameof(InitUpdateMachineBasicInfoHandler)} should only called once");
  510. }
  511. getMachineConfigurationHandler = new GroupHandler<string, List<MachineConfigurations>>(
  512. handleFunc: BundelGetMachineConfiguration,
  513. logger: loggerFactory.CreateLogger("GetMachineConfigurationHandler"),
  514. workerCnt: 10);
  515. }
  516. private async Task UpdateMachineBasicInfoEF(string chargeBoxId, Machine machine)
  517. {
  518. using var semaphoreWrapper = await startupSemaphore.GetToken();
  519. using var db = await contextFactory.CreateDbContextAsync();
  520. var _machine = await db.Machine.FirstOrDefaultAsync(x => x.ChargeBoxId == chargeBoxId);
  521. _machine.ChargeBoxSerialNumber = machine.ChargeBoxSerialNumber;
  522. _machine.ChargePointSerialNumber = machine.ChargePointSerialNumber;
  523. _machine.ChargePointModel = machine.ChargePointModel;
  524. _machine.ChargePointVendor = machine.ChargePointVendor;
  525. _machine.FwCurrentVersion = machine.FwCurrentVersion;
  526. _machine.Iccid = machine.Iccid;
  527. _machine.Imsi = machine.Imsi;
  528. _machine.MeterSerialNumber = machine.MeterSerialNumber;
  529. _machine.MeterType = machine.MeterType;
  530. await db.SaveChangesAsync();
  531. //using var semaphoreWrapper = await startupSemaphore.GetToken();
  532. }
  533. private async Task BundelUpdateMachineBasicInfo(BundleHandlerData<UpdateMachineBasicInfoParam> bundleHandlerData)
  534. {
  535. using var db = await contextFactory.CreateDbContextAsync();
  536. using var trans = await db.Database.BeginTransactionAsync();
  537. var pams = bundleHandlerData.Datas.DistinctBy(x => x.ChargeBoxId);
  538. foreach (var pam in pams)
  539. {
  540. var _machine = db.Machine.FirstOrDefault(x => x.ChargeBoxId == pam.ChargeBoxId);
  541. _machine.ChargeBoxSerialNumber = pam.machine.ChargeBoxSerialNumber;
  542. _machine.ChargePointSerialNumber = pam.machine.ChargePointSerialNumber;
  543. _machine.ChargePointModel = pam.machine.ChargePointModel;
  544. _machine.ChargePointVendor = pam.machine.ChargePointVendor;
  545. _machine.FwCurrentVersion = pam.machine.FwCurrentVersion;
  546. _machine.Iccid = pam.machine.Iccid;
  547. _machine.Imsi = pam.machine.Imsi;
  548. _machine.MeterSerialNumber = pam.machine.MeterSerialNumber;
  549. _machine.MeterType = pam.machine.MeterType;
  550. }
  551. await db.SaveChangesAsync();
  552. await trans.CommitAsync();
  553. bundleHandlerData.CompletedDatas.AddRange(bundleHandlerData.Datas);
  554. }
  555. private async Task BundelUpdateServerMessageUpdateOn(BundleHandlerData<int> bundleHandlerData)
  556. {
  557. var ids = bundleHandlerData.Datas;
  558. var sql = """
  559. UPDATE [dbo].[ServerMessage]
  560. SET UpdatedOn = @DateTimeNow
  561. WHERE Id in @Ids
  562. """;
  563. DynamicParameters parameters = new DynamicParameters();
  564. parameters.Add("DateTimeNow", DateTime.UtcNow, DbType.DateTime);
  565. parameters.Add("Ids", ids);
  566. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  567. var cnt = await sqlConnection.ExecuteAsync(sql, parameters);
  568. if (cnt != 0 || ids.Count == 0)
  569. {
  570. bundleHandlerData.CompletedDatas.AddRange(ids);
  571. }
  572. }
  573. private async Task BundelGetMachineConfiguration(BundleHandlerData<string, List<MachineConfigurations>> bundleHandlerData)
  574. {
  575. var chargeboxIds = bundleHandlerData.Datas;
  576. var sql = """
  577. SELECT [ChargeBoxId], [ConfigureName], [ConfigureSetting], [ReadOnly], [Exists]
  578. FROM [dbo].[MachineConfigurations]
  579. WHERE ChargeBoxId IN @ChargeBoxIds
  580. """;
  581. DynamicParameters parameters = new DynamicParameters();
  582. parameters.Add("@ChargeBoxIds", chargeboxIds, direction: ParameterDirection.Input, size: 25);
  583. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  584. var result = await sqlConnection.QueryAsync<MachineConfigurations>(sql, parameters);
  585. var gReult = result.GroupBy(x => x.ChargeBoxId);
  586. foreach (var g in gReult)
  587. {
  588. var originKey = chargeboxIds.FirstOrDefault(x=> x.ToLower() == g.Key.ToLower());
  589. if (string.IsNullOrEmpty(originKey))
  590. {
  591. continue;
  592. }
  593. bundleHandlerData.AddCompletedData(originKey, g.ToList());
  594. }
  595. var getConfigChargeboxIds = gReult.Select(x => x.Key);
  596. var emptyConfigChargeboxIds = chargeboxIds.Except(getConfigChargeboxIds);
  597. foreach (var chargeboxId in emptyConfigChargeboxIds)
  598. {
  599. bundleHandlerData.AddCompletedData(chargeboxId, new List<MachineConfigurations>());
  600. }
  601. }
  602. private async Task UpdateConnectorStatusEF(string Id, ConnectorStatus Status)
  603. {
  604. using var db = await contextFactory.CreateDbContextAsync();
  605. ConnectorStatus status = new() { Id = Id };
  606. db.ChangeTracker.AutoDetectChangesEnabled = false;
  607. db.ConnectorStatus.Attach(status);
  608. status.CreatedOn = Status.CreatedOn;
  609. status.Status = Status.Status;
  610. status.ChargePointErrorCodeId = Status.ChargePointErrorCodeId;
  611. status.ErrorInfo = Status.ErrorInfo;
  612. status.VendorId = Status.VendorId;
  613. status.VendorErrorCode = Status.VendorErrorCode;
  614. db.Entry(status).Property(x => x.CreatedOn).IsModified = true;
  615. db.Entry(status).Property(x => x.Status).IsModified = true;
  616. db.Entry(status).Property(x => x.ChargePointErrorCodeId).IsModified = true;
  617. db.Entry(status).Property(x => x.ErrorInfo).IsModified = true;
  618. db.Entry(status).Property(x => x.VendorId).IsModified = true;
  619. db.Entry(status).Property(x => x.VendorErrorCode).IsModified = true;
  620. await db.SaveChangesAsync();
  621. }
  622. private async Task UpdateConnectorStatusDapper(string Id, ConnectorStatus Status)
  623. {
  624. var parameters = new DynamicParameters();
  625. parameters.Add("@Id", Id, DbType.String, ParameterDirection.Input, 36);
  626. parameters.Add("@CreatedOn", Status.CreatedOn, DbType.DateTime, ParameterDirection.Input);
  627. parameters.Add("@Status", Status.Status, DbType.Int32, ParameterDirection.Input);
  628. parameters.Add("@ChargePointErrorCodeId", Status.ChargePointErrorCodeId, DbType.Int32, ParameterDirection.Input);
  629. parameters.Add("@ErrorInfo", Status.ErrorInfo, DbType.String, ParameterDirection.Input, 50);
  630. parameters.Add("@VendorId", Status.VendorId, DbType.String, ParameterDirection.Input, 255);
  631. parameters.Add("@VendorErrorCode", Status.VendorErrorCode, DbType.String, ParameterDirection.Input, 100);
  632. using var conn = await sqlConnectionFactory.CreateAsync();
  633. await conn.ExecuteAsync("""
  634. update ConnectorStatus
  635. set
  636. CreatedOn = @CreatedOn,
  637. Status = @Status,
  638. ChargePointErrorCodeId = @ChargePointErrorCodeId,
  639. ErrorInfo = @ErrorInfo,
  640. VendorId = @VendorId,
  641. VendorErrorCode = @VendorErrorCode
  642. where Id = @Id
  643. """, parameters);
  644. }
  645. private async Task<Guid> GetCustomerIdByChargeBoxIdEF(string chargeboxId)
  646. {
  647. using var db = await contextFactory.CreateDbContextAsync();
  648. var _CustomerId = await db.Machine.Where(x => x.ChargeBoxId == chargeboxId).Select(x => x.CustomerId).FirstOrDefaultAsync();
  649. return _CustomerId;
  650. }
  651. private async Task<Guid> GetCustomerIdByChargeBoxIdDapper(string chargeboxId)
  652. {
  653. var parameters = new DynamicParameters();
  654. parameters.Add("@ChargeBoxId", chargeboxId, DbType.String, ParameterDirection.Input, 50);
  655. using var conn = await sqlConnectionFactory.CreateAsync();
  656. var _existedTx = await conn.QueryFirstOrDefaultAsync<Guid>("""
  657. select CustomerId
  658. from dbo.Machine
  659. where
  660. ChargeBoxId = @ChargeBoxId
  661. """, parameters);
  662. return _existedTx;
  663. }
  664. private async Task<int?> TryGetDuplicatedTransactionIdEF(string chargeBoxId, Guid customerId, int connectorId, DateTime timestamp)
  665. {
  666. using var db = await contextFactory.CreateDbContextAsync();
  667. var _existedTx = await db.TransactionRecord.Where(x => x.CustomerId == customerId && x.ChargeBoxId == chargeBoxId
  668. && x.ConnectorId == connectorId && x.StartTime == timestamp).Select(x => x.Id).FirstOrDefaultAsync();
  669. return _existedTx;
  670. }
  671. private async Task<int?> TryGetDuplicatedTransactionIdDapper(string chargeBoxId, Guid customerId, int connectorId, DateTime timestamp)
  672. {
  673. var parameters = new DynamicParameters();
  674. parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input, 50);
  675. parameters.Add("@CustomerId", customerId, DbType.Guid, ParameterDirection.Input);
  676. parameters.Add("@ConnectorId", connectorId, DbType.Int16, ParameterDirection.Input);
  677. parameters.Add("@TimeStamp", timestamp, DbType.DateTime, ParameterDirection.Input);
  678. using var conn = await sqlConnectionFactory.CreateAsync();
  679. var _existedTx = await conn.QueryFirstOrDefaultAsync<int?>("""
  680. SELECT Id
  681. FROM dbo.TransactionRecord
  682. WHERE
  683. ChargeBoxId = @ChargeBoxId and
  684. CustomerId = @CustomerId and
  685. ConnectorId = @ConnectorId and
  686. StartTime = @TimeStamp
  687. """, parameters);
  688. return _existedTx;
  689. }
  690. private async ValueTask AddMachineErrorEF(byte connectorId, DateTime createdOn, int status, string chargeBoxId, int errorCodeId, string errorInfo, int preStatus, string vendorErrorCode, string vendorId)
  691. {
  692. using var db = await contextFactory.CreateDbContextAsync();
  693. await db.MachineError.AddAsync(new MachineError()
  694. {
  695. ConnectorId = connectorId,
  696. CreatedOn = createdOn,
  697. Status = status,
  698. ChargeBoxId = chargeBoxId,
  699. ErrorCodeId = errorCodeId,
  700. ErrorInfo = errorInfo,
  701. PreStatus = preStatus,
  702. VendorErrorCode = vendorErrorCode,
  703. VendorId = vendorId
  704. });
  705. await db.SaveChangesAsync();
  706. }
  707. private async ValueTask AddMachineErrorDapper(byte connectorId, DateTime createdOn, int status, string chargeBoxId, int errorCodeId, string errorInfo, int preStatus, string vendorErrorCode, string vendorId)
  708. {
  709. var parameters = new DynamicParameters();
  710. parameters.Add("@ConnectorId", connectorId, DbType.Int16, ParameterDirection.Input);
  711. parameters.Add("@PreStatus", preStatus, DbType.Int32, ParameterDirection.Input);
  712. parameters.Add("@Status", status, DbType.Int32, ParameterDirection.Input);
  713. parameters.Add("@ErrorInfo", errorInfo, DbType.String, ParameterDirection.Input, 50);
  714. parameters.Add("@VendorId", vendorId, DbType.String, ParameterDirection.Input, 255);
  715. parameters.Add("@CreatedOn", createdOn, DbType.DateTime, ParameterDirection.Input);
  716. parameters.Add("@ErrorCodeId", errorCodeId, DbType.Int32, ParameterDirection.Input);
  717. parameters.Add("@VendorErrorCode", vendorErrorCode, DbType.String, ParameterDirection.Input, 100);
  718. parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input, 50);
  719. using var conn = await sqlConnectionFactory.CreateAsync();
  720. await conn.ExecuteAsync("""
  721. INSERT INTO MachineError
  722. (ConnectorId, PreStatus, Status, ErrorInfo, VendorId, CreatedOn, ErrorCodeId, VendorErrorCode, ChargeBoxId)
  723. VALUES (@ConnectorId, @PreStatus, @Status, @ErrorInfo, @VendorId, @CreatedOn, @ErrorCodeId, @VendorErrorCode, @ChargeBoxId)
  724. """, parameters);
  725. }
  726. private async Task BundleUpdateConnectorStatus(IEnumerable<StatusNotificationParam> statusNotifications)
  727. {
  728. using var db = await contextFactory.CreateDbContextAsync();
  729. using var trans = await db.Database.BeginTransactionAsync();
  730. statusNotifications = statusNotifications.OrderBy(x => x.Status.CreatedOn).DistinctBy(x => x.Id);
  731. foreach (var param in statusNotifications)
  732. {
  733. ConnectorStatus status = new() { Id = param.Id };
  734. //db.ChangeTracker.AutoDetectChangesEnabled = false;
  735. db.ConnectorStatus.Attach(status);
  736. status.CreatedOn = param.Status.CreatedOn;
  737. status.Status = param.Status.Status;
  738. status.ChargePointErrorCodeId = param.Status.ChargePointErrorCodeId;
  739. status.ErrorInfo = param.Status.ErrorInfo;
  740. status.VendorId = param.Status.VendorId;
  741. status.VendorErrorCode = param.Status.VendorErrorCode;
  742. db.Entry(status).Property(x => x.CreatedOn).IsModified = true;
  743. db.Entry(status).Property(x => x.Status).IsModified = true;
  744. db.Entry(status).Property(x => x.ChargePointErrorCodeId).IsModified = true;
  745. db.Entry(status).Property(x => x.ErrorInfo).IsModified = true;
  746. db.Entry(status).Property(x => x.VendorId).IsModified = true;
  747. db.Entry(status).Property(x => x.VendorErrorCode).IsModified = true;
  748. //await db.SaveChangesAsync();
  749. }
  750. await db.SaveChangesAsync();
  751. await trans.CommitAsync();
  752. //db.ChangeTracker.Clear();
  753. }
  754. private async Task BundleUpdateConnectorStatusDapper(BundleHandlerData<StatusNotificationParam> bundleHandlerData)
  755. {
  756. using var conn = await sqlConnectionFactory.CreateAsync();
  757. foreach (var status in bundleHandlerData.Datas)
  758. {
  759. var parameters = new DynamicParameters();
  760. parameters.Add("@Id", status.Id, DbType.String, ParameterDirection.Input, 36);
  761. parameters.Add("@CreatedOn", status.Status.CreatedOn, DbType.DateTime, ParameterDirection.Input);
  762. parameters.Add("@Status", status.Status.Status, DbType.Int32, ParameterDirection.Input);
  763. parameters.Add("@ChargePointErrorCodeId", status.Status.ChargePointErrorCodeId, DbType.Int32, ParameterDirection.Input);
  764. parameters.Add("@ErrorInfo", status.Status.ErrorInfo, DbType.String, ParameterDirection.Input, 50);
  765. parameters.Add("@VendorId", status.Status.VendorId, DbType.String, ParameterDirection.Input, 255);
  766. parameters.Add("@VendorErrorCode", status.Status.VendorErrorCode, DbType.String, ParameterDirection.Input, 100);
  767. await conn.ExecuteAsync("""
  768. update ConnectorStatus
  769. set
  770. CreatedOn = @CreatedOn,
  771. Status = @Status,
  772. ChargePointErrorCodeId = @ChargePointErrorCodeId,
  773. ErrorInfo = @ErrorInfo,
  774. VendorId = @VendorId,
  775. VendorErrorCode = @VendorErrorCode
  776. where Id = @Id
  777. """, parameters);
  778. bundleHandlerData.AddCompletedData(status);
  779. }
  780. }
  781. private async Task BundleAddServerMessage(BundleHandlerData<ServerMessage, string> bundleHandlerData)
  782. {
  783. //var sql = """
  784. // INSERT INTO [ServerMessage] ([ChargeBoxId], [CreatedBy], [CreatedOn], [InMessage], [OutAction], [OutRequest], [ReceivedOn], [SerialNo], [UpdatedOn])
  785. // OUTPUT INSERTED.Id
  786. // VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8)
  787. // """;
  788. //using var conn = await sqlConnectionFactory.CreateAsync();
  789. //foreach(var data in bundleHandlerData.Datas)
  790. //{
  791. // var dymparam = new DynamicParameters();
  792. // dymparam.Add("@p0", data.ChargeBoxId);
  793. // dymparam.Add("@p1", data.CreatedBy);
  794. // dymparam.Add("@p2", data.CreatedOn);
  795. // dymparam.Add("@p3", data.InMessage);
  796. // dymparam.Add("@p4", data.OutAction);
  797. // dymparam.Add("@p5", data.OutRequest);
  798. // dymparam.Add("@p6", data.ReceivedOn);
  799. // dymparam.Add("@p7", data.SerialNo);
  800. // dymparam.Add("@p8", data.UpdatedOn);
  801. //}
  802. using var db = await contextFactory.CreateDbContextAsync();
  803. using var trans = await db.Database.BeginTransactionAsync();
  804. foreach (var message in bundleHandlerData.Datas)
  805. {
  806. await db.ServerMessage.AddAsync(message);
  807. }
  808. await db.SaveChangesAsync();
  809. await trans.CommitAsync();
  810. bundleHandlerData.CompletedDatas.AddRange(bundleHandlerData.Datas.Select(x => new KeyValuePair<ServerMessage, string>(x, x.SerialNo)));
  811. }
  812. private async Task AddServerMessageEF(ServerMessage message)
  813. {
  814. using var db = await contextFactory.CreateDbContextAsync();
  815. using var trans = await db.Database.BeginTransactionAsync();
  816. await db.ServerMessage.AddAsync(message);
  817. await db.SaveChangesAsync();
  818. await trans.CommitAsync();
  819. //db.ChangeTracker.Clear();
  820. }
  821. private async Task AddServerMessageDapper(ServerMessage message)
  822. {
  823. var parameters = new DynamicParameters();
  824. parameters.Add("@SerialNo", message.SerialNo, DbType.String, ParameterDirection.Input, 36);
  825. parameters.Add("@OutAction", message.OutAction, DbType.String, ParameterDirection.Input, 30);
  826. parameters.Add("@OutRequest", message.OutRequest, DbType.String, ParameterDirection.Input);
  827. parameters.Add("@InMessage", message.InMessage, DbType.String, ParameterDirection.Input);
  828. parameters.Add("@CreatedOn", message.CreatedOn, DbType.DateTime, ParameterDirection.Input);
  829. parameters.Add("@CreatedBy", message.CreatedBy, DbType.String, ParameterDirection.Input, 36);
  830. parameters.Add("@ReceivedOn", message.ReceivedOn, DbType.DateTime, ParameterDirection.Input);
  831. parameters.Add("@ChargeBoxId", message.ChargeBoxId, DbType.String, ParameterDirection.Input, 30);
  832. parameters.Add("@UpdatedOn", message.UpdatedOn, DbType.DateTime, ParameterDirection.Input);
  833. using var conn = await sqlConnectionFactory.CreateAsync();
  834. var resultCnt = await conn.ExecuteAsync("""
  835. INSERT INTO ServerMessage
  836. (SerialNo, OutAction, OutRequest, InMessage, CreatedOn, CreatedBy, ReceivedOn, ChargeBoxId, UpdatedOn)
  837. VALUES (@SerialNo, @OutAction, @OutRequest, @InMessage, @CreatedOn, @CreatedBy, @ReceivedOn, @ChargeBoxId, @UpdatedOn)
  838. """, parameters);
  839. if (resultCnt != 1)
  840. {
  841. throw new Exception("Insert failed");
  842. }
  843. return;
  844. }
  845. private async Task<int> AddNewTransactionRecordEF(TransactionRecord newTransaction)
  846. {
  847. using var db = await contextFactory.CreateDbContextAsync();
  848. await db.TransactionRecord.AddAsync(newTransaction);
  849. await db.SaveChangesAsync();
  850. return newTransaction.Id;
  851. }
  852. private async Task<int> AddNewTransactionRecordDapper(TransactionRecord newTransaction)
  853. {
  854. var parameters = new DynamicParameters();
  855. parameters.Add("@ChargeBoxId", newTransaction.ChargeBoxId, DbType.String, ParameterDirection.Input, 50);
  856. parameters.Add("@ConnectorId", newTransaction.ConnectorId, DbType.Int16, ParameterDirection.Input);
  857. parameters.Add("@CreatedOn", newTransaction.CreatedOn, DbType.DateTime, ParameterDirection.Input);
  858. parameters.Add("@UpdatedOn", newTransaction.UpdatedOn, DbType.DateTime, ParameterDirection.Input);
  859. parameters.Add("@StartTransactionReportedOn", newTransaction.StartTransactionReportedOn, DbType.DateTime, ParameterDirection.Input);
  860. parameters.Add("@StopTransactionReportedOn", newTransaction.StopTransactionReportedOn, DbType.DateTime, ParameterDirection.Input);
  861. parameters.Add("@StartIdTag", newTransaction.StartIdTag, DbType.String, ParameterDirection.Input, 20);
  862. parameters.Add("@MeterStart", newTransaction.MeterStart, DbType.Decimal, ParameterDirection.Input, precision: 18, scale: 2);
  863. parameters.Add("@MeterStop", newTransaction.MeterStop, DbType.Decimal, ParameterDirection.Input, precision: 18, scale: 2);
  864. parameters.Add("@CustomerId", newTransaction.CustomerId, DbType.Guid, ParameterDirection.Input);
  865. parameters.Add("@StartTime", newTransaction.StartTime, DbType.DateTime, ParameterDirection.Input);
  866. parameters.Add("@StopTime", newTransaction.StopTime, DbType.DateTime, ParameterDirection.Input);
  867. parameters.Add("@ReservationId", newTransaction.ReservationId, DbType.Int32, ParameterDirection.Input);
  868. parameters.Add("@RetryStartTransactionTimes", newTransaction.RetryStartTransactionTimes, DbType.Int32, ParameterDirection.Input);
  869. parameters.Add("@RetryStopTransactionTimes", newTransaction.RetryStopTransactionTimes, DbType.Int32, ParameterDirection.Input);
  870. parameters.Add("@Fee", newTransaction.Fee, DbType.String, ParameterDirection.Input, 1500);
  871. using var conn = await sqlConnectionFactory.CreateAsync();
  872. var id = await conn.QuerySingleAsync<int>("""
  873. INSERT INTO TransactionRecord
  874. (ChargeBoxId, ConnectorId, CreatedOn, UpdatedOn, StartTransactionReportedOn, StopTransactionReportedOn,
  875. StartIdTag, MeterStart, MeterStop, CustomerId, StartTime, StopTime, ReservationId, RetryStartTransactionTimes, RetryStopTransactionTimes, Fee)
  876. OUTPUT INSERTED.Id
  877. VALUES (@ChargeBoxId, @ConnectorId, @CreatedOn, @UpdatedOn, @StartTransactionReportedOn, @StopTransactionReportedOn,
  878. @StartIdTag, @MeterStart, @MeterStop, @CustomerId, @StartTime, @StopTime, @ReservationId, @RetryStartTransactionTimes, @RetryStopTransactionTimes, @Fee)
  879. """, parameters);
  880. return id;
  881. }
  882. private async Task<TransactionRecord> GetTransactionForStopTransactionEF(int transactionId, string chargeBoxId)
  883. {
  884. using var db = await contextFactory.CreateDbContextAsync();
  885. return await db.TransactionRecord.Where(x => x.Id == transactionId
  886. && x.ChargeBoxId == chargeBoxId).FirstOrDefaultAsync();
  887. }
  888. private async Task<TransactionRecord> GetTransactionForStopTransactionDapper(int transactionId, string chargeBoxId)
  889. {
  890. var parameters = new DynamicParameters();
  891. parameters.Add("@TransactionId", transactionId, DbType.Int32, ParameterDirection.Input);
  892. parameters.Add("@ChargeBoxId", chargeBoxId, DbType.String, ParameterDirection.Input, 50);
  893. using var conn = await sqlConnectionFactory.CreateAsync();
  894. var record = await conn.QuerySingleAsync<TransactionRecord>("""
  895. SELECT Id, ConnectorId, MeterStop, MeterStart, StartTime, StopTime FROM TransactionRecord
  896. WHERE Id = @TransactionId and ChargeBoxId = @ChargeBoxId
  897. """, parameters);
  898. return record;
  899. }
  900. private Task BulkInsertServerMessage(IEnumerable<ServerMessage> messages)
  901. {
  902. var table = new DataTable();
  903. table.Columns.Add("ChargeBoxId");
  904. table.Columns.Add("SerialNo");
  905. table.Columns.Add("OutAction");
  906. table.Columns.Add("OutRequest");
  907. table.Columns.Add("InMessage");
  908. table.Columns.Add("CreatedOn");
  909. table.Columns.Add("CreatedBy");
  910. table.Columns.Add("UpdatedOn");
  911. table.Columns.Add("ReceivedOn");
  912. foreach (var param in messages)
  913. {
  914. var row = table.NewRow();
  915. row["ChargeBoxId"] = param.ChargeBoxId;
  916. row["SerialNo"] = param.SerialNo;
  917. row["OutAction"] = param.OutAction;
  918. row["OutRequest"] = param.OutRequest;
  919. row["InMessage"] = param.InMessage;
  920. row["CreatedOn"] = param.CreatedOn;
  921. row["CreatedBy"] = param.CreatedBy;
  922. row["UpdatedOn"] = param.UpdatedOn;
  923. row["ReceivedOn"] = param.ReceivedOn;
  924. table.Rows.Add(row);
  925. }
  926. using SqlConnection sqlConnection = sqlConnectionFactory.Create();
  927. using SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection);
  928. sqlBulkCopy.BatchSize = messages.Count();
  929. sqlBulkCopy.DestinationTableName = "ServerMessage";
  930. sqlBulkCopy.ColumnMappings.Add("ChargeBoxId", "ChargeBoxId");
  931. sqlBulkCopy.ColumnMappings.Add("SerialNo", "SerialNo");
  932. sqlBulkCopy.ColumnMappings.Add("OutAction", "OutAction");
  933. sqlBulkCopy.ColumnMappings.Add("OutRequest", "OutRequest");
  934. sqlBulkCopy.ColumnMappings.Add("InMessage", "InMessage");
  935. sqlBulkCopy.ColumnMappings.Add("CreatedOn", "CreatedOn");
  936. sqlBulkCopy.ColumnMappings.Add("CreatedBy", "CreatedBy");
  937. sqlBulkCopy.ColumnMappings.Add("UpdatedOn", "UpdatedOn");
  938. sqlBulkCopy.ColumnMappings.Add("ReceivedOn", "ReceivedOn");
  939. return sqlBulkCopy.WriteToServerAsync(table);
  940. }
  941. private int GetStartupLimit(IConfiguration configuration)
  942. {
  943. var limitConfig = configuration["MainDbStartupLimit"];
  944. int limit = 5;
  945. if (limitConfig != default)
  946. {
  947. int.TryParse(limitConfig, out limit);
  948. }
  949. return limit;
  950. }
  951. private int GetOpLimit(IConfiguration configuration)
  952. {
  953. var limitConfig = configuration["MainDbOpLimit"];
  954. int limit = 500;
  955. if (limitConfig != default)
  956. {
  957. int.TryParse(limitConfig, out limit);
  958. }
  959. return limit;
  960. }
  961. private async Task<bool> UpdateHeartBeatsDapper(IEnumerable<Machine> heartBeatsData)
  962. {
  963. using var conn = await sqlConnectionFactory.CreateAsync();
  964. using var trans = await conn.BeginTransactionAsync();
  965. try
  966. {
  967. foreach (var data in heartBeatsData)
  968. {
  969. var parameters = new DynamicParameters();
  970. parameters.Add("@Id", data.Id, DbType.String, ParameterDirection.Input, 36);
  971. parameters.Add("@HeartbeatUpdatedOn", data.HeartbeatUpdatedOn, DbType.DateTime, ParameterDirection.Input);
  972. parameters.Add("@ConnectionType", data.ConnectionType, DbType.Int32, ParameterDirection.Input);
  973. var resultCnt = await conn.ExecuteAsync("""
  974. UPDATE Machine
  975. SET HeartbeatUpdatedOn = @HeartbeatUpdatedOn, ConnectionType = @ConnectionType
  976. WHERE Id = @Id
  977. """, parameters, trans);
  978. if (resultCnt != 1)
  979. {
  980. throw new Exception("Update over one columes");
  981. }
  982. }
  983. await trans.CommitAsync();
  984. }
  985. catch
  986. {
  987. logger.LogCritical("HeartBeatCheckTrigger update fail, roll back");
  988. await trans.RollbackAsync();
  989. return false;
  990. }
  991. return true;
  992. }
  993. private async Task<bool> UpdateHeartBeatsDapper(List<string> machineIds)
  994. {
  995. using var conn = await sqlConnectionFactory.CreateAsync();
  996. try
  997. {
  998. var parameters = new DynamicParameters();
  999. parameters.Add("@Ids", machineIds, size: 36);
  1000. parameters.Add("@HeartbeatUpdatedOn", DateTime.UtcNow, DbType.DateTime, ParameterDirection.Input);
  1001. var resultCnt = await conn.ExecuteAsync("""
  1002. UPDATE Machine
  1003. SET HeartbeatUpdatedOn = @HeartbeatUpdatedOn
  1004. WHERE Id in @Ids
  1005. """, parameters);
  1006. }
  1007. catch (Exception e)
  1008. {
  1009. logger.LogError(e.Message);
  1010. logger.LogCritical("HeartBeatCheckTrigger update fail");
  1011. return false;
  1012. }
  1013. return true;
  1014. }
  1015. private async Task<bool> UpdateHeartBeatsEF(IEnumerable<Machine> heartBeatsData)
  1016. {
  1017. using var db = await contextFactory.CreateDbContextAsync();
  1018. using var transaction = await db.Database.BeginTransactionAsync();
  1019. try
  1020. {
  1021. foreach (var data in heartBeatsData)
  1022. {
  1023. var machine = new Machine() { Id = data.Id };
  1024. if (machine != null)
  1025. {
  1026. db.Machine.Attach(machine);
  1027. machine.HeartbeatUpdatedOn = DateTime.UtcNow;
  1028. machine.ConnectionType = data.ConnectionType;
  1029. db.Entry(machine).Property(x => x.HeartbeatUpdatedOn).IsModified = true;
  1030. db.Entry(machine).Property(x => x.ConnectionType).IsModified = true;
  1031. }
  1032. }
  1033. await db.SaveChangesAsync();
  1034. await transaction.CommitAsync();
  1035. db.ChangeTracker.Clear();
  1036. }
  1037. catch (Exception ex)
  1038. {
  1039. logger.LogCritical(ex, "HeartBeatCheckTrigger update fail, roll back");
  1040. transaction.Rollback();
  1041. return false;
  1042. }
  1043. return true;
  1044. }
  1045. public async Task<string> GetMachineConnectorType(string chargeBoxId, CancellationToken token = default)
  1046. {
  1047. using var db = await contextFactory.CreateDbContextAsync(token);
  1048. var machine = await db.Machine.Where(x => x.ChargeBoxId == chargeBoxId).FirstOrDefaultAsync(token);
  1049. if (machine == null)
  1050. {
  1051. return null;
  1052. }
  1053. return machine.ConnectorType;
  1054. }
  1055. public async Task SetMachineConnectionType(string chargeBoxId, int v, CancellationToken token = default)
  1056. {
  1057. using var db = await contextFactory.CreateDbContextAsync(token);
  1058. var machine = await db.Machine.Where(x => x.ChargeBoxId == chargeBoxId).FirstOrDefaultAsync(token);
  1059. if (machine == null)
  1060. {
  1061. return;
  1062. }
  1063. machine.ConnectionType = v;
  1064. return;
  1065. }
  1066. }
  1067. public record MachineAndCustomerInfo(string MachineId, Guid CustomerId, string CustomerName);
  1068. public record StatusNotificationParam(string Id, ConnectorStatus Status);
  1069. public record UpdateMachineBasicInfoParam(string ChargeBoxId, Machine machine);