sendevent

This commit is contained in:
thuannd88
2024-09-06 17:20:09 +07:00
parent 8fb4e9ae92
commit bcfef9d82d
6 changed files with 280 additions and 36 deletions
+126 -3
View File
@@ -14,6 +14,7 @@ using System.Threading.Tasks;
using Serilog;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using SafeBagDE70.Model;
namespace SafeBagDE70.API
{
@@ -41,19 +42,36 @@ namespace SafeBagDE70.API
Log.Fatal(ex, "SendHealthCheck");
}
}
public static async Task<bool> SendHealthCheck(DeviceStatus? deviceStatus=null)
public static void SendHealthCheck(DeviceStatus? deviceStatus = null)
{
TaskSendHealthCheck(deviceStatus).ContinueWith(t => {
if (t.IsCompletedSuccessfully)
{
Log.Information("Send HealthCheck Success");
}
else
{
Log.Information("Send HealthCheck Fail");
}
});
}
public static async Task<bool> TaskSendHealthCheck(DeviceStatus? deviceStatus=null)
{
bool bSuccess = false;
try
{
if(deviceStatus != null)
{
var json = JsonConvert.SerializeObject(deviceStatus);
var _deviceStatus = JsonConvert.DeserializeObject<DeviceStatus>(json);
_deviceStatus.DeviceTime=DateTime.Now;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient httpClient = new HttpClient(clientHandler);
string strJsonObj = JsonConvert.SerializeObject(deviceStatus);
string strJsonObj = JsonConvert.SerializeObject(_deviceStatus);
var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.PostAsync(AppData.BaseURL + "HealthCheck_v2", content);
@@ -72,6 +90,111 @@ namespace SafeBagDE70.API
}
return bSuccess;
}
public static void SendEvent(DeviceStatus? deviceStatus = null)
{
try
{
if (deviceStatus == null) return;
DeviceEvent deviceEvent = InsertEventToDB(deviceStatus);
deviceStatus.DeviceTime = DateTime.Now;
deviceStatus.TransactionCode = AppData.GetTransactionCode();
TaskSendEvent(deviceStatus).ContinueWith(t =>
{
if (t.IsCompletedSuccessfully)
{
Log.Information("Send Event Success");
deviceEvent.IsSent = t.Result;
UpdateEventToDB(deviceEvent);
}
else
{
Log.Information("Send Event Fail");
}
});
}
catch(Exception ex)
{
Log.Fatal(ex, "SendEvent");
}
}
private static void UpdateEventToDB(DeviceEvent deviceEvent)
{
try
{
using (var db = new CDMDbContext())
{
db.DeviceEvents.Update(deviceEvent);
db.SaveChanges();
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Fail to Update Event to DB");
}
}
private static DeviceEvent InsertEventToDB(DeviceStatus? deviceStatus)
{
var data = JsonConvert.SerializeObject(deviceStatus);
var deviceEvent = new DeviceEvent
{
Data = data,
IsSent = false,
DeviceTime = DateTime.Now
};
try
{
using (var db = new CDMDbContext())
{
db.DeviceEvents.Add(deviceEvent);
db.SaveChanges();
}
}
catch (Exception ex)
{
Log.Fatal(ex, "Fail to Save Event to DB");
}
return deviceEvent;
}
public static async Task<bool> TaskSendEvent(DeviceStatus? deviceStatus = null)
{
bool bSuccess = false;
try
{
if (deviceStatus != null)
{
var json = JsonConvert.SerializeObject(deviceStatus);
var _deviceStatus = JsonConvert.DeserializeObject<DeviceStatus>(json);
_deviceStatus.DeviceTime = DateTime.Now;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
// Pass the handler to httpclient(from you are calling api)
HttpClient httpClient = new HttpClient(clientHandler);
string strJsonObj = JsonConvert.SerializeObject(_deviceStatus);
var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
using HttpResponseMessage response = await httpClient.PostAsync(AppData.BaseURL + "DeviceEvents", content);
if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
{
var jsonResponse = await response.Content.ReadAsStringAsync();
bSuccess = true;
}
}
}
catch (Exception ex)
{
Log.Fatal(ex, "SendHealthCheck");
}
return bSuccess;
}
public static async Task<bool> SendCountingData(CountingData2Send data2Send)
{
@@ -104,7 +227,7 @@ namespace SafeBagDE70.API
{
try
{
var url = AppData.BaseURL + "GetAeonMallCustomers?tenantId="+tenantId;
var url = AppData.BaseURL + "GetAeonMallCustomers?tenantId="+tenantId;
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
+15 -1
View File
@@ -71,7 +71,7 @@ namespace SafeBagDE70
public static CDMSTATE? CDMSTATE = null;
private static DateTime CutOffTime = new DateTime(1, 1, 1, 12, 0, 0); // 12:00 noon as cut-off time
public static void GetNewTransactionCode()
public static void CreateNewTransactionCode()
{
DateTime transactionDateTime = DateTime.Now;
@@ -100,6 +100,13 @@ namespace SafeBagDE70
CurrentCustomerAccount.TransactionCode = transactionId;
CurrentCustomerAccount.TransactionTime = transactionDateTime;
}
public static string GetTransactionCode()
{
if (CurrentCustomerAccount != null)
return CurrentCustomerAccount.TransactionCode;
else
return "";
}
public static CDMSTATE? GetCDMState()
{
try
@@ -393,6 +400,7 @@ namespace SafeBagDE70
public int SensorStatus { get; set; }
public int OtherError { get; set; }
public string? Notes { get; set; }
public string? TransactionCode { get; set; }
public string Description { get; set; }
}
public enum DeviceStatusCode {
@@ -410,4 +418,10 @@ namespace SafeBagDE70
NORMAL = 0,
ERROR = 1
}
public enum CDMStatusCode
{
NORMAL = 0,
DISCONNECT_SERIALPORT=1,
}
}
+2 -2
View File
@@ -845,7 +845,7 @@ namespace SafeBagDE70
{
var data2Send = new CountingData2Send
{
TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
TransactionCode = AppData.GetTransactionCode(),
Sessions = sessions,
MachineId = Environment.MachineName,
UserId = AppData.CurrentCustomerAccount.CustomerId,
@@ -1015,7 +1015,7 @@ namespace SafeBagDE70
Log.Information("PrintReceipt");
var shopName = AppData.CurrentCustomerAccount.Name;
var shopCode = AppData.CurrentCustomerAccount.CustomerId;
var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
var tradingCode = AppData.GetTransactionCode();// "TRA04052024CDM";
var storeAccountNumber = 686868686688;
var currentTime = DateTime.Now;
var printDocument = new PrintDocument();
+122 -27
View File
@@ -41,6 +41,7 @@ using Button = System.Windows.Controls.Button;
using UserControl = System.Windows.Controls.UserControl;
using Application = System.Windows.Application;
using Control = System.Windows.Controls.Control;
using static Azure.Core.HttpHeader;
namespace SafeBagDE70
@@ -94,10 +95,13 @@ namespace SafeBagDE70
try
{
lblName.Content= "Vietinbank " + Environment.MachineName;
string? transactionCode = null;
if (AppData.IsAuthenticated)
{
transactionCode = AppData.GetTransactionCode();
lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
lblTransactionCode.Content = $"Mã GD: {AppData.CurrentCustomerAccount.TransactionCode}";
lblTransactionCode.Content = $"Mã GD: {transactionCode}";
}
cCmdRsp = new CCmdRsp(serialPortDE70);
AppData.cCmdRsp = cCmdRsp;
@@ -120,10 +124,20 @@ namespace SafeBagDE70
StopTimers();
ShowError(state.CDMStatus);
}
AppData.GetCassetteData();
var data= AppData.GetCassetteData();
if (transactionCode != null)
{
AppData.DeviceStatus.Description = $"[CASSETTE]" + AppData.GetNotesString(data);
APIModels.SendEvent(AppData.DeviceStatus);
}
}
catch (Exception ex)
{
AppData.DeviceStatus.CDMStatus = (int)CDMStatusCode.DISCONNECT_SERIALPORT;
APIModels.SendEvent(AppData.DeviceStatus);
Log.Fatal(ex, "LỖI CỔNG KẾT NỐI");
ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
}
@@ -332,7 +346,8 @@ namespace SafeBagDE70
//lvCountItems[0].Quantity = "10";
}
int prevPrinterStatus = -1;
int prevSensorStatus = -1;
private void SensorTimer_Tick(object? sender, EventArgs e)
{
sensorTimer.IsEnabled = false;
@@ -344,22 +359,27 @@ namespace SafeBagDE70
{
var status = printerManager.GetStatus();
var strPrinterMessage = "";
if(status.StsNOPAPER)
{
AppData.DeviceStatus.PrinterStatus = (int)PrinterStatusCode.PAPEROUT;
StopTimers();
ShowError("MÁY IN HẾT GIẤY! ĐỀ NGHỊ THAY GIẤY");
strPrinterMessage = "MÁY IN HẾT GIẤY! ĐỀ NGHỊ THAY GIẤY";
ShowError(strPrinterMessage);
}
else if(status.StsNEARENDPAP)
{
strPrinterMessage = "MÁY IN GẦN HẾT GIẤY";
AppData.DeviceStatus.PrinterStatus = (int)PrinterStatusCode.NEARPAPEROUT;
}
if(AppData.DeviceStatus.PrinterStatus!= prevPrinterStatus)
{
AppData.DeviceStatus.Description = strPrinterMessage;
APIModels.SendEvent(AppData.DeviceStatus);
prevPrinterStatus = AppData.DeviceStatus.PrinterStatus;
}
AppData.DeviceStatus.Description = AppData.CDMSTATE.CDMStatus;
AppData.DeviceStatus.DeviceTime = DateTime.Now;
APIModels.SendHealthCheck(AppData.DeviceStatus);
}
@@ -403,21 +423,29 @@ namespace SafeBagDE70
else
gridMain.IsEnabled = true;
}
string strSensorMessage = "";
switch (state)
{
case 0:
lblStatus.Content = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: ĐÓNG";
strSensorMessage = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: ĐÓNG";
break;
case 1:
lblStatus.Content = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: MỞ";
strSensorMessage = "NGĂN KÉT: ĐÓNG, NGĂN TÚI: MỞ";
break;
case 2:
lblStatus.Content = "NGĂN KÉT: MỞ, NGĂN TÚI: ĐÓNG";
strSensorMessage = "NGĂN KÉT: MỞ, NGĂN TÚI: ĐÓNG";
break;
case 3:
lblStatus.Content = "NGĂN KÉT: MỞ, NGĂN TÚI: MỞ";
strSensorMessage = "NGĂN KÉT: MỞ, NGĂN TÚI: MỞ";
break;
}
lblStatus.Content = strSensorMessage;
if (state!=prevSensorStatus)
{
AppData.DeviceStatus.Description=strSensorMessage;
APIModels.SendEvent(AppData.DeviceStatus);
prevSensorStatus = state;
}
if (state > 0)
{
if (!bIsMaintain)
@@ -425,7 +453,6 @@ namespace SafeBagDE70
bIsMaintain = true;
DoMaintaince();
}
// TransitionToState("Maintainance");
}
else
@@ -587,6 +614,30 @@ namespace SafeBagDE70
{
return JsonConvert.SerializeObject(lvCountItems);
}
private string GetQuantityFromSessions(List<CountSession> countSessions,bool? btoreFlag=null)
{
var quantFromSession = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//500.000->500
foreach (var session in countSessions)
{
if(btoreFlag == null)
{
for (int i = 0; i < 10; i++)
quantFromSession[i] += session.QuantityDenomi[i];
}
else if ((session.IsStored == btoreFlag))
{
for (int i = 0; i < 10; i++)
quantFromSession[i] += session.QuantityDenomi[i];
}
}
string str = "";
for (int i = 0; i < quantFromSession.Length; i++)
{
str += quantFromSession[i] + ",";
}
str = str.Trim(',');
return str;
}
private bool DoCountStart()
{
@@ -614,12 +665,24 @@ namespace SafeBagDE70
taskCounting = Task.Run(() =>
{
var str = "BEFORE COUNT";
str+="\r\nSTORED: "+ GetQuantityFromSessions(sessions,true);
str += "\r\nSTACKER: " + GetQuantityFromSessions(sessions, false);
AppData.DeviceStatus.Description = str;
APIModels.SendEvent(AppData.DeviceStatus);
Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
bIsCounted = false;
AutoSerialGet();
bIsCounted = true;
Log.Information("After AutoCount: " + GetShortInforFromCountItems());
str = "AFTER COUNT";
str+= "\r\nSTORED: " + GetQuantityFromSessions(sessions, true);
str += "\r\nSTACKER: " + GetQuantityFromSessions(sessions, false);
AppData.DeviceStatus.Description = str;
APIModels.SendEvent(AppData.DeviceStatus);
});
@@ -754,6 +817,12 @@ namespace SafeBagDE70
string currentMethod = MethodBase.GetCurrentMethod().Name;
try
{
var str = "BEFORE CHECK";
str += "\r\nSTORED: " + GetQuantityFromSessions(sessions, true);
str += "\r\nSTACKER: " + GetQuantityFromSessions(sessions, false);
AppData.DeviceStatus.Description = str;
APIModels.SendEvent(AppData.DeviceStatus);
Log.Information("Before Check: "+GetShortInforFromCountItems());
serialPortDE70.DiscardInBuffer();
serialPortDE70.DiscardOutBuffer();
@@ -768,6 +837,12 @@ namespace SafeBagDE70
Log.Information("After Check: "+GetShortInforFromCountItems());
str = "AFTER CHECK";
str += "\r\nSTORED: " + GetQuantityFromSessions(sessions, true);
str += "\r\nSTACKER: " + GetQuantityFromSessions(sessions, false);
AppData.DeviceStatus.Description = str;
APIModels.SendEvent(AppData.DeviceStatus);
}
catch (Exception ex)
{
@@ -835,11 +910,23 @@ namespace SafeBagDE70
//Debug.WriteLine(quantityStored);
var previousCassetData = AppData.GetCassetteData();
if(CheckPreStoreValid(previousCassetData, AppData.MaxNotes, sessions))
var str = "BEFORE STORE [CASSETTE]" + AppData.GetNotesString(previousCassetData);
str += "\r\nSTORED: " + GetQuantityFromSessions(sessions, true);
str += "\r\nSTACKER: " + GetQuantityFromSessions(sessions, false);
AppData.DeviceStatus.Description = str;
APIModels.SendEvent(AppData.DeviceStatus);
if (CheckPreStoreValid(previousCassetData, AppData.MaxNotes, sessions))
{
cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
bSuccess = WaitUntilCountReady(10);
var newCasstData = AppData.GetCassetteData();
AppData.DeviceStatus.Description = "AFTER STORE [CASSETTE]" + AppData.GetNotesString(newCasstData);
APIModels.SendEvent(AppData.DeviceStatus);
bool bValid = CheckStoreValid(previousCassetData, newCasstData, sessions);
if (bValid)
{
@@ -859,16 +946,15 @@ namespace SafeBagDE70
}
else
{
string str = "PHIÊN GIAO DỊCH KHÔNG HỢP LỆ (SỐ TIỀN GIAO DỊCH KHÔNG KHỚP), VUI LÒNG BÁO CÁO LẠI CHI NHÁNH";
str = "PHIÊN GIAO DỊCH KHÔNG HỢP LỆ (SỐ TIỀN GIAO DỊCH KHÔNG KHỚP), VUI LÒNG BÁO CÁO LẠI CHI NHÁNH";
Log.Information(str);
ShowError(str);
}
Thread.Sleep(1000);
}
else
{
string str = "KÉT ĐÃ ĐẦY ĐỀ NGHỊ LẤY LẠI TIỀN VÀ KẾT THÚC GIAO DỊCH, VUI LÒNG BÁO CÁO LẠI CHI NHÁNH";
str = "KÉT ĐÃ ĐẦY ĐỀ NGHỊ LẤY LẠI TIỀN VÀ KẾT THÚC GIAO DỊCH, VUI LÒNG BÁO CÁO LẠI CHI NHÁNH";
Log.Information(str);
DoCheck();
EndSession(COUNTINGSTATE.FULLIFSTORE,str);
@@ -911,6 +997,10 @@ namespace SafeBagDE70
if (cCmdRsp.recv_dat.dat[0]!=0x40)
{
bSuccess = false;
var state = GetCDMState();
AppData.DeviceStatus.Description = "START_ERROR:" + state.GetFullStatus();
APIModels.SendEvent(AppData.DeviceStatus);
}
}
catch (Exception ex)
@@ -997,11 +1087,14 @@ namespace SafeBagDE70
Log.Information(currentMethod);
serialPortDE70.DiscardInBuffer();
serialPortDE70.DiscardOutBuffer();
if (double.Parse(totalValue) > 0)
{
var data2Send = new CountingData2Send
{
TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
TransactionCode = AppData.GetTransactionCode(),
Sessions = sessions,
MachineId = Environment.MachineName,
UserId = AppData.CurrentCustomerAccount.CustomerId,
@@ -1027,7 +1120,7 @@ namespace SafeBagDE70
+ $"SỐ TIỀN: {totalValue} VND\r\n";
if (AppData.CurrentCustomerAccount != null)
{
var strTransactionCode = AppData.CurrentCustomerAccount.TransactionCode;
var strTransactionCode = AppData.GetTransactionCode();
strNotify = "MÃ GD: "+strTransactionCode + "\r\n" + strNotify;
}
@@ -1048,7 +1141,7 @@ namespace SafeBagDE70
var strNotify = "";
if (AppData.CurrentCustomerAccount != null)
{
var strTransactionCode = AppData.CurrentCustomerAccount.TransactionCode;
var strTransactionCode = AppData.GetTransactionCode();
strNotify = "MÃ GD: "+strTransactionCode + "\r\n" + strNotify;
}
@@ -1067,6 +1160,8 @@ namespace SafeBagDE70
{
mainWindow.ShowWelcomeScreen();
}
if (AppData.CurrentCustomerAccount != null)
AppData.CurrentCustomerAccount.TransactionCode = "";
//SendData2Server
}
catch (Exception ex)
@@ -1193,7 +1288,7 @@ namespace SafeBagDE70
Log.Information("PrintReceipt");
var shopName = AppData.CurrentCustomerAccount.Name;
var shopCode = AppData.CurrentCustomerAccount.CustomerId;
var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
var tradingCode = AppData.GetTransactionCode();// "TRA04052024CDM";
var storeAccountNumber = AppData.CurrentCustomerAccount.CustomerId;
var currentTime = DateTime.Now;
var printDocument = new PrintDocument();
@@ -1324,17 +1419,15 @@ namespace SafeBagDE70
{
btnCountStart.IsEnabled = true;
ResetTimers();
Log.Information("1. Start completed");
}
else
{
btnStart.IsEnabled = true;
btnLogout.IsEnabled = true;
}
if (bResult)
Log.Information("1. Start completed");
else
Log.Information("1. Start failed");
Log.Information("1. Start failed");
}
}
else if(btn==btnCountStart)
{
@@ -1350,6 +1443,8 @@ namespace SafeBagDE70
{
string str = "ĐÃ XẢY RA LỖI TRONG QUÁ TRÌNH NỘP TIỀN";
Log.Information(str);
AppData.DeviceStatus.Description = "COUNT_ERROR:"+state.GetFullStatus();
APIModels.SendEvent(AppData.DeviceStatus);
DoCheck();
EndSession(COUNTINGSTATE.FULLIFSTORE, str);
}
+13
View File
@@ -13,6 +13,7 @@ namespace SafeBagDE70.Model
{
public DbSet<History> Histories { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<DeviceEvent> DeviceEvents { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=.\\SQLEXPRESS;Database=CDMLOCAL;User Id=cdm;Password=Navis@123;Trusted_Connection=False;TrustServerCertificate=True");
@@ -36,6 +37,18 @@ namespace SafeBagDE70.Model
public string Status { get; set; }
}
public class DeviceEvent
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Data { get; set; }
public bool? IsSent { get; set; }
public DateTime? SyncTime { get; set; }
public DateTime? DeviceTime { get; set; }
}
public class Customer
{
public int Id { get; set; }
+2 -3
View File
@@ -69,8 +69,7 @@ namespace SafeBagDE70
{
AppData.IsAuthenticated=true;
AppData.CurrentCustomerAccount=cca;
AppData.GetNewTransactionCode();
AppData.GetNewTransactionCode();
AppData.CreateNewTransactionCode();
((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
//DialogResult = true;
//this.Close();
@@ -208,7 +207,7 @@ namespace SafeBagDE70
cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
AppData.IsAuthenticated = true;
AppData.CurrentCustomerAccount = cca;
AppData.GetNewTransactionCode();
AppData.CreateNewTransactionCode();
((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
}
else