diff --git a/.svn/entries b/.svn/entries
new file mode 100644
index 0000000..48082f7
--- /dev/null
+++ b/.svn/entries
@@ -0,0 +1 @@
+12
diff --git a/.svn/format b/.svn/format
new file mode 100644
index 0000000..48082f7
--- /dev/null
+++ b/.svn/format
@@ -0,0 +1 @@
+12
diff --git a/.svn/pristine/00/00ca05828582eb28a3f5e26fd02c533c49e9b831.svn-base b/.svn/pristine/00/00ca05828582eb28a3f5e26fd02c533c49e9b831.svn-base
new file mode 100644
index 0000000..4ed0a9c
--- /dev/null
+++ b/.svn/pristine/00/00ca05828582eb28a3f5e26fd02c533c49e9b831.svn-base
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/01/012d27f712c523f4a8304159764ebcdfdbe5680f.svn-base b/.svn/pristine/01/012d27f712c523f4a8304159764ebcdfdbe5680f.svn-base
new file mode 100644
index 0000000..3db7982
--- /dev/null
+++ b/.svn/pristine/01/012d27f712c523f4a8304159764ebcdfdbe5680f.svn-base
@@ -0,0 +1,1357 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.StateMachine;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
+using System.Runtime.Intrinsics.Arm;
+using SafeBagDE70.Services;
+using System.Windows.Forms;
+using Button = System.Windows.Controls.Button;
+using UserControl = System.Windows.Controls.UserControl;
+using Application = System.Windows.Application;
+using Control = System.Windows.Controls.Control;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositSMUCv2 : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer sensorTimer;
+ DispatcherTimer? warningTimer = null;
+ DispatcherTimer? endsessionTimer = null;
+ DispatcherTimer? backToWelcomeTimer = null;
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int countSensorTimer = 0;
+ private PrinterManager printerManager = new PrinterManager();
+
+ private NotesInSession notesInSession= new NotesInSession();
+ //DispatcherTimer?
+ private volatile bool bIsCounted = false;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+ bool bOpenPort = true;
+ bool bIsMaintain = false;
+ MainWindow mainWindow = null;
+ Thread thread = null;
+ Task taskCounting = null;
+ public DepositSMUCv2()
+ {
+ InitializeComponent();
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ mainWindow=((MainWindow)Application.Current.MainWindow);
+ InitTransaction();
+ StopTimers();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ lblName.Content= "Vietinbank " + Environment.MachineName;
+ if (AppData.IsAuthenticated)
+ {
+ 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}";
+ }
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+
+ notesInSession = new NotesInSession();
+ spNotesInSession.DataContext = notesInSession;
+
+ AppData.IsInTransaction = true;
+ ResetButtons();
+ btnStart.IsEnabled = true;
+ ResetTimers();
+ var state=GetCDMState();
+ if(state.GetSR2()==0x1C)
+ {
+ StopTimers();
+ ShowError(state.CDMStatus);
+ }
+ GetCassetteData();
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if(bOpenPort)
+ {
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+ if(bOpenPort)
+ {
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ }
+
+ private void InitTimers()
+ {
+ warningTimer = new DispatcherTimer(); // 30 seconds
+ warningTimer.Interval = new TimeSpan(0, 0, 30);
+ warningTimer.Tick += WarningTimer_Tick; ;
+ warningTimer.Stop();
+
+ endsessionTimer = new DispatcherTimer(); // 60 seconds
+ endsessionTimer.Interval = new TimeSpan(0, 0, 60);
+ endsessionTimer.Tick += EndSessionTimer_Tick;
+ endsessionTimer.Stop();
+
+ backToWelcomeTimer = new DispatcherTimer();
+ backToWelcomeTimer.Interval = new TimeSpan(0, 0, 15);
+ backToWelcomeTimer.Tick += BackToWelcomeTimer_Tick;
+ backToWelcomeTimer.Stop();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void StopWelcomeTimer()
+ {
+ if(backToWelcomeTimer != null)
+ backToWelcomeTimer.Stop();
+ }
+ public void StartWelcomeTimer()
+ {
+ if (backToWelcomeTimer != null)
+ backToWelcomeTimer.Start();
+ }
+ private void BackToWelcomeTimer_Tick(object? sender, EventArgs e)
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ private void EndSessionTimer_Tick(object? sender, EventArgs e)
+ {
+ Log.Information("7. Timout starting");
+ mainWindow.ShowEndSessionScreen();
+ StopTimers();
+ DoStoreStart();
+ bIsCounted = false;
+ DoCountStart();
+ Task.Run(() =>
+ {
+ taskCounting.Wait();
+ DoStoreStart();
+ Dispatcher.Invoke(() =>
+ {
+ EndSession(1);
+ });
+ Log.Information("7. Timout completed");
+ });
+
+
+ }
+
+ private void BackToWelcomeScreen()
+ {
+ StopTimers();
+
+ var cdmState = GetCDMState();
+ var state = GetCDMState();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInHopper > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ }
+
+ private void WarningTimer_Tick(object? sender, EventArgs e)
+ {
+
+ mainWindow.ShowTimeoutScreen();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ if (warningTimer != null)
+ {
+ warningTimer.Tick -=WarningTimer_Tick;
+ warningTimer.Stop();
+ }
+ if (endsessionTimer != null)
+ {
+ endsessionTimer.Tick -=EndSessionTimer_Tick;
+ endsessionTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+
+
+ public void InitLvCountItems()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ sensorTimer.IsEnabled = false;
+ try
+ {
+ countSensorTimer++;
+
+ if (countSensorTimer % 10 == 0)
+ {
+
+ var status = printerManager.GetStatus();
+
+ if(status.StsNOPAPER)
+ {
+ AppData.DeviceStatus.PrinterStatus = (int)PrinterStatusCode.PAPEROUT;
+ StopTimers();
+ ShowError("MÁY IN HẾT GIẤY! ĐỀ NGHỊ THAY GIẤY");
+ }
+ else if(status.StsNEARENDPAP)
+ {
+ AppData.DeviceStatus.PrinterStatus = (int)PrinterStatusCode.NEARPAPEROUT;
+ }
+
+ AppData.DeviceStatus.Description = AppData.CDMSTATE.CDMStatus;
+ AppData.DeviceStatus.DeviceTime = DateTime.Now;
+
+
+ APIModels.SendHealthCheck(AppData.DeviceStatus);
+ }
+
+ sensorTimer.IsEnabled = false;
+ GetSensorValue();
+ sensorTimer.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Sensor_Timer");
+ }
+ sensorTimer.IsEnabled = true;
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ if (!bIsMaintain)
+ {
+ bIsMaintain = true;
+ DoMaintaince();
+ }
+
+ // TransitionToState("Maintainance");
+ }
+ else
+ {
+ if(bIsMaintain)
+ {
+ bIsMaintain = false;
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ }
+
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"GetSensorValue");
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+ private void DoMaintaince()
+ {
+ StopTimers();
+ mainWindow.ShowMaintainanceScreen();
+ }
+
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet()
+ {
+ try
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ var countSession = new CountSession();
+ countSession.IsStored = false;
+ sessions.Add(countSession);
+ while (true)
+ {
+ AppData.WDTCount = 0;
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ AppData.WDTCount = 0;
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: countSession.TempNotes[0]++;break;
+ case 0x02:
+ //TempNote[1] ++;
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}");
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: countSession.QuantityDenomi[0]++; break;
+ case 0x01: countSession.QuantityDenomi[1]++; break;
+ case 0x02: countSession.QuantityDenomi[2]++; break;
+ case 0x03: countSession.QuantityDenomi[3]++; break;
+ case 0x04: countSession.QuantityDenomi[4]++; break;
+ case 0x05: countSession.QuantityDenomi[5]++; break;
+ case 0x06: countSession.QuantityDenomi[6]++; break;
+ case 0x07: countSession.QuantityDenomi[7]++; break;
+ case 0x08: countSession.QuantityDenomi[8]++; break;
+ case 0x09: countSession.QuantityDenomi[9]++; break;
+
+ }
+ break;
+ case 0x03: countSession.TempNotes[2]++; break;
+ case 0x0b: countSession.TempNotes[3]++; break;
+ case 0x0c: countSession.TempNotes[4]++; break;
+ }
+ UpdateListViewCountItems();
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0)
+ {
+ sessions.Remove(countSession);
+ }
+ }catch(Exception ex)
+ {
+ Log.Fatal(ex, "AutoSerialGet");
+ }
+
+ //Log.Information(JsonConvert.SerializeObject(sessions));
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private bool DoCountStart()
+ {
+ bool bSuccess = true;
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ if(bOpenPort)
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+ }
+
+
+ taskCounting = Task.Run(() =>
+ {
+ Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ bIsCounted = false;
+ AutoSerialGet();
+ bIsCounted = true;
+ Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+ });
+
+
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex,currentMethod);
+ }
+ return bSuccess;
+ }
+ private byte[] GetCassetteData()
+ {
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_READ_CASSETTE);
+ var data=cCmdRsp.recv_dat.dat;
+
+ StringBuilder str=new StringBuilder();
+ var recv_dat = cCmdRsp.recv_dat;
+
+ AppData.DeviceStatus.Notes = GetNotes(recv_dat.dat);
+ str.Append("DATA:");
+ for (int i = 0; i < recv_dat.leng - 1; i++)
+ {
+ var dat = string.Format("{0:X2} ", recv_dat.dat[i]);
+ str.Append(dat);
+ }
+ Log.Information("[CASSETTE]" + str.ToString());
+ return (byte[])data.Clone();
+ }
+ private int GetNotes(byte[] cassetData)
+ {
+ int notes = 0;
+ int offset = 14;
+ for (int i = 0; i < 10; i++)
+ {
+ notes += cassetData[2 * i + offset] * 256 + cassetData[2 * i + 1 + offset];
+ }
+ return notes;
+ }
+ private bool CheckStoreValid(byte[] previousCassetData, byte[] newCassetData,List countSessions)
+ {
+ var quantFromSession = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//500.000->500
+ foreach (var session in countSessions) {
+ if ((session.IsStored==false))
+ {
+ for (int i = 0; i < 10; i++)
+ quantFromSession[i] += session.QuantityDenomi[i];
+ }
+ }
+ var nPreviousCassetData = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ var nNewCassetData = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ int offset = 14;
+ bool bValid = true;
+ for(int i=0;i<10;i++)
+ {
+ nPreviousCassetData[i] = previousCassetData[2*i + offset] * 256 + previousCassetData[2*i + 1 + offset];
+ nNewCassetData[i]=newCassetData[2*i + offset] * 256 + newCassetData[2*i+1+ offset];
+ if (nNewCassetData[i] - nPreviousCassetData[i]!=quantFromSession[i])
+ {
+ bValid = false;
+ break;
+ }
+ }
+ return bValid;
+ }
+
+ private void UpdateListViewCountItems()
+ {
+ Dispatcher.Invoke(DispatcherPriority.Normal, () =>
+ {
+ double sum = 0;
+ if (sessions != null && sessions.Count > 0)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ int quantity = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ quantity += sessions[j].QuantityDenomi[9 - i];
+
+ }
+ lvCountItems[i].Quantity = quantity.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ //Update Notes In Sesion
+ notesInSession.GenuineNotes = 0;
+ notesInSession.RejectNotes = 0;
+
+ for (int j = 0; j < sessions.Count; j++)
+ {
+ if (sessions[j].IsStored == false)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ notesInSession.GenuineNotes += sessions[j].QuantityDenomi[9 - i];
+ }
+ notesInSession.RejectNotes += sessions[j].TempNotes.Sum();
+ }
+ }
+ }
+ else
+ {
+ for (int i = 0; i < 11; i++)
+ {
+ lvCountItems[i].Quantity = "0";
+ lvCountItems[i].Value = "0";
+ }
+ }
+ });
+
+ }
+
+ public bool DoCheck()
+ {
+ bool bSuccess = true;
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ sessions.RemoveAll(item=>!item.IsStored);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ UpdateListViewCountItems();
+
+
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilCountReady(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while (true)
+ {
+ state = GetCDMState();
+ if (state.GetSR2() == 0x07)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilEnscrowEmpty(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while(true)
+ {
+ state = GetCDMState();
+ if (state.IsNotesInEscrow == 0)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool DoStoreStart()
+ {
+
+ bool bSuccess = true;
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ //sessions.Add(new CountSession());
+
+ // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+
+ //Debug.WriteLine(quantityStored);
+
+ var previousCassetData = GetCassetteData();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ bSuccess=WaitUntilCountReady(10);
+ var newCasstData = GetCassetteData();
+ bool bValid= CheckStoreValid(previousCassetData,newCasstData,sessions);
+ if(bValid)
+ {
+ if (bSuccess)
+ {
+ foreach (var item in sessions)
+ {
+ item.IsStored = true;
+ }
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored " + GetShortInforFromCountItems());
+ }
+ else
+ {
+ Log.Error("Store FAIL " + GetShortInforFromCountItems());
+ }
+ }
+ 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";
+ Log.Information(str);
+ ShowError(str);
+ }
+
+ Thread.Sleep(2000);
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoStart()
+ {
+ bool bSuccess = true;
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ if (cCmdRsp.recv_dat.dat[0]!=0x40)
+ {
+ bSuccess = false;
+ }
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoEnd()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ StopTimers();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ var lstEnabledControls = new List { btnEnd, btnCountStart };
+ if (state.IsNotesInEscrow > 0)
+ {
+ btnEnd.IsEnabled = true;
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true,true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ btnEnd.IsEnabled = true;
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true, true);
+ }
+ else if(state.IsNotesInHopper>0)
+ {
+ btnEnd.IsEnabled = true;
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", true, true);
+ }
+ else
+ {
+ bSuccess = true;
+ AppData.WDTCount = 0;
+ EndSession();
+
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+
+ ResetTimers();
+ }
+ return bSuccess;
+ }
+ private bool DoLogout()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ InitLvCountItems();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else //if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess = true;
+ ResetSessions();
+ BackToWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession(int _CountingState=0)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ //Remove sessions with store flag is false
+
+ sessions.RemoveAll(item => !item.IsStored);
+ UpdateListViewCountItems();
+
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ if (double.Parse(totalValue) > 0)
+ {
+ var data2Send = new CountingData2Send
+ {
+ TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
+ Sessions = sessions,
+ MachineId = Environment.MachineName,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ GenuineNotes = quantityStored,
+ CountingState= _CountingState
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if (double.Parse(totalValue) > 0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN NỘP TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+ mainWindow.ShowInformationScreen(strNotify, false, false);
+ ResetSessions();
+ StartWelcomeTimer();
+
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ //SendData2Server
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, currentMethod);
+ }
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Save2DB Exception");
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Update2DB Exception");
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ mainWindow.ShowErrorScreen(strError);
+ }
+
+ public CDMSTATE GetCDMState()
+ {
+ return AppData.GetCDMState();
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ ResetSessions();
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal(ex,"InitSession");
+ }
+ return false;
+ }
+
+ private void ResetSessions()
+ {
+ InitLvCountItems();
+ sessions.Clear();
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ }
+
+ private void PrintReceipt()
+ {
+ Log.Information("PrintReceipt");
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ public void ResetTimers()
+ {
+ StopTimers();
+ StartTimers();
+ }
+
+ public void StartTimers()
+ {
+ if(warningTimer!=null && endsessionTimer != null)
+ {
+ warningTimer.Start();
+ endsessionTimer.Start();
+ }
+
+ }
+
+ public void StopTimers()
+ {
+ if(warningTimer!=null && endsessionTimer !=null)
+ {
+ warningTimer.Stop();
+ endsessionTimer.Stop();
+ }
+
+ }
+
+ private void ResetButtons()
+ {
+ btnStart.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ btnLogout.IsEnabled = false;
+ }
+
+
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ SoundManager.StartButtonPressSound();
+ // Console.Beep(800, 200);
+ StopTimers();
+ bool bResult = false;
+ if (btn==btnStart)
+ {
+ Log.Information("Deposit starting");
+ Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ Log.Information("1. Start starting");
+ ResetButtons();
+ bResult = DoStart();
+ if (bResult)
+ {
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ }
+ else
+ {
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+ }
+ if (bResult)
+ Log.Information("1. Start completed");
+ else
+ Log.Information("1. Start failed");
+
+ }
+ else if(btn==btnCountStart)
+ {
+
+ Log.Information("2. Count starting");
+ ResetButtons();
+ bResult = DoCountStart();
+ Task.Run(() =>
+ {
+ taskCounting.Wait();
+ Dispatcher.Invoke(() =>
+ {
+ btnCountStart.IsEnabled = true;
+ btnCheck.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ ResetTimers();
+ Log.Information("2. Count completed");
+ });
+ });
+
+
+ }
+ else if(btn==btnCheck)
+ {
+ Log.Information($"3. Check starting");
+ ResetButtons();
+ bResult = DoCheck();
+ btnCountStart.IsEnabled= true;
+ ResetTimers();
+ if (bResult)
+ Log.Information($"3. Check completed");
+ else
+ Log.Information($"3. Check failed");
+ }
+ else if (btn == btnStoreStart)
+ {
+ //TransitionToState("Store");
+ Log.Information("4. Store starting");
+ ResetButtons();
+ bResult = DoStoreStart();
+ btnEnd.IsEnabled= true;
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("4. Store completed");
+ else
+ Log.Information("4. Store failed");
+ }
+ else if (btn == btnEnd)
+ {
+ // TransitionToState("End");
+ Log.Information("5. End starting");
+ ResetButtons();
+ bResult = DoEnd();
+ //btnStart.IsEnabled = true;
+ //btnLogout.IsEnabled = true;
+ //ResetTimers();
+ if (bResult)
+ Log.Information("5. End Completed");
+ else
+ Log.Information("5. End failed");
+ }
+ else if (btn == btnLogout)
+ {
+ Log.Information("6. Exit starting");
+ bResult = DoLogout();
+ if (bResult)
+ Log.Information("6. Exit Completed");
+ else
+ Log.Information("6. Exit failed");
+ }
+ }
+ }
+}
+
diff --git a/.svn/pristine/01/016232993cd3b1cbb037185c868e15aa9996813b.svn-base b/.svn/pristine/01/016232993cd3b1cbb037185c868e15aa9996813b.svn-base
new file mode 100644
index 0000000..5303b8d
--- /dev/null
+++ b/.svn/pristine/01/016232993cd3b1cbb037185c868e15aa9996813b.svn-base
@@ -0,0 +1,20 @@
+using Microsoft.Extensions.Configuration;
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+using System.Windows;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for App.xaml
+ ///
+ public partial class App : Application
+ {
+
+ }
+}
diff --git a/.svn/pristine/05/051bf169707f7befae027e153dadad082679dd03.svn-base b/.svn/pristine/05/051bf169707f7befae027e153dadad082679dd03.svn-base
new file mode 100644
index 0000000..60da5ed
--- /dev/null
+++ b/.svn/pristine/05/051bf169707f7befae027e153dadad082679dd03.svn-base
@@ -0,0 +1,189 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using SafeBagDE70.Services;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ private WelcomeUC _welcomeUC;
+ private DepositSMUCv2 _depositUC;
+ private CollectionUC _collectionUC;
+ private InformationUC _informationUC;
+ private ErrorUC _errorUC;
+ private UserControl _currentUC;
+ private UserControl _prevUC;
+ private TimeoutUC _timeoutUC;
+ private MaintainanceUC _maintainanceUC;
+ private EndSessionUC _endSessionUC;
+ private object objLock = new object();
+ public MainWindow()
+ {
+ InitializeComponent();
+ Loaded += MainWindow_Loaded;
+ }
+
+ private void MainWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.Init();
+ if (_welcomeUC == null) _welcomeUC = new WelcomeUC();
+ if (_collectionUC == null) _collectionUC = new CollectionUC();
+ if (_informationUC == null) _informationUC = new InformationUC();
+ if (_errorUC == null) _errorUC = new ErrorUC();
+ if (_depositUC == null) _depositUC = new DepositSMUCv2();
+ if (_timeoutUC == null) _timeoutUC = new TimeoutUC();
+ if (_maintainanceUC == null) _maintainanceUC = new MaintainanceUC();
+ if (_endSessionUC == null) _endSessionUC = new EndSessionUC();
+
+
+ gridMain.Children.Add(_welcomeUC);
+ gridMain.Children.Add(_depositUC);
+ gridMain.Children.Add(_collectionUC);
+ gridMain.Children.Add(_informationUC);
+ gridMain.Children.Add(_errorUC);
+ gridMain.Children.Add(_timeoutUC);
+ gridMain.Children.Add(_maintainanceUC);
+ gridMain.Children.Add(_endSessionUC);
+
+ ShowWelcomeScreen();
+ //ShowDepositScreen();
+ }
+
+ public void HideAll()
+ {
+ lock(objLock)
+ {
+ foreach (var item in gridMain.Children)
+ {
+ if (item != null)
+ (item as UserControl).Visibility = Visibility.Hidden;
+ }
+ //_collectionUC.Visibility = Visibility.Hidden;
+ //_informationUC.Visibility = Visibility.Hidden;
+ //_errorUC.Visibility = Visibility.Hidden;
+ //_depositUC.Visibility = Visibility.Hidden;
+ //_welcomeUC.Visibility = Visibility.Hidden;
+ //_maintainanceUC.Visibility=Visibility.Hidden;
+ //_endSessionUC.Visibility = Visibility.Hidden;
+ SoundManager.StopWarningSound();
+ }
+
+ }
+ public void ShowEndSessionScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _endSessionUC.Visibility= Visibility.Visible;
+ }
+ public void ShowInformationScreen(string strInfor,bool bContinue=false,bool bPlaySound=true,List lstControls=null)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _informationUC;
+ HideAll();
+ _informationUC.Visibility = Visibility.Visible;
+ _informationUC.ShowInfor(strInfor, bContinue, bPlaySound,lstControls);
+ }
+ public void ShowErrorScreen(string strError)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _errorUC;
+ HideAll();
+ _errorUC.Visibility = Visibility.Visible;
+ _errorUC.ShowInfor(strError);
+ }
+ public void ShowWelcomeScreen()
+ {
+ _depositUC.StopTimers();
+ _depositUC.StopWelcomeTimer();
+ _prevUC = _currentUC;
+ _currentUC = _welcomeUC;
+ HideAll();
+ _welcomeUC.Init();
+
+ _welcomeUC.Visibility = Visibility.Visible;
+ }
+ public void ShowDepositScreen(bool bInit=true)
+ {
+ _depositUC.ResetTimers();
+ _prevUC = _currentUC;
+ _currentUC = _depositUC;
+ HideAll();
+ _depositUC.Visibility = Visibility.Visible;
+ if(bInit)
+ {
+ _depositUC.EndTransaction();
+ _depositUC.InitTransaction();
+ }
+ }
+
+ public void ShowCollectionScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _collectionUC;
+ HideAll();
+ _collectionUC.Init();
+ _collectionUC.Visibility = Visibility.Visible;
+ }
+ public bool IsMaintainanceScreen()
+ {
+ return _currentUC == _maintainanceUC;
+ }
+ public DepositSMUCv2 GetDepositScreen()
+ {
+ return _depositUC;
+ }
+ public void ShowMaintainanceScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _maintainanceUC.Visibility = Visibility.Visible;
+ }
+ public void ShowTimeoutScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _timeoutUC.Visibility = Visibility.Visible;
+ }
+ public void StopTimers()
+ {
+ _depositUC.StopTimers();
+ }
+
+ public bool DoCheck()
+ {
+ return _depositUC.DoCheck();
+ }
+ public void ResetTimers()
+ {
+ _depositUC.ResetTimers();
+ }
+ public void BackScreen()
+ {
+ HideAll();
+ _prevUC.Visibility = Visibility.Visible;
+ _currentUC = _prevUC;
+ }
+ }
+}
diff --git a/.svn/pristine/05/0544c1c531cfeb0e85da5d25c02fd7df8910b301.svn-base b/.svn/pristine/05/0544c1c531cfeb0e85da5d25c02fd7df8910b301.svn-base
new file mode 100644
index 0000000..1f8400f
Binary files /dev/null and b/.svn/pristine/05/0544c1c531cfeb0e85da5d25c02fd7df8910b301.svn-base differ
diff --git a/.svn/pristine/05/05ed1e63594d8f555955e90a3b4c1661f7f03e44.svn-base b/.svn/pristine/05/05ed1e63594d8f555955e90a3b4c1661f7f03e44.svn-base
new file mode 100644
index 0000000..b4ced11
--- /dev/null
+++ b/.svn/pristine/05/05ed1e63594d8f555955e90a3b4c1661f7f03e44.svn-base
@@ -0,0 +1,211 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeUC : UserControl
+ {
+ public string? QRCodeContent = null;
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeUC()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ }
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+ string pin = PinCodeBox.Password;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Password.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Help clicked.");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ {
+ UseShellExecute = true
+ };
+ Process.Start(onScreenKeyboardProcess);
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ QRCodeContent = HexStringToString(rawDataHex);
+ this.Dispatcher.Invoke(() =>
+ {
+
+
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (QRCodeContent != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/06/0647e0e9088716b5fe424ece48a99f9eeb32b877.svn-base b/.svn/pristine/06/0647e0e9088716b5fe424ece48a99f9eeb32b877.svn-base
new file mode 100644
index 0000000..576d5f4
--- /dev/null
+++ b/.svn/pristine/06/0647e0e9088716b5fe424ece48a99f9eeb32b877.svn-base
@@ -0,0 +1,826 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositUC : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+
+ public DepositUC()
+ {
+ InitializeComponent();
+
+ }
+
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ InitTransaction();
+
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+ }
+
+ // LoginUsingQRCode();
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+
+ serialPortDE70.PortName = "COM4";
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+
+ serialPortSensor.PortName = "COM3";
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+
+ //Subscrible to the DataReveied event
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+
+ bInitialized = InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ timer.IsEnabled = false;
+ GetSensorValue();
+ if (AppData.IsInTransaction)
+ {
+ if (AppData.WDTCount == 30)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen();
+ }
+ else if (AppData.WDTCount == 60)
+ {
+ //Nhận tiền và Kết thúc
+ StoreStart();
+ EndSession();
+
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ }
+ AppData.WDTCount++;
+ }
+ else
+ {
+ AppData.WDTCount = 0;
+ }
+ timer.IsEnabled = true;
+ }
+ catch (Exception)
+ {
+
+ }
+
+
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException("GetSensorValue", ex.ToString());
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ CountStart();
+ AppData.WDTCount = 0;
+ }
+
+ private void CountStart()
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ AppData.LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ AppData.LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ AppData.WDTCount = 0;
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ StoreStart();
+ AppData.WDTCount = 0;
+ }
+
+ private void StoreStart()
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ AppData.LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+ AppData.IsInTransaction= true;
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ AppData.LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ AppData.WDTCount = 0;
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ EndSession();
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+ try
+ {
+ AppData.LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+ var str = JsonConvert.SerializeObject(data2Send);
+
+ APIModels.SendCountingData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify);
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull = 0;
+ int IsNotesInEscrow = 0;
+ IsCassetteFull = data[17] & 0x08;
+ IsNotesInEscrow = data[4] & 0x01;
+
+ if (IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ AppData.LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60));
+ e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90));
+ e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120));
+ e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150));
+ e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180));
+ e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210));
+ e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270));
+ e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ }
+}
+
diff --git a/.svn/pristine/07/07ab6085662974f90c92b73a87ae3017a976c2f5.svn-base b/.svn/pristine/07/07ab6085662974f90c92b73a87ae3017a976c2f5.svn-base
new file mode 100644
index 0000000..4465696
--- /dev/null
+++ b/.svn/pristine/07/07ab6085662974f90c92b73a87ae3017a976c2f5.svn-base
@@ -0,0 +1,49 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static void Init()
+ {
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ }
+ public static void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public static void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ }
+}
diff --git a/.svn/pristine/07/07baf310051dfa00e370cecf40ec2e397214b8fa.svn-base b/.svn/pristine/07/07baf310051dfa00e370cecf40ec2e397214b8fa.svn-base
new file mode 100644
index 0000000..c29ae7c
--- /dev/null
+++ b/.svn/pristine/07/07baf310051dfa00e370cecf40ec2e397214b8fa.svn-base
@@ -0,0 +1,211 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/09/0931f02ff2cc8831765b74d58eb233384080725e.svn-base b/.svn/pristine/09/0931f02ff2cc8831765b74d58eb233384080725e.svn-base
new file mode 100644
index 0000000..f3895c9
--- /dev/null
+++ b/.svn/pristine/09/0931f02ff2cc8831765b74d58eb233384080725e.svn-base
@@ -0,0 +1,30 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/09/094290c5b870779c80ec54113de27b686d0b8c07.svn-base b/.svn/pristine/09/094290c5b870779c80ec54113de27b686d0b8c07.svn-base
new file mode 100644
index 0000000..2171ba3
--- /dev/null
+++ b/.svn/pristine/09/094290c5b870779c80ec54113de27b686d0b8c07.svn-base
@@ -0,0 +1,53 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for AdminSettingsUC.xaml
+ ///
+ public partial class AdminMainUC : UserControl
+ {
+ public AdminMainUC()
+ {
+ InitializeComponent();
+ }
+
+ private void LogoutButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void UserManagementButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void DashboardButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void SettingsButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void ReportsButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+ }
+}
diff --git a/.svn/pristine/09/0954c7d3ff41de7ad1116431e3943852bdb28477.svn-base b/.svn/pristine/09/0954c7d3ff41de7ad1116431e3943852bdb28477.svn-base
new file mode 100644
index 0000000..661e364
--- /dev/null
+++ b/.svn/pristine/09/0954c7d3ff41de7ad1116431e3943852bdb28477.svn-base
@@ -0,0 +1,52 @@
+
+
+
+
+
+ Designer
+
+
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/0a/0abee0b6725c838726c2da43603ac11479cb1695.svn-base b/.svn/pristine/0a/0abee0b6725c838726c2da43603ac11479cb1695.svn-base
new file mode 100644
index 0000000..5b88252
--- /dev/null
+++ b/.svn/pristine/0a/0abee0b6725c838726c2da43603ac11479cb1695.svn-base
@@ -0,0 +1,766 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+ public class CountSession
+ {
+ public int[] QuantityDenomi { get; set; }
+ public int[] SumDenomi { get; set; }
+
+ }
+
+ public class CountingData2Send
+ {
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ }
+
+ public partial class MainUserWindow : HandyControl.Controls.Window
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+ public MainUserWindow()
+ {
+ //Need to update: auto detect COM Port
+ try
+ {
+ InitializeComponent();
+ //string queuePath = ConfigurationManager.AppSettings["SensorPort"].ToString();
+ AppData.Init();
+ //this.gridMain.IsEnabled = false;
+ LoginUsingQRCode();
+
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+
+ serialPortDE70.PortName = "COM4";
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+
+ serialPortSensor.PortName = "COM3";
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+
+ //Subscrible to the DataReveied event
+
+ serialPortDE70.Open();
+ serialPortSensor.Open();
+
+ bInitialized= InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //10 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ //MessageBox.Show("Cổng đang mở, kiểm tra lại cổng kết nối");
+ //this.Close();
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ lvCountItems.Clear();
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+ int state = 0;
+ if (serialPortSensor.IsOpen==true)
+ {
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1]-48;
+ if(bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "Két: đóng, Túi: đóng";
+ break;
+ case 1:
+ lblStatus.Content = "Két: đóng, Túi: đã bị lấy ra";
+ break;
+ case 2:
+ lblStatus.Content = "Két: mở, Túi: đóng";
+ break;
+ case 3:
+ lblStatus.Content = "Két: mở, Túi: đã bị lấy ra";
+ break;
+ }
+ break;
+ }
+ }
+
+ }
+
+ timer.IsEnabled = true;
+ }
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+ var str = JsonConvert.SerializeObject(data2Send);
+
+ APIModels.SendCountingData(data2Send);
+ //Reset all and ready to next session
+
+ if(printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ LoginUsingQRCode();
+
+ }
+ private void ShowError(string strError)
+ {
+ gridMain.IsEnabled = false;
+
+ panelError.Visibility = Visibility.Visible;
+ lblError.Text = strError;
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull=data[17] & 0x08;
+ if(IsCassetteFull != 0)
+ {
+ ShowError("TÚI ĐẦY, ĐỀ NGHỊ LẤY TÚI TRƯỚC KHI TIẾP TỤC THAO TÁC");
+ btnCollect2.Visibility=Visibility.Visible;
+ return false;
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60));
+ e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90));
+ e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120));
+ e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150));
+ e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180));
+ e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210));
+ e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270));
+ e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ public void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ private void LoginUsingQRCode()
+ {
+ var wnd = new WelcomeWindow();
+ wnd.ShowDialog();
+
+ lblUser.Content = "";
+ //var wnd = new QRCodeZebraWindow();
+ //wnd.ShowDialog();
+ if (wnd.DialogResult == true)
+ {
+ var strQR = wnd.QRCodeContent;
+ var strPincode = wnd.PinCode;
+ if (AppData.customerAccounts!=null)
+ {
+ CustomerAccount? cca = null;
+ if(strQR!=null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == strQR).FirstOrDefault();
+ }
+ else if(strPincode!=null)
+ {
+ strPincode = strPincode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.CurrentCustomerAccount = cca;
+ lblUser.Content = $"Xin chào khách hàng: {cca.Name} (Gian hàng {cca.CustomerId})";
+ }
+ else
+ {
+ MessageBox.Show("QRCode không đúng, vui lòng thử lại");
+ LoginUsingQRCode();
+ }
+ }
+ }
+ }
+
+ private void btnLoginByPINCode_Click(object sender, RoutedEventArgs e)
+ {
+ var wnd = new PinCodeWindow();
+ wnd.ShowDialog();
+ }
+
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ MessageBox.Show(cCmdRsp.GetSendDat(false));
+ Thread.Sleep(5000);
+ cCmdRsp.GetLockParam().mode = currentMode;
+ cCmdRsp.SendLock();
+
+ InitSession();
+ }
+ }
+}
+
diff --git a/.svn/pristine/0b/0b8721a6a37692cc3e1feca4e6e2671296c688ab.svn-base b/.svn/pristine/0b/0b8721a6a37692cc3e1feca4e6e2671296c688ab.svn-base
new file mode 100644
index 0000000..e4566a9
--- /dev/null
+++ b/.svn/pristine/0b/0b8721a6a37692cc3e1feca4e6e2671296c688ab.svn-base
@@ -0,0 +1,77 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class CollectionUC : UserControl
+ {
+ public CollectionUC()
+ {
+ InitializeComponent();
+ }
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ if(AppData.cCmdRsp!=null)
+ {
+ CCmdRsp cCmdRsp = AppData.cCmdRsp;
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ lblStatus.Text="TRẠNG THÁI: KHỞI TẠO BỘ ĐẾM THÀNH CÔNG";
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ }
+ }
+
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if(AppData.cCmdRsp!=null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ }
+ }
+
+}
diff --git a/.svn/pristine/0b/0b92102365245cca6c79ca53f4c87fc58858c093.svn-base b/.svn/pristine/0b/0b92102365245cca6c79ca53f4c87fc58858c093.svn-base
new file mode 100644
index 0000000..63cee56
--- /dev/null
+++ b/.svn/pristine/0b/0b92102365245cca6c79ca53f4c87fc58858c093.svn-base
@@ -0,0 +1,24 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/0c/0c61b7d74f9781eafb66b336fa071eb41638ca3f.svn-base b/.svn/pristine/0c/0c61b7d74f9781eafb66b336fa071eb41638ca3f.svn-base
new file mode 100644
index 0000000..891e52d
--- /dev/null
+++ b/.svn/pristine/0c/0c61b7d74f9781eafb66b336fa071eb41638ca3f.svn-base
@@ -0,0 +1,146 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+
+ //public class CountSession
+ //{
+ // public int[] QuantityDenomi { get; set; }
+ // public int[] SumDenomi { get; set; }
+
+ //}
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ private WelcomeUC _welcomeUC;
+ private DepositUC _depositUC;
+ private CollectionUC _collectionUC;
+ private InformationUC _informationUC;
+ private ErrorUC _errorUC;
+ private UserControl _currentUC;
+ private UserControl _prevUC;
+ private TimeoutUC _timeoutUC;
+ private object objLock = new object();
+ public MainWindow()
+ {
+ InitializeComponent();
+ Loaded += MainWindow_Loaded;
+
+ }
+
+ private void MainWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.Init();
+ if (_welcomeUC == null) _welcomeUC = new WelcomeUC();
+ if (_collectionUC == null) _collectionUC = new CollectionUC();
+ if (_informationUC == null) _informationUC = new InformationUC();
+ if (_errorUC == null) _errorUC = new ErrorUC();
+ if (_depositUC == null) _depositUC = new DepositUC();
+ if (_timeoutUC == null) _timeoutUC = new TimeoutUC();
+
+ gridMain.Children.Add(_welcomeUC);
+ gridMain.Children.Add(_depositUC);
+ gridMain.Children.Add(_collectionUC);
+ gridMain.Children.Add(_informationUC);
+ gridMain.Children.Add(_errorUC);
+ gridMain.Children.Add(_timeoutUC);
+
+ ShowWelcomeScreen();
+ }
+
+ public void HideAll()
+ {
+ lock(objLock)
+ {
+ foreach (var item in gridMain.Children)
+ {
+ if (item != null)
+ (item as UserControl).Visibility = Visibility.Hidden;
+ }
+ _collectionUC.Visibility = Visibility.Hidden;
+ _informationUC.Visibility = Visibility.Hidden;
+ _errorUC.Visibility = Visibility.Hidden;
+ _depositUC.Visibility = Visibility.Hidden;
+ _welcomeUC.Visibility = Visibility.Hidden;
+ }
+
+ }
+ public void ShowInformationScreen(string strInfor)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _informationUC;
+ HideAll();
+ _informationUC.Visibility = Visibility.Visible;
+ _informationUC.ShowInfor(strInfor);
+
+ }
+ public void ShowErrorScreen(string strError)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _errorUC;
+ HideAll();
+ _errorUC.Visibility = Visibility.Visible;
+ _errorUC.ShowInfor(strError);
+ }
+ public void ShowWelcomeScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _welcomeUC;
+ HideAll();
+ _welcomeUC.Init();
+ _welcomeUC.Visibility = Visibility.Visible;
+ }
+ public void ShowDepositScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _depositUC;
+ HideAll();
+ _depositUC.Visibility = Visibility.Visible;
+ _depositUC.EndTransaction();
+ _depositUC.InitTransaction();
+ }
+ public void ShowCollectionScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _collectionUC;
+ HideAll();
+ _collectionUC.Init();
+ _collectionUC.Visibility = Visibility.Visible;
+ }
+ public void ShowTimeoutScreen()
+ {
+ _prevUC = _currentUC;
+
+ HideAll();
+ _timeoutUC.Visibility = Visibility.Visible;
+ }
+ public void BackScreen()
+ {
+ HideAll();
+ _prevUC.Visibility = Visibility.Visible;
+ _currentUC = _prevUC;
+ }
+ }
+}
diff --git a/.svn/pristine/0d/0de0466d6a4859e53b6c986bcb0a14668286da79.svn-base b/.svn/pristine/0d/0de0466d6a4859e53b6c986bcb0a14668286da79.svn-base
new file mode 100644
index 0000000..abbb21a
Binary files /dev/null and b/.svn/pristine/0d/0de0466d6a4859e53b6c986bcb0a14668286da79.svn-base differ
diff --git a/.svn/pristine/0e/0e720757044d667726d738a1aba0655861f760bd.svn-base b/.svn/pristine/0e/0e720757044d667726d738a1aba0655861f760bd.svn-base
new file mode 100644
index 0000000..69bea40
--- /dev/null
+++ b/.svn/pristine/0e/0e720757044d667726d738a1aba0655861f760bd.svn-base
@@ -0,0 +1,11 @@
+
+
+
+ Library
+ net8.0-windows
+ enable
+ enable
+ true
+
+
+
diff --git a/.svn/pristine/0f/0f584142418a8387ba9718a52fae2126376565fa.svn-base b/.svn/pristine/0f/0f584142418a8387ba9718a52fae2126376565fa.svn-base
new file mode 100644
index 0000000..6d4561c
Binary files /dev/null and b/.svn/pristine/0f/0f584142418a8387ba9718a52fae2126376565fa.svn-base differ
diff --git a/.svn/pristine/10/107bde8f2556dcc7d406f3f9e75005692bdfb7ac.svn-base b/.svn/pristine/10/107bde8f2556dcc7d406f3f9e75005692bdfb7ac.svn-base
new file mode 100644
index 0000000..47dfdd8
Binary files /dev/null and b/.svn/pristine/10/107bde8f2556dcc7d406f3f9e75005692bdfb7ac.svn-base differ
diff --git a/.svn/pristine/11/113d2bad539eaf5aed237605814b4145b67c3a87.svn-base b/.svn/pristine/11/113d2bad539eaf5aed237605814b4145b67c3a87.svn-base
new file mode 100644
index 0000000..c259a08
--- /dev/null
+++ b/.svn/pristine/11/113d2bad539eaf5aed237605814b4145b67c3a87.svn-base
@@ -0,0 +1,62 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+namespace XamlGeneratedNamespace {
+
+
+ ///
+ /// GeneratedInternalTypeHelper
+ ///
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ public sealed class GeneratedInternalTypeHelper : System.Windows.Markup.InternalTypeHelper {
+
+ ///
+ /// CreateInstance
+ ///
+ protected override object CreateInstance(System.Type type, System.Globalization.CultureInfo culture) {
+ return System.Activator.CreateInstance(type, ((System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)
+ | (System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.CreateInstance)), null, null, culture);
+ }
+
+ ///
+ /// GetPropertyValue
+ ///
+ protected override object GetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, System.Globalization.CultureInfo culture) {
+ return propertyInfo.GetValue(target, System.Reflection.BindingFlags.Default, null, null, culture);
+ }
+
+ ///
+ /// SetPropertyValue
+ ///
+ protected override void SetPropertyValue(System.Reflection.PropertyInfo propertyInfo, object target, object value, System.Globalization.CultureInfo culture) {
+ propertyInfo.SetValue(target, value, System.Reflection.BindingFlags.Default, null, null, culture);
+ }
+
+ ///
+ /// CreateDelegate
+ ///
+ protected override System.Delegate CreateDelegate(System.Type delegateType, object target, string handler) {
+ return ((System.Delegate)(target.GetType().InvokeMember("_CreateDelegate", (System.Reflection.BindingFlags.InvokeMethod
+ | (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)), null, target, new object[] {
+ delegateType,
+ handler}, null)));
+ }
+
+ ///
+ /// AddEventHandler
+ ///
+ protected override void AddEventHandler(System.Reflection.EventInfo eventInfo, object target, System.Delegate handler) {
+ eventInfo.AddEventHandler(target, handler);
+ }
+ }
+}
+
diff --git a/.svn/pristine/12/1249514b52a2eea3535917b527dfbd894cd15f43.svn-base b/.svn/pristine/12/1249514b52a2eea3535917b527dfbd894cd15f43.svn-base
new file mode 100644
index 0000000..ab93f7b
--- /dev/null
+++ b/.svn/pristine/12/1249514b52a2eea3535917b527dfbd894cd15f43.svn-base
@@ -0,0 +1,25 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+using System;
+using System.Reflection;
+
+[assembly: System.Reflection.AssemblyCompanyAttribute("VirtualKeyboard")]
+[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
+[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
+[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
+[assembly: System.Reflection.AssemblyProductAttribute("VirtualKeyboard")]
+[assembly: System.Reflection.AssemblyTitleAttribute("VirtualKeyboard")]
+[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
+[assembly: System.Runtime.Versioning.TargetPlatformAttribute("Windows7.0")]
+[assembly: System.Runtime.Versioning.SupportedOSPlatformAttribute("Windows7.0")]
+
+// Generated by the MSBuild WriteCodeFragment class.
+
diff --git a/.svn/pristine/13/131229a0c6c56a833d3b118ce00d02563b715dd4.svn-base b/.svn/pristine/13/131229a0c6c56a833d3b118ce00d02563b715dd4.svn-base
new file mode 100644
index 0000000..cc51e5c
--- /dev/null
+++ b/.svn/pristine/13/131229a0c6c56a833d3b118ce00d02563b715dd4.svn-base
@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for AdminSettingsUC.xaml
+ ///
+ public partial class AdminSettingsUC : UserControl
+ {
+ public AdminSettingsUC()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/.svn/pristine/13/135c54ce53178d9672c42a99644a1d29591f3f67.svn-base b/.svn/pristine/13/135c54ce53178d9672c42a99644a1d29591f3f67.svn-base
new file mode 100644
index 0000000..81a0229
--- /dev/null
+++ b/.svn/pristine/13/135c54ce53178d9672c42a99644a1d29591f3f67.svn-base
@@ -0,0 +1,16 @@
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/16/164eb638e3b187ca9fa44ae5855c722c7e31a5a2.svn-base b/.svn/pristine/16/164eb638e3b187ca9fa44ae5855c722c7e31a5a2.svn-base
new file mode 100644
index 0000000..e86eda1
--- /dev/null
+++ b/.svn/pristine/16/164eb638e3b187ca9fa44ae5855c722c7e31a5a2.svn-base
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/18/1867122055affebb2a592f610637758a527d8227.svn-base b/.svn/pristine/18/1867122055affebb2a592f610637758a527d8227.svn-base
new file mode 100644
index 0000000..eabff50
--- /dev/null
+++ b/.svn/pristine/18/1867122055affebb2a592f610637758a527d8227.svn-base
@@ -0,0 +1,79 @@
+{
+ "format": 1,
+ "restore": {
+ "C:\\Users\\DELL Precision 7530\\Desktop\\Test\\VK\\VK\\WPFKeyboard\\VirtualKeyboard\\VirtualKeyboard.csproj": {}
+ },
+ "projects": {
+ "C:\\Users\\DELL Precision 7530\\Desktop\\Test\\VK\\VK\\WPFKeyboard\\VirtualKeyboard\\VirtualKeyboard.csproj": {
+ "version": "1.0.0",
+ "restore": {
+ "projectUniqueName": "C:\\Users\\DELL Precision 7530\\Desktop\\Test\\VK\\VK\\WPFKeyboard\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "projectName": "VirtualKeyboard",
+ "projectPath": "C:\\Users\\DELL Precision 7530\\Desktop\\Test\\VK\\VK\\WPFKeyboard\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "packagesPath": "C:\\Users\\DELL Precision 7530\\.nuget\\packages\\",
+ "outputPath": "C:\\Users\\DELL Precision 7530\\Desktop\\Test\\VK\\VK\\WPFKeyboard\\VirtualKeyboard\\obj\\",
+ "projectStyle": "PackageReference",
+ "fallbackFolders": [
+ "C:\\Program Files (x86)\\DevExpress 20.2\\Components\\Offline Packages",
+ "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages",
+ "C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder"
+ ],
+ "configFilePaths": [
+ "C:\\Users\\DELL Precision 7530\\AppData\\Roaming\\NuGet\\NuGet.Config",
+ "C:\\Program Files (x86)\\NuGet\\Config\\DevExpress 20.2.config",
+ "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.FallbackLocation.config",
+ "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
+ ],
+ "originalTargetFrameworks": [
+ "net8.0-windows"
+ ],
+ "sources": {
+ "C:\\Program Files (x86)\\DevExpress 20.2\\Components\\System\\Components\\Packages": {},
+ "C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
+ "https://api.nuget.org/v3/index.json": {}
+ },
+ "frameworks": {
+ "net8.0-windows7.0": {
+ "targetAlias": "net8.0-windows",
+ "projectReferences": {}
+ }
+ },
+ "warningProperties": {
+ "warnAsError": [
+ "NU1605"
+ ]
+ },
+ "restoreAuditProperties": {
+ "enableAudit": "true",
+ "auditLevel": "low",
+ "auditMode": "direct"
+ }
+ },
+ "frameworks": {
+ "net8.0-windows7.0": {
+ "targetAlias": "net8.0-windows",
+ "imports": [
+ "net461",
+ "net462",
+ "net47",
+ "net471",
+ "net472",
+ "net48",
+ "net481"
+ ],
+ "assetTargetFallback": true,
+ "warn": true,
+ "frameworkReferences": {
+ "Microsoft.NETCore.App": {
+ "privateAssets": "all"
+ },
+ "Microsoft.WindowsDesktop.App.WPF": {
+ "privateAssets": "none"
+ }
+ },
+ "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\8.0.200/PortableRuntimeIdentifierGraph.json"
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/19/194825ccb42e4318cb1576978070ee71671e5e67.svn-base b/.svn/pristine/19/194825ccb42e4318cb1576978070ee71671e5e67.svn-base
new file mode 100644
index 0000000..472cffc
--- /dev/null
+++ b/.svn/pristine/19/194825ccb42e4318cb1576978070ee71671e5e67.svn-base
@@ -0,0 +1,45 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class TimeoutUC : UserControl
+ {
+ public TimeoutUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor)
+ {
+ lblInfor.Text = strInfor;
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ AppData.WDTCount = 0;
+ ((MainWindow)Application.Current.MainWindow).BackScreen();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ }
+ }
+}
diff --git a/.svn/pristine/1a/1a952fdc7e6ef952bd6f7ffe7ab99a296a959270.svn-base b/.svn/pristine/1a/1a952fdc7e6ef952bd6f7ffe7ab99a296a959270.svn-base
new file mode 100644
index 0000000..c3ec7db
--- /dev/null
+++ b/.svn/pristine/1a/1a952fdc7e6ef952bd6f7ffe7ab99a296a959270.svn-base
@@ -0,0 +1,1296 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.StateMachine;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
+using System.Runtime.Intrinsics.Arm;
+using SafeBagDE70.Services;
+using System.Windows.Forms;
+using Button = System.Windows.Controls.Button;
+using UserControl = System.Windows.Controls.UserControl;
+using Application = System.Windows.Application;
+using Control = System.Windows.Controls.Control;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositSMUCv2 : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer sensorTimer;
+ DispatcherTimer? warningTimer = null;
+ DispatcherTimer? endsessionTimer = null;
+ DispatcherTimer? backToWelcomeTimer = null;
+ //DispatcherTimer?
+ private volatile bool bIsCounted = false;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+ bool bOpenPort = true;
+ bool bIsMaintain = false;
+ MainWindow mainWindow = null;
+ Thread thread = null;
+ Task taskCounting = null;
+ public DepositSMUCv2()
+ {
+ InitializeComponent();
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ mainWindow=((MainWindow)Application.Current.MainWindow);
+ InitTransaction();
+ StopTimers();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ lblName.Content= "Vietinbank " + Environment.MachineName;
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+
+ }
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+ AppData.IsInTransaction = true;
+ ResetButtons();
+ btnStart.IsEnabled = true;
+ ResetTimers();
+ var state=GetCDMState();
+ if(state.SR2==0x1C)
+ {
+ StopTimers();
+ ShowError(state.CDMStatus);
+ }
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if(bOpenPort)
+ {
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+ if(bOpenPort)
+ {
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ }
+
+ private void InitTimers()
+ {
+ warningTimer = new DispatcherTimer(); // 30 seconds
+ warningTimer.Interval = new TimeSpan(0, 0, 15);
+ warningTimer.Tick += WarningTimer_Tick; ;
+ warningTimer.Stop();
+
+ endsessionTimer = new DispatcherTimer(); // 60 seconds
+ endsessionTimer.Interval = new TimeSpan(0, 0, 30);
+ endsessionTimer.Tick += EndSessionTimer_Tick;
+ endsessionTimer.Stop();
+
+ backToWelcomeTimer = new DispatcherTimer();
+ backToWelcomeTimer.Interval = new TimeSpan(0, 0, 15);
+ backToWelcomeTimer.Tick += BackToWelcomeTimer_Tick;
+ backToWelcomeTimer.Stop();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void StopWelcomeTimer()
+ {
+ if(backToWelcomeTimer != null)
+ backToWelcomeTimer.Stop();
+ }
+ public void StartWelcomeTimer()
+ {
+ if (backToWelcomeTimer != null)
+ backToWelcomeTimer.Start();
+ }
+ private void BackToWelcomeTimer_Tick(object? sender, EventArgs e)
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ private void EndSessionTimer_Tick(object? sender, EventArgs e)
+ {
+ Log.Information("7. Timout starting");
+ mainWindow.ShowEndSessionScreen();
+ StopTimers();
+ DoStoreStart();
+ bIsCounted = false;
+ CountStart(false);
+ Task.Run(() =>
+ {
+ taskCounting.Wait();
+ DoStoreStart();
+ Dispatcher.Invoke(() =>
+ {
+ EndSession();
+ });
+ Log.Information("7. Timout completed");
+ });
+
+ }
+
+ private void BackToWelcomeScreen()
+ {
+ StopTimers();
+
+ var cdmState = GetCDMState();
+ var state = GetCDMState();
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInHopper > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ }
+
+ private void WarningTimer_Tick(object? sender, EventArgs e)
+ {
+
+ mainWindow.ShowTimeoutScreen();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ if (warningTimer != null)
+ {
+ warningTimer.Tick -=WarningTimer_Tick;
+ warningTimer.Stop();
+ }
+ if (endsessionTimer != null)
+ {
+ endsessionTimer.Tick -=EndSessionTimer_Tick;
+ endsessionTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+
+
+ public void InitLvCountItems()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ // public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ // public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ // public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+ public int countSensorTimer = 0;
+ //PrinterManager printerManager = new PrinterManager();
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ countSensorTimer++;
+
+ if (countSensorTimer % 10 == 0)
+ {
+ APIModels.SendHealthCheck();
+ }
+
+ sensorTimer.IsEnabled = false;
+ GetSensorValue();
+ sensorTimer.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Sensor_Timer");
+ }
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ if (!bIsMaintain)
+ {
+ bIsMaintain = true;
+ DoMaintaince();
+ }
+
+ // TransitionToState("Maintainance");
+ }
+ else
+ {
+ if(bIsMaintain)
+ {
+ bIsMaintain = false;
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ }
+
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"GetSensorValue");
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+ private void DoMaintaince()
+ {
+ StopTimers();
+ ((MainWindow)Application.Current.MainWindow).ShowMaintainanceScreen();
+ }
+
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet()
+ {
+ try
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ var countSession = new CountSession();
+ countSession.IsStored = false;
+ sessions.Add(countSession);
+ while (true)
+ {
+ AppData.WDTCount = 0;
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ AppData.WDTCount = 0;
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: countSession.TempNotes[0]++;break;
+ case 0x02:
+ //TempNote[1] ++;
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}");
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: countSession.QuantityDenomi[0]++; break;
+ case 0x01: countSession.QuantityDenomi[1]++; break;
+ case 0x02: countSession.QuantityDenomi[2]++; break;
+ case 0x03: countSession.QuantityDenomi[3]++; break;
+ case 0x04: countSession.QuantityDenomi[4]++; break;
+ case 0x05: countSession.QuantityDenomi[5]++; break;
+ case 0x06: countSession.QuantityDenomi[6]++; break;
+ case 0x07: countSession.QuantityDenomi[7]++; break;
+ case 0x08: countSession.QuantityDenomi[8]++; break;
+ case 0x09: countSession.QuantityDenomi[9]++; break;
+
+ }
+ break;
+ case 0x03: countSession.TempNotes[2]++; break;
+ case 0x0b: countSession.TempNotes[3]++; break;
+ case 0x0c: countSession.TempNotes[4]++; break;
+ }
+ UpdateListViewCountItems();
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0)
+ {
+ sessions.Remove(countSession);
+ }
+ }catch(Exception ex)
+ {
+ Log.Fatal(ex, "AutoSerialGet");
+ }
+
+ //Log.Information(JsonConvert.SerializeObject(sessions));
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private bool CountStart(bool bInitState=true)
+ {
+ bool bSuccess = true;
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ if(bOpenPort)
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+ }
+
+
+ //SR3 = 0x43 : Stacker full
+
+ //thread = new Thread(new ThreadStart(() =>
+ //{
+ // Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ // bIsCounted = false;
+ // AutoSerialGet();
+ // bIsCounted = true;
+ // Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+
+ // if (bInitState)
+ // {
+ // Dispatcher.Invoke(() =>
+ // {
+ // btnCountStart.IsEnabled = true;
+ // btnCheck.IsEnabled = true;
+ // btnStoreStart.IsEnabled = true;
+ // ResetTimers();
+ // Log.Information("2. Count completed");
+ // });
+ // }
+ //}));
+ //thread.Start();
+ taskCounting = Task.Run(() =>
+ {
+ Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ bIsCounted = false;
+ AutoSerialGet();
+ bIsCounted = true;
+ Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+
+ if (bInitState)
+ {
+ Dispatcher.Invoke(() =>
+ {
+ btnCountStart.IsEnabled = true;
+ btnCheck.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ ResetTimers();
+ Log.Information("2. Count completed");
+ });
+ }
+ });
+
+
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex,currentMethod);
+ }
+ return bSuccess;
+ }
+
+ private void UpdateListViewCountItems()
+ {
+ Dispatcher.Invoke(DispatcherPriority.Normal, () =>
+ {
+ double sum = 0;
+ if (sessions != null && sessions.Count > 0)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ int quantity = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ quantity += sessions[j].QuantityDenomi[9 - i];
+
+ }
+ lvCountItems[i].Quantity = quantity.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+ }
+ else
+ {
+ for (int i = 0; i < 11; i++)
+ {
+ lvCountItems[i].Quantity = "0";
+ lvCountItems[i].Value = "0";
+ }
+ }
+ });
+
+ }
+
+ private bool DoCheck()
+ {
+ bool bSuccess = true;
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ sessions.RemoveAll(item=>!item.IsStored);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ UpdateListViewCountItems();
+
+
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilCountReady(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while (true)
+ {
+ state = GetCDMState();
+ if (state.SR2 == 0x07)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilEnscrowEmpty(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while(true)
+ {
+ state = GetCDMState();
+ if (state.IsNotesInEscrow == 0)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool DoStoreStart()
+ {
+ bool bSuccess = true;
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ //sessions.Add(new CountSession());
+
+ // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+
+ //Debug.WriteLine(quantityStored);
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ bSuccess=WaitUntilCountReady(10);
+ if (bSuccess)
+ {
+ foreach (var item in sessions)
+ {
+ item.IsStored = true;
+ }
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored " + GetShortInforFromCountItems());
+ }
+ else
+ {
+ Log.Error("Store FAIL " + GetShortInforFromCountItems());
+ }
+ Thread.Sleep(2000);
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoStart()
+ {
+ bool bSuccess = true;
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ if (cCmdRsp.recv_dat.dat[0]!=0x40)
+ {
+ bSuccess = false;
+ }
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoEnd()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ StopTimers();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ var lstEnabledControls = new List { btnEnd, btnCountStart };
+ if (state.IsNotesInEscrow > 0)
+ {
+ btnEnd.IsEnabled = true;
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true,true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ btnEnd.IsEnabled = true;
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true, true);
+ }
+ else if(state.IsNotesInHopper>0)
+ {
+ btnEnd.IsEnabled = true;
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", true, true);
+ }
+ else
+ {
+ bSuccess = true;
+ AppData.WDTCount = 0;
+ EndSession();
+
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+
+ ResetTimers();
+ }
+ return bSuccess;
+ }
+ private bool DoLogout()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ InitLvCountItems();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else //if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess = true;
+ EndSession();
+ BackToWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ //Remove sessions with store flag is false
+
+ sessions.RemoveAll(item => !item.IsStored);
+ UpdateListViewCountItems();
+
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ if (double.Parse(totalValue) > 0)
+ {
+ var data2Send = new CountingData2Send
+ {
+ TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
+ Sessions = sessions,
+ MachineId = Environment.MachineName,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ //RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ //UnfitNotes = Notes[2],
+ //CounterfeitNotes = Notes[3],
+ // SuspendNotes = Notes[4]
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if (double.Parse(totalValue) > 0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+ mainWindow.ShowInformationScreen(strNotify, false, false);
+ ResetSessions();
+ StartWelcomeTimer();
+
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ //SendData2Server
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, currentMethod);
+ }
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Save2DB Exception");
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Update2DB Exception");
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+
+ private CDMSTATE GetCDMState()
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv=cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+
+ AppData.CDMSTATE.IsCassetteFull = data[17] & 0x08;
+ AppData.CDMSTATE.IsNotesInEscrow = data[4] & 0x01;
+ AppData.CDMSTATE.IsRejectPocketFull = data[3] & 0x40;
+ AppData.CDMSTATE.IsNotesInRejectPocket = data[3] & 0x10;
+ AppData.CDMSTATE.IsNotesInHopper = data[3] & 0x01;
+ AppData.CDMSTATE.SR1 = data[0];
+ AppData.CDMSTATE.SR2 = data[1];
+ AppData.CDMSTATE.SR3 = data[2];
+ return AppData.CDMSTATE;
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ ResetSessions();
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal(ex,"InitSession");
+ }
+ return false;
+ }
+
+ private void ResetSessions()
+ {
+ InitLvCountItems();
+ sessions.Clear();
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ }
+
+ private void PrintReceipt()
+ {
+ Log.Information("PrintReceipt");
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ public void ResetTimers()
+ {
+ StopTimers();
+ StartTimers();
+ }
+
+ public void StartTimers()
+ {
+ if(warningTimer!=null && endsessionTimer != null)
+ {
+ warningTimer.Start();
+ endsessionTimer.Start();
+ }
+
+ }
+
+ public void StopTimers()
+ {
+ if(warningTimer!=null && endsessionTimer !=null)
+ {
+ warningTimer.Stop();
+ endsessionTimer.Stop();
+ }
+
+ }
+
+ private void ResetButtons()
+ {
+ btnStart.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ btnLogout.IsEnabled = false;
+ }
+
+
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ SoundManager.StartButtonPressSound();
+ // Console.Beep(800, 200);
+ StopTimers();
+ bool bResult = false;
+ if (btn==btnStart)
+ {
+ Log.Information("Deposit starting");
+ Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ Log.Information("1. Start starting");
+ ResetButtons();
+ bResult = DoStart();
+ if (bResult)
+ {
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ }
+ else
+ {
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+ }
+ if (bResult)
+ Log.Information("1. Start completed");
+ else
+ Log.Information("1. Start failed");
+
+ }
+ else if(btn==btnCountStart)
+ {
+
+ Log.Information("2. Count starting");
+ ResetButtons();
+ bResult = CountStart();
+
+ // if (taskCounting != null) taskCounting.Wait();
+ //while (!bIsCounted) // chua thoat duoc loop
+ //{
+ // Thread.Sleep(100);
+ //}
+ //Do in counting thread
+
+ }
+ else if(btn==btnCheck)
+ {
+ Log.Information($"3. Check starting");
+ ResetButtons();
+ bResult = DoCheck();
+ btnCountStart.IsEnabled= true;
+ ResetTimers();
+ if (bResult)
+ Log.Information($"3. Check completed");
+ else
+ Log.Information($"3. Check failed");
+ }
+ else if (btn == btnStoreStart)
+ {
+ //TransitionToState("Store");
+ Log.Information("4. Store starting");
+ ResetButtons();
+ bResult = DoStoreStart();
+ btnEnd.IsEnabled= true;
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("4. Store completed");
+ else
+ Log.Information("4. Store failed");
+ }
+ else if (btn == btnEnd)
+ {
+ // TransitionToState("End");
+ Log.Information("5. End starting");
+ ResetButtons();
+ bResult = DoEnd();
+ //btnStart.IsEnabled = true;
+ //btnLogout.IsEnabled = true;
+ //ResetTimers();
+ if (bResult)
+ Log.Information("5. End Completed");
+ else
+ Log.Information("5. End failed");
+ }
+ else if (btn == btnLogout)
+ {
+ Log.Information("6. Exit starting");
+ bResult = DoLogout();
+ if (bResult)
+ Log.Information("6. Exit Completed");
+ else
+ Log.Information("6. Exit failed");
+ }
+ }
+
+
+ }
+}
+
diff --git a/.svn/pristine/1c/1c486fad38db1f1d677f3289b136d11f95352bb3.svn-base b/.svn/pristine/1c/1c486fad38db1f1d677f3289b136d11f95352bb3.svn-base
new file mode 100644
index 0000000..c7d5423
--- /dev/null
+++ b/.svn/pristine/1c/1c486fad38db1f1d677f3289b136d11f95352bb3.svn-base
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/1d/1dc85659112394da242522554e2516230483b308.svn-base b/.svn/pristine/1d/1dc85659112394da242522554e2516230483b308.svn-base
new file mode 100644
index 0000000..9959b0f
--- /dev/null
+++ b/.svn/pristine/1d/1dc85659112394da242522554e2516230483b308.svn-base
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/1f/1ff99b78af4a154666c81c52f6d46d121cc42112.svn-base b/.svn/pristine/1f/1ff99b78af4a154666c81c52f6d46d121cc42112.svn-base
new file mode 100644
index 0000000..df0eb75
--- /dev/null
+++ b/.svn/pristine/1f/1ff99b78af4a154666c81c52f6d46d121cc42112.svn-base
@@ -0,0 +1,39 @@
+
+
+
+
+ 50
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/21/2163b520b7b0fc921e463038ec3291b71e1fe45a.svn-base b/.svn/pristine/21/2163b520b7b0fc921e463038ec3291b71e1fe45a.svn-base
new file mode 100644
index 0000000..e2098ea
--- /dev/null
+++ b/.svn/pristine/21/2163b520b7b0fc921e463038ec3291b71e1fe45a.svn-base
@@ -0,0 +1,58 @@
+using DE70_CMDv2;
+using SafeBagDE70.Services;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class InformationUC : UserControl
+ {
+ private bool _bContinue = false;
+ private bool _bPlaySound = false;
+ public InformationUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor, bool bContinue = false, bool bPlaySound=true)
+ {
+ lblInfor.Text = strInfor;
+ _bContinue = bContinue;
+ _bPlaySound = bPlaySound;
+ if (_bPlaySound)
+ SoundManager.StartWarningSound();
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ if(_bContinue)
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen(false);
+ else
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+
+ SoundManager.StopWarningSound();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ SoundManager.StopWarningSound();
+ }
+ }
+}
diff --git a/.svn/pristine/22/22094a0d9ce70d942bc0d883adf51bec7cb6eb6b.svn-base b/.svn/pristine/22/22094a0d9ce70d942bc0d883adf51bec7cb6eb6b.svn-base
new file mode 100644
index 0000000..a82951b
--- /dev/null
+++ b/.svn/pristine/22/22094a0d9ce70d942bc0d883adf51bec7cb6eb6b.svn-base
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/23/230f34ab35921847ae60989b53fa6c7180c89c1b.svn-base b/.svn/pristine/23/230f34ab35921847ae60989b53fa6c7180c89c1b.svn-base
new file mode 100644
index 0000000..0eaa289
--- /dev/null
+++ b/.svn/pristine/23/230f34ab35921847ae60989b53fa6c7180c89c1b.svn-base
@@ -0,0 +1,113 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/23/235e93fb4b1743d0369be7b4e3d1bdfaa0e6b57b.svn-base b/.svn/pristine/23/235e93fb4b1743d0369be7b4e3d1bdfaa0e6b57b.svn-base
new file mode 100644
index 0000000..c7feedb
--- /dev/null
+++ b/.svn/pristine/23/235e93fb4b1743d0369be7b4e3d1bdfaa0e6b57b.svn-base
@@ -0,0 +1,32 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static void Init()
+ {
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ }
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ }
+}
diff --git a/.svn/pristine/23/2363e19962de569371d3efe1ee0bac9082c662b7.svn-base b/.svn/pristine/23/2363e19962de569371d3efe1ee0bac9082c662b7.svn-base
new file mode 100644
index 0000000..61fb2b6
--- /dev/null
+++ b/.svn/pristine/23/2363e19962de569371d3efe1ee0bac9082c662b7.svn-base
@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70.StateMachine
+{
+ public class Transition
+ {
+ public List From { get; set; }
+ public List To { get; set; }
+ public List Actions { get; set; }
+ public bool RequireAtLeastOneActionSuccess { get; set; }
+ }
+}
diff --git a/.svn/pristine/28/28cfbaf2667599eda36e61cd1a849b69dad0dd7a.svn-base b/.svn/pristine/28/28cfbaf2667599eda36e61cd1a849b69dad0dd7a.svn-base
new file mode 100644
index 0000000..21d8df4
--- /dev/null
+++ b/.svn/pristine/28/28cfbaf2667599eda36e61cd1a849b69dad0dd7a.svn-base
@@ -0,0 +1,70 @@
+using DE70_CMDv2;
+using SafeBagDE70.Services;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class InformationUC : UserControl
+ {
+ private bool _bContinue = false;
+ private bool _bPlaySound = false;
+ private List _controls = null;
+ public InformationUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor, bool bContinue = false, bool bPlaySound=true,List controls=null)
+ {
+ lblInfor.Text = strInfor;
+ _bContinue = bContinue;
+ _bPlaySound = bPlaySound;
+ _controls = controls;
+ if (_bPlaySound)
+ SoundManager.StartWarningSound();
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ if(_controls!=null)
+ {
+ foreach (var item in _controls)
+ {
+ item.IsEnabled = true;
+ }
+ }
+
+ if (_bContinue)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen(false);
+ ((MainWindow)Application.Current.MainWindow).ResetTimers();
+ }
+ else
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ SoundManager.StopWarningSound();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ SoundManager.StopWarningSound();
+ }
+ }
+}
diff --git a/.svn/pristine/29/295a558c21526e4684b6054182152cc2e984653c.svn-base b/.svn/pristine/29/295a558c21526e4684b6054182152cc2e984653c.svn-base
new file mode 100644
index 0000000..06277f0
--- /dev/null
+++ b/.svn/pristine/29/295a558c21526e4684b6054182152cc2e984653c.svn-base
@@ -0,0 +1,98 @@
+#pragma checksum "..\..\..\DefaultKeyboardHost.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8509DC7DAD84ED248634BE5108571E782945BD81"
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Controls.Ribbon;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Ink;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Media.Effects;
+using System.Windows.Media.Imaging;
+using System.Windows.Media.Media3D;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Windows.Shell;
+using VirtualKeyboard.Wpf;
+
+
+namespace VirtualKeyboard.Wpf {
+
+
+ internal partial class DefaultKeyboardHost : System.Windows.Window, System.Windows.Markup.IComponentConnector {
+
+
+ #line 19 "..\..\..\DefaultKeyboardHost.xaml"
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
+ internal System.Windows.Controls.ContentControl KeyboardValueContent;
+
+ #line default
+ #line hidden
+
+
+ #line 22 "..\..\..\DefaultKeyboardHost.xaml"
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
+ internal System.Windows.Controls.ContentControl KeyboardContent;
+
+ #line default
+ #line hidden
+
+ private bool _contentLoaded;
+
+ ///
+ /// InitializeComponent
+ ///
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ public void InitializeComponent() {
+ if (_contentLoaded) {
+ return;
+ }
+ _contentLoaded = true;
+ System.Uri resourceLocater = new System.Uri("/VirtualKeyboard;component/defaultkeyboardhost.xaml", System.UriKind.Relative);
+
+ #line 1 "..\..\..\DefaultKeyboardHost.xaml"
+ System.Windows.Application.LoadComponent(this, resourceLocater);
+
+ #line default
+ #line hidden
+ }
+
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
+ void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
+ switch (connectionId)
+ {
+ case 1:
+ this.KeyboardValueContent = ((System.Windows.Controls.ContentControl)(target));
+ return;
+ case 2:
+ this.KeyboardContent = ((System.Windows.Controls.ContentControl)(target));
+ return;
+ }
+ this._contentLoaded = true;
+ }
+ }
+}
+
diff --git a/.svn/pristine/29/29b4287da88c973c01665198ecfcd88fb066b882.svn-base b/.svn/pristine/29/29b4287da88c973c01665198ecfcd88fb066b882.svn-base
new file mode 100644
index 0000000..bf784ee
--- /dev/null
+++ b/.svn/pristine/29/29b4287da88c973c01665198ecfcd88fb066b882.svn-base
@@ -0,0 +1,211 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/2a/2a3e59c4f0df7d5d550b2247e23c50dd38a14374.svn-base b/.svn/pristine/2a/2a3e59c4f0df7d5d550b2247e23c50dd38a14374.svn-base
new file mode 100644
index 0000000..b420913
--- /dev/null
+++ b/.svn/pristine/2a/2a3e59c4f0df7d5d550b2247e23c50dd38a14374.svn-base
@@ -0,0 +1,102 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/2a/2a59fc499bed8850e8fc84d198653808f3f14213.svn-base b/.svn/pristine/2a/2a59fc499bed8850e8fc84d198653808f3f14213.svn-base
new file mode 100644
index 0000000..c297d18
--- /dev/null
+++ b/.svn/pristine/2a/2a59fc499bed8850e8fc84d198653808f3f14213.svn-base
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/2b/2bdbb1a5c8557e88ab21756b210ceb5a53e89337.svn-base b/.svn/pristine/2b/2bdbb1a5c8557e88ab21756b210ceb5a53e89337.svn-base
new file mode 100644
index 0000000..1d5038f
--- /dev/null
+++ b/.svn/pristine/2b/2bdbb1a5c8557e88ab21756b210ceb5a53e89337.svn-base
@@ -0,0 +1,129 @@
+
+using Microsoft.Extensions.Configuration;
+using Newtonsoft.Json;
+using SafeBagDE70.Admin;
+using SafeBagDE70.Model;
+using SafeBagDE70.StateMachine;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Forms;
+using VirtualKeyboard.Wpf;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for App.xaml
+ ///
+ public partial class App : System.Windows.Application
+ {
+ public static StateMachineConfig StateMachineConfig { get; private set; }
+ private static Mutex mutex;
+ public App()
+ {
+ }
+ protected override void OnStartup(StartupEventArgs e)
+ {
+ base.OnStartup(e);
+
+ CheckInstance();
+ LoadConfig();
+ LoadDualScreens();
+ }
+ private static void CheckInstance()
+ {
+ bool isNewInstance;
+ string mutexName = "9f5b55c9-c6eb-443a-8e28-027defa46fb5";
+
+ mutex = new Mutex(true, mutexName, out isNewInstance);
+
+ if (!isNewInstance)
+ {
+ // If an instance is already running, exit the application
+ System.Windows.MessageBox.Show("Ứng dụng đã khởi chạy");
+ System.Windows.Application.Current.Shutdown();
+ return;
+ }
+ }
+ private static void LoadConfig()
+ {
+ try
+ {
+ AppData.CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version;
+ VKeyboard.Listen(e => e.Text);
+ var configuration = new ConfigurationBuilder()
+ .AddJsonFile("appsettings.json")
+ .Build();
+ Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .WriteTo.Sink(new RealTimeLogSink())
+ .CreateLogger();
+ AppData.CDMPort = configuration["SerialPort:CDMPort"];
+ AppData.SensorPort = configuration["SerialPort:SensorPort"];
+ StateMachineConfig = new StateMachineConfig();
+ configuration.GetSection("StateMachine").Bind(StateMachineConfig);
+ Log.Information("START APP");
+ }
+ catch (Exception ex)
+ {
+ System.Windows.MessageBox.Show(ex.Message);
+ }
+ }
+ private void LoadDualScreens()
+ {
+ try
+ {
+ // Create instances of the windows you want to open
+ var mainWindow = new MainWindow();
+
+ // Show both windows
+ mainWindow.Show();
+
+ // Get all available screens
+ var screens = Screen.AllScreens;
+
+ // Open the Main Window on the primary screen
+ var primaryScreen = screens.FirstOrDefault(s => s.Primary) ?? screens.First();
+ PositionWindowOnScreen(mainWindow, primaryScreen);
+ mainWindow.Show();
+
+ // Open the Secondary Window on the secondary screen, if available
+ if (screens.Length > 1)
+ {
+ var adminWindow = new AdminWindow(); // Replace this with your actual window class
+ adminWindow.Show();
+ var secondaryScreen = screens.First(s => !s.Primary);
+ PositionWindowOnScreen(adminWindow, secondaryScreen);
+ adminWindow.Show();
+ }
+ }catch (Exception ex)
+ {
+ Log.Fatal(ex,"START APP");
+ }
+
+ }
+
+ private void PositionWindowOnScreen(Window window, Screen screen)
+ {
+ // Convert screen bounds to WPF units (96 DPI)
+ var screenLeft = screen.WorkingArea.Left / (double)Screen.PrimaryScreen.WorkingArea.Width * SystemParameters.PrimaryScreenWidth;
+ var screenTop = screen.WorkingArea.Top / (double)Screen.PrimaryScreen.WorkingArea.Height * SystemParameters.PrimaryScreenHeight;
+
+ // Set window position and state
+ window.WindowStartupLocation = WindowStartupLocation.Manual;
+ window.Left = screenLeft;
+ window.Top = screenTop;
+ window.Width = screen.WorkingArea.Width;
+ window.Height = screen.WorkingArea.Height;
+ }
+ }
+}
diff --git a/.svn/pristine/2d/2d7e2b0e8efdd036ed252c9e551961db0d46f60c.svn-base b/.svn/pristine/2d/2d7e2b0e8efdd036ed252c9e551961db0d46f60c.svn-base
new file mode 100644
index 0000000..2217181
--- /dev/null
+++ b/.svn/pristine/2d/2d7e2b0e8efdd036ed252c9e551961db0d46f60c.svn-base
@@ -0,0 +1,4 @@
+//
+using System;
+using System.Reflection;
+[assembly: global::System.Runtime.Versioning.TargetFrameworkAttribute(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
diff --git a/.svn/pristine/2d/2dd7a1bb82ed6ffe482c8760313267c30ba66061.svn-base b/.svn/pristine/2d/2dd7a1bb82ed6ffe482c8760313267c30ba66061.svn-base
new file mode 100644
index 0000000..c9d1f78
--- /dev/null
+++ b/.svn/pristine/2d/2dd7a1bb82ed6ffe482c8760313267c30ba66061.svn-base
@@ -0,0 +1,8 @@
+{
+ "version": 2,
+ "dgSpecHash": "0AU11qKXzf8=",
+ "success": true,
+ "projectFilePath": "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "expectedPackageFiles": [],
+ "logs": []
+}
\ No newline at end of file
diff --git a/.svn/pristine/2d/2deaf905d3fc9472dee2205eb53aad1cffa4f259.svn-base b/.svn/pristine/2d/2deaf905d3fc9472dee2205eb53aad1cffa4f259.svn-base
new file mode 100644
index 0000000..ca4cab3
Binary files /dev/null and b/.svn/pristine/2d/2deaf905d3fc9472dee2205eb53aad1cffa4f259.svn-base differ
diff --git a/.svn/pristine/2e/2e62f7034f46df794a0fba0e1cec8d2de30c63be.svn-base b/.svn/pristine/2e/2e62f7034f46df794a0fba0e1cec8d2de30c63be.svn-base
new file mode 100644
index 0000000..789013b
--- /dev/null
+++ b/.svn/pristine/2e/2e62f7034f46df794a0fba0e1cec8d2de30c63be.svn-base
@@ -0,0 +1,279 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+
+ //public class CountSession
+ //{
+ // public int[] QuantityDenomi { get; set; }
+ // public int[] SumDenomi { get; set; }
+
+ //}
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ SerialPort serialPort = new SerialPort();
+
+ private int[] denominations = { 500000, 200000, 100000, 50000, 20000, 10000, 5000, 2000, 1000, 500 };
+
+ List sessions = new List();
+ public MainWindow()
+ {
+
+ InitializeComponent();
+
+ serialPort.PortName = "COM3";
+ serialPort.BaudRate = 9600;
+ serialPort.Parity = Parity.Even;
+ serialPort.DataBits = 8;
+ serialPort.StopBits = StopBits.One;
+
+ //Subscrible to the DataReveied event
+
+ serialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPort_DataReceived);
+
+ //serialPort.Open();
+ }
+ public long maxQuantitySheet = 10000;
+
+
+ public int totalAllDenominations = 0;
+
+ public int flag = 0;
+
+
+ public string hexReceivedString = "";
+
+ public void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
+ {
+ int bytesToRead = serialPort.BytesToRead;
+ byte[] receivedBytes = new byte[bytesToRead];
+ serialPort.Read(receivedBytes, 0, bytesToRead);
+
+
+ //Convert to hex string
+
+
+ string newHexString = BitConverter.ToString(receivedBytes).Replace("-", " ");
+
+ hexReceivedString = newHexString;
+
+
+ }
+ public async void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ sessions.Add(new CountSession());
+
+ string deSenseExpectedString0 = "10 02 30 38 34 60 40 07 41 00 01 00 00 00 00 00 00 10 10 00 00 00 00 00 F0 12";
+ string deSenseExpectedString1 = "10 02 30 38 34 60 40 07 41 00 01 00 00 00 00 00 00 10 10 00 00 01 00 01 F0 12";
+ string deSenseExpectedString2 = "10 02 30 38 34 60 40 07 41 00 01 00 00 00 00 00 00 10 10 00 00 02 00 02 F0 12";
+ string deSenseExpectedString3 = "10 02 30 38 34 60 40 07 41 00 01 00 00 00 00 00 00 10 10 00 00 03 00 03 F0 12";
+ string deSenseExpectedString4 = "10 02 30 38 34 60 40 07 41 00 01 00 00 00 00 00 00 10 10 00 00 04 00 04 F0 12";
+ string deSenseExpectedString5 = "10 02 30 38 34 60 40 07 41 00 01 00 00 00 00 00 00 10 10 00 00 05 00 05 F0 12";
+
+
+ var countStart = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x73, 0x10, 0x03, 0x41 };
+ serialPort.Write(countStart, 0, countStart.Length);
+
+ await Task.Delay(2500);
+
+
+
+ //int[] quantityValues = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+
+ //int[] sessions[sessions.Count - 1].SumDenomi = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+
+
+
+ var deSense = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x60, 0x10, 0x03, 0x52 };
+
+ serialPort.Write(deSense, 0, deSense.Length);
+
+ await Task.Delay(300);
+
+ if (hexReceivedString.Contains(deSenseExpectedString0) || hexReceivedString.Contains(deSenseExpectedString1) || hexReceivedString.Contains(deSenseExpectedString2) || hexReceivedString.Contains(deSenseExpectedString3) || hexReceivedString.Contains(deSenseExpectedString4) || hexReceivedString.Contains(deSenseExpectedString5))
+ {
+ //Hexa string data received process
+ string[] hexValues = hexReceivedString.Split(' ');
+
+
+ int[] values = new int[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ values[i] = Convert.ToInt32(hexValues[i], 16);
+ }
+
+ //Take amount of each denomination
+
+ sessions[0].QuantityDenomi = values.Skip(26).Take(10).ToArray();
+
+ //Total money of each denomination.
+
+
+ for (int i = 0; i < sessions[0].QuantityDenomi.Length; i++)
+ {
+ sessions[sessions.Count - 1].SumDenomi[i] = sessions[sessions.Count - 1].QuantityDenomi[i] * denominations[i];
+ }
+ //Total amount of each denomination
+
+ // Total money of all denominations
+ totalAllDenominations = sessions[sessions.Count - 1].SumDenomi.Sum();
+
+ }
+
+ Dispatcher.Invoke(() =>
+ {
+ //Update UI
+ txtTotalMoney.Text = totalAllDenominations.ToString();
+
+ quantityDenomi0.Text = sessions[sessions.Count - 1].QuantityDenomi[9].ToString();
+ quantityDenomi1.Text = sessions[sessions.Count - 1].QuantityDenomi[8].ToString();
+ quantityDenomi2.Text = sessions[sessions.Count - 1].QuantityDenomi[7].ToString();
+ quantityDenomi3.Text = sessions[sessions.Count - 1].QuantityDenomi[6].ToString();
+ quantityDenomi4.Text = sessions[sessions.Count - 1].QuantityDenomi[5].ToString();
+ quantityDenomi5.Text = sessions[sessions.Count - 1].QuantityDenomi[4].ToString();
+ quantityDenomi6.Text = sessions[sessions.Count - 1].QuantityDenomi[3].ToString();
+ quantityDenomi7.Text = sessions[sessions.Count - 1].QuantityDenomi[2].ToString();
+ quantityDenomi8.Text = sessions[sessions.Count - 1].QuantityDenomi[1].ToString();
+ quantityDenomi9.Text = sessions[sessions.Count - 1].QuantityDenomi[0].ToString();
+
+ totalAmountQuantityDenomi0.Text = sessions[sessions.Count - 1].SumDenomi[9].ToString();
+ totalAmountQuantityDenomi1.Text = sessions[sessions.Count - 1].SumDenomi[8].ToString();
+ totalAmountQuantityDenomi2.Text = sessions[sessions.Count - 1].SumDenomi[7].ToString();
+ totalAmountQuantityDenomi3.Text = sessions[sessions.Count - 1].SumDenomi[6].ToString();
+ totalAmountQuantityDenomi4.Text = sessions[sessions.Count - 1].SumDenomi[5].ToString();
+ totalAmountQuantityDenomi5.Text = sessions[sessions.Count - 1].SumDenomi[4].ToString();
+ totalAmountQuantityDenomi6.Text = sessions[sessions.Count - 1].SumDenomi[3].ToString();
+ totalAmountQuantityDenomi7.Text = sessions[sessions.Count - 1].SumDenomi[2].ToString();
+ totalAmountQuantityDenomi8.Text = sessions[sessions.Count - 1].SumDenomi[1].ToString();
+ totalAmountQuantityDenomi9.Text = sessions[sessions.Count - 1].SumDenomi[0].ToString();
+ });
+
+
+
+
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ //Xóa tiền đã đếm trong lần trước, cập nhật lại giao diện
+
+
+ var check = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x76, 0x10, 0x03, 0x44 };
+ serialPort.Write(check, 0, check.Length);
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ var storeStart = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x75, 0x10, 0x03, 0x47 };
+ serialPort.Write(storeStart, 0, storeStart.Length);
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+ string deSenseDataRev01 = "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 00 00 01 70 00 10 03 35";
+ string deSenseDataRev02 = "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 01 00 02 70 00 10 03 37";
+ string deSenseDataRev03 = "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 02 00 03 70 00 10 03 35";
+ string deSenseDataRev04 = "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 03 00 04 70 00 10 03 33";
+ string deSenseDataRev05 = "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 04 00 05 70 00 10 03 35";
+ string deSenseDataRev00 = "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 05 00 00 70 00 10 03 31";
+
+ string[] deSenseDataRevSatisfy = { "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 05 00 05 70 00 10 03 34", "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 04 00 04 70 00 10 03 34", "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 03 00 03 70 00 10 03 34", "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 02 00 02 70 00 10 03 34", "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 01 00 01 70 00 10 03 34", "10 02 30 32 30 60 40 04 41 00 00 00 00 00 00 00 00 10 10 00 00 00 00 00 70 00 10 03 34" };
+
+
+ var deSense = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x60, 0x10, 0x03, 0x52 };
+ serialPort.Write(deSense, 0, deSense.Length);
+
+ Thread.Sleep(100);
+
+ if (hexReceivedString == deSenseDataRev01)
+ {
+ flag = 1;
+ var eventDataFixed_1 = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x01, 0x10, 0x03, 0x54 };
+
+ serialPort.Write(eventDataFixed_1, 0, eventDataFixed_1.Length);
+ } else if (hexReceivedString == deSenseDataRev02)
+ {
+ flag = 1;
+ var eventDataFixed_2 = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x02, 0x10, 0x03, 0x57 };
+
+ serialPort.Write(eventDataFixed_2, 0, eventDataFixed_2.Length);
+ }
+ else if (hexReceivedString == deSenseDataRev03)
+ {
+ flag = 1;
+ var eventDataFixed_3 = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x03, 0x10, 0x03, 0x56 };
+
+ serialPort.Write(eventDataFixed_3, 0, eventDataFixed_3.Length);
+ }
+ else if (hexReceivedString == deSenseDataRev04)
+ {
+ flag = 1;
+ var eventDataFixed_4 = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x04, 0x10, 0x03, 0x51 };
+
+ serialPort.Write(eventDataFixed_4, 0, eventDataFixed_4.Length);
+ }
+ else if (hexReceivedString == deSenseDataRev05)
+ {
+ flag = 1;
+ var eventDataFixed_5 = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x05, 0x10, 0x03, 0x50 };
+
+ serialPort.Write(eventDataFixed_5, 0, eventDataFixed_5.Length);
+ }
+ else if (hexReceivedString == deSenseDataRev00)
+ {
+ flag = 1;
+ var eventDataFixed_0 = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x00, 0x10, 0x03, 0x55 };
+
+ serialPort.Write(eventDataFixed_0, 0, eventDataFixed_0.Length);
+ } else if (deSenseDataRevSatisfy.Contains(hexReceivedString))
+ {
+ flag = 1;
+ };
+
+
+ if(flag == 1)
+ {
+ var start = new byte[] { 0x10, 0x02, 0x30, 0x31, 0x33, 0x70, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x09, 0x00, 0x01, 0x01, 0x00, 0x10, 0x03, 0x48 }; //lock
+ serialPort.Write(start, 0, start.Length);
+ }
+
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+
+ //Đặt lại tất cả , kết thúc phiên và sẵn sàng vào phiên mới
+
+ //int[] numbers = new int[] {1,2,3,4,5,6};
+ //Array.Clear(numbers, 0, numbers.Length);
+ var end = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x71, 0x10, 0x03, 0x43 };
+ serialPort.Write(end, 0, end.Length);
+ flag = 0;
+ maxQuantitySheet = 0;
+ }
+
+ }
+}
diff --git a/.svn/pristine/2e/2e67fa142d2d90139818d36b4d1063e0f8523a41.svn-base b/.svn/pristine/2e/2e67fa142d2d90139818d36b4d1063e0f8523a41.svn-base
new file mode 100644
index 0000000..bae5da1
--- /dev/null
+++ b/.svn/pristine/2e/2e67fa142d2d90139818d36b4d1063e0f8523a41.svn-base
@@ -0,0 +1,67 @@
+using DE70_CMDv2;
+using SafeBagDE70.Services;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class InformationUC : UserControl
+ {
+ private bool _bContinue = false;
+ private bool _bPlaySound = false;
+ private List _controls = null;
+ public InformationUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor, bool bContinue = false, bool bPlaySound=true,List controls=null)
+ {
+ lblInfor.Text = strInfor;
+ _bContinue = bContinue;
+ _bPlaySound = bPlaySound;
+ _controls = controls;
+ if (_bPlaySound)
+ SoundManager.StartWarningSound();
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ if(_controls!=null)
+ {
+ foreach (var item in _controls)
+ {
+ item.IsEnabled = true;
+ }
+ }
+
+ if(_bContinue)
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen(false);
+ else
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ SoundManager.StopWarningSound();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ SoundManager.StopWarningSound();
+ }
+ }
+}
diff --git a/.svn/pristine/2f/2fedb2a062d77673a9c55e94464cd330e5b23010.svn-base b/.svn/pristine/2f/2fedb2a062d77673a9c55e94464cd330e5b23010.svn-base
new file mode 100644
index 0000000..8599efd
--- /dev/null
+++ b/.svn/pristine/2f/2fedb2a062d77673a9c55e94464cd330e5b23010.svn-base
@@ -0,0 +1,11 @@
+{
+ "runtimeTarget": {
+ "name": ".NETCoreApp,Version=v8.0",
+ "signature": ""
+ },
+ "compilationOptions": {},
+ "targets": {
+ ".NETCoreApp,Version=v8.0": {}
+ },
+ "libraries": {}
+}
\ No newline at end of file
diff --git a/.svn/pristine/30/300eda00820628fbe6afbb46187f36e547015f21.svn-base b/.svn/pristine/30/300eda00820628fbe6afbb46187f36e547015f21.svn-base
new file mode 100644
index 0000000..6d99bc7
--- /dev/null
+++ b/.svn/pristine/30/300eda00820628fbe6afbb46187f36e547015f21.svn-base
@@ -0,0 +1,65 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/31/313dff12b1ec05aaf70e1bfd51d27a40f90107fa.svn-base b/.svn/pristine/31/313dff12b1ec05aaf70e1bfd51d27a40f90107fa.svn-base
new file mode 100644
index 0000000..3de3d83
--- /dev/null
+++ b/.svn/pristine/31/313dff12b1ec05aaf70e1bfd51d27a40f90107fa.svn-base
@@ -0,0 +1,13 @@
+is_global = true
+build_property.TargetFramework = net8.0-windows
+build_property.TargetPlatformMinVersion = 7.0
+build_property.UsingMicrosoftNETSdkWeb =
+build_property.ProjectTypeGuids =
+build_property.InvariantGlobalization =
+build_property.PlatformNeutralAssembly =
+build_property.EnforceExtendedAnalyzerRules =
+build_property._SupportedPlatformList = Linux,macOS,Windows
+build_property.RootNamespace = VirtualKeyboard_dsmyrzi2_wpftmp
+build_property.ProjectDir = C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\
+build_property.EnableComHosting =
+build_property.EnableGeneratedComInterfaceComImportInterop =
diff --git a/.svn/pristine/33/33137c6642651ea1c5be552706afa8ecfd505ef5.svn-base b/.svn/pristine/33/33137c6642651ea1c5be552706afa8ecfd505ef5.svn-base
new file mode 100644
index 0000000..394dbe7
--- /dev/null
+++ b/.svn/pristine/33/33137c6642651ea1c5be552706afa8ecfd505ef5.svn-base
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/33/33955113d4abbedfb5cf88e02d94a0dba1ef31de.svn-base b/.svn/pristine/33/33955113d4abbedfb5cf88e02d94a0dba1ef31de.svn-base
new file mode 100644
index 0000000..89dd690
--- /dev/null
+++ b/.svn/pristine/33/33955113d4abbedfb5cf88e02d94a0dba1ef31de.svn-base
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/34/34aa833a63d6d22b5ad669650e255da461087029.svn-base b/.svn/pristine/34/34aa833a63d6d22b5ad669650e255da461087029.svn-base
new file mode 100644
index 0000000..5028e11
--- /dev/null
+++ b/.svn/pristine/34/34aa833a63d6d22b5ad669650e255da461087029.svn-base
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.7.34202.233
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SafeBagDE70", "SafeBagDE70.csproj", "{DCA4F90E-EB1C-4038-BEAC-73BC15158E05}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "VirtualKeyboard", "VirtualKeyboard\VirtualKeyboard.csproj", "{F7B9604B-FC5A-493E-98C1-38E54329E33F}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Release|Any CPU.Build.0 = Release|Any CPU
+ {F7B9604B-FC5A-493E-98C1-38E54329E33F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {F7B9604B-FC5A-493E-98C1-38E54329E33F}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {F7B9604B-FC5A-493E-98C1-38E54329E33F}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {F7B9604B-FC5A-493E-98C1-38E54329E33F}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {471DAFF3-9038-41B5-8763-7F24A56B5F19}
+ EndGlobalSection
+EndGlobal
diff --git a/.svn/pristine/36/36bc643c49cb358e10bd5d4ee4b0bb9b40f73b2c.svn-base b/.svn/pristine/36/36bc643c49cb358e10bd5d4ee4b0bb9b40f73b2c.svn-base
new file mode 100644
index 0000000..5eedacf
Binary files /dev/null and b/.svn/pristine/36/36bc643c49cb358e10bd5d4ee4b0bb9b40f73b2c.svn-base differ
diff --git a/.svn/pristine/36/36ce9699a2203ded4bbc230e0ed6729dfe608535.svn-base b/.svn/pristine/36/36ce9699a2203ded4bbc230e0ed6729dfe608535.svn-base
new file mode 100644
index 0000000..08bb19f
--- /dev/null
+++ b/.svn/pristine/36/36ce9699a2203ded4bbc230e0ed6729dfe608535.svn-base
@@ -0,0 +1,6 @@
+//
+global using global::System;
+global using global::System.Collections.Generic;
+global using global::System.Linq;
+global using global::System.Threading;
+global using global::System.Threading.Tasks;
diff --git a/.svn/pristine/36/36d27c611cbc34447deb0018407decb3864e4358.svn-base b/.svn/pristine/36/36d27c611cbc34447deb0018407decb3864e4358.svn-base
new file mode 100644
index 0000000..7b7de26
--- /dev/null
+++ b/.svn/pristine/36/36d27c611cbc34447deb0018407decb3864e4358.svn-base
@@ -0,0 +1,95 @@
+using DE70_CMDv2;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for AdminConfigurationUC.xaml
+ ///
+ public partial class AdminConfigurationUC : UserControl
+ {
+ public AdminConfigurationUC()
+ {
+ InitializeComponent();
+ }
+
+ private void btnResetCounter_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ {
+ Log.Information("[ADMIN] reset counter");
+ CCmdRsp cCmdRsp = AppData.cCmdRsp;
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ Log.Information("[ADMIN] reset counter success");
+ lblStatus.Text = "TRẠNG THÁI: KHỞI TẠO BỘ ĐẾM THÀNH CÔNG";
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ Task.Run(() =>
+ {
+ Thread.Sleep(2);
+ lblStatus.Text = "";
+ });
+ }
+ else
+ {
+ Log.Information("[ADMIN] reset counter fail");
+ }
+ }
+ }
+
+ private void btnOpenEscrow_Click(object sender, RoutedEventArgs e)
+ {
+ Log.Information("[ADMIN] Do Check");
+ var mainWindow = ((MainWindow)Application.Current.MainWindow);
+ if (mainWindow!=null)
+ mainWindow.DoCheck();
+ }
+
+ private void btnGetCDMState_Click(object sender, RoutedEventArgs e)
+ {
+ AppData.GetCDMState();
+ }
+ }
+}
diff --git a/.svn/pristine/38/38f4ced668feee3f638188f35897358659d19a40.svn-base b/.svn/pristine/38/38f4ced668feee3f638188f35897358659d19a40.svn-base
new file mode 100644
index 0000000..5fb33d3
--- /dev/null
+++ b/.svn/pristine/38/38f4ced668feee3f638188f35897358659d19a40.svn-base
@@ -0,0 +1,13 @@
+is_global = true
+build_property.TargetFramework = net8.0-windows
+build_property.TargetPlatformMinVersion = 7.0
+build_property.UsingMicrosoftNETSdkWeb =
+build_property.ProjectTypeGuids =
+build_property.InvariantGlobalization =
+build_property.PlatformNeutralAssembly =
+build_property.EnforceExtendedAnalyzerRules =
+build_property._SupportedPlatformList = Linux,macOS,Windows
+build_property.RootNamespace = VirtualKeyboard_haw2ca4l_wpftmp
+build_property.ProjectDir = D:\SRC\VirtualKeyboard\
+build_property.EnableComHosting =
+build_property.EnableGeneratedComInterfaceComImportInterop =
diff --git a/.svn/pristine/3a/3a6f3f9c5dfab137eb1c445ea492ab0bb1428bc0.svn-base b/.svn/pristine/3a/3a6f3f9c5dfab137eb1c445ea492ab0bb1428bc0.svn-base
new file mode 100644
index 0000000..a2ce655
--- /dev/null
+++ b/.svn/pristine/3a/3a6f3f9c5dfab137eb1c445ea492ab0bb1428bc0.svn-base
@@ -0,0 +1,113 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/3a/3a8ab8af47d218dfcfe8741496ff7f3915877194.svn-base b/.svn/pristine/3a/3a8ab8af47d218dfcfe8741496ff7f3915877194.svn-base
new file mode 100644
index 0000000..5af882e
--- /dev/null
+++ b/.svn/pristine/3a/3a8ab8af47d218dfcfe8741496ff7f3915877194.svn-base
@@ -0,0 +1,75 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/3b/3be411ab57b30b1382bfb131f79d063bfe16777a.svn-base b/.svn/pristine/3b/3be411ab57b30b1382bfb131f79d063bfe16777a.svn-base
new file mode 100644
index 0000000..c6fa04e
--- /dev/null
+++ b/.svn/pristine/3b/3be411ab57b30b1382bfb131f79d063bfe16777a.svn-base
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/3c/3cc92d67cafcea958d6f9b6c091a0cd1040d2136.svn-base b/.svn/pristine/3c/3cc92d67cafcea958d6f9b6c091a0cd1040d2136.svn-base
new file mode 100644
index 0000000..4331f68
--- /dev/null
+++ b/.svn/pristine/3c/3cc92d67cafcea958d6f9b6c091a0cd1040d2136.svn-base
@@ -0,0 +1 @@
+4a056bf95b46531a2877476e4e0992b8c717c7956a532dafc823bd29f67e8c0f
diff --git a/.svn/pristine/3e/3ed1c8bff708abaf92e7156fecb329a2aa25b3a9.svn-base b/.svn/pristine/3e/3ed1c8bff708abaf92e7156fecb329a2aa25b3a9.svn-base
new file mode 100644
index 0000000..d4e5fed
--- /dev/null
+++ b/.svn/pristine/3e/3ed1c8bff708abaf92e7156fecb329a2aa25b3a9.svn-base
@@ -0,0 +1,1243 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.StateMachine;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
+using System.Runtime.Intrinsics.Arm;
+using SafeBagDE70.Services;
+using System.Windows.Forms;
+using Button = System.Windows.Controls.Button;
+using UserControl = System.Windows.Controls.UserControl;
+using Application = System.Windows.Application;
+using Control = System.Windows.Controls.Control;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositSMUCv2 : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer sensorTimer;
+ private volatile bool bIsCounted = false;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+ bool bOpenPort = true;
+ bool bIsMaintain = false;
+ MainWindow mainWindow = null;
+ Thread thread = null;
+ Task taskCounting = null;
+ public DepositSMUCv2()
+ {
+ InitializeComponent();
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ mainWindow=((MainWindow)Application.Current.MainWindow);
+ //InitTransaction();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ lblName.Content= "Vietinbank " + Environment.MachineName;
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+
+ }
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+ AppData.IsInTransaction = true;
+ ResetButtons();
+ btnStart.IsEnabled = true;
+ ResetTimers();
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if(bOpenPort)
+ {
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+ if(bOpenPort)
+ {
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ }
+ DispatcherTimer? warningTimer = null;
+ DispatcherTimer? timeoutTimer = null;
+ private void InitTimers()
+ {
+ warningTimer = new DispatcherTimer(); // 30 seconds
+ warningTimer.Interval = new TimeSpan(0, 0, 15);
+ warningTimer.Tick += WarningTimer_Tick; ;
+ warningTimer.Stop();
+
+ timeoutTimer = new DispatcherTimer(); // 60 seconds
+ timeoutTimer.Interval = new TimeSpan(0, 0, 30);
+ timeoutTimer.Tick += TimeoutTimer_Tick;
+ timeoutTimer.Stop();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ private void TimeoutTimer_Tick(object? sender, EventArgs e)
+ {
+ Log.Information("6. Timout starting");
+ StopTimers();
+ DoStoreStart();
+ bIsCounted = false;
+ CountStart(false);
+ Task.Run(() =>
+ {
+ taskCounting.Wait();
+ DoStoreStart();
+ Dispatcher.Invoke(() =>
+ {
+ EndSession();
+ });
+ Log.Information("6. Timout completed");
+ });
+
+ }
+
+ private void BackToWelcomeScreen()
+ {
+ StopTimers();
+ var cdmState = GetCDMState();
+ var state = GetCDMState();
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInHopper > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ }
+
+ private void WarningTimer_Tick(object? sender, EventArgs e)
+ {
+
+ mainWindow.ShowTimeoutScreen();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ if (warningTimer != null)
+ {
+ warningTimer.Tick -=WarningTimer_Tick;
+ warningTimer.Stop();
+ }
+ if (timeoutTimer != null)
+ {
+ timeoutTimer.Tick -= TimeoutTimer_Tick;
+ timeoutTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+
+
+ public void InitLvCountItems()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ // public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ // public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ // public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+ public int countSensorTimer = 0;
+ //PrinterManager printerManager = new PrinterManager();
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ countSensorTimer++;
+
+ if (countSensorTimer % 10 == 0)
+ {
+ APIModels.SendHealthCheck();
+ }
+
+ sensorTimer.IsEnabled = false;
+ GetSensorValue();
+ sensorTimer.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Sensor_Timer");
+ }
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ if (!bIsMaintain)
+ {
+ bIsMaintain = true;
+ DoMaintaince();
+ }
+
+ // TransitionToState("Maintainance");
+ }
+ else
+ {
+ if(bIsMaintain)
+ {
+ bIsMaintain = false;
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ }
+
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"GetSensorValue");
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+ private void DoMaintaince()
+ {
+ StopTimers();
+ ((MainWindow)Application.Current.MainWindow).ShowMaintainanceScreen();
+ }
+
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet()
+ {
+ try
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ var countSession = new CountSession();
+ countSession.IsStored = false;
+ sessions.Add(countSession);
+ while (true)
+ {
+ AppData.WDTCount = 0;
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ AppData.WDTCount = 0;
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: countSession.TempNotes[0]++;break;
+ case 0x02:
+ //TempNote[1] ++;
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}");
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: countSession.QuantityDenomi[0]++; break;
+ case 0x01: countSession.QuantityDenomi[1]++; break;
+ case 0x02: countSession.QuantityDenomi[2]++; break;
+ case 0x03: countSession.QuantityDenomi[3]++; break;
+ case 0x04: countSession.QuantityDenomi[4]++; break;
+ case 0x05: countSession.QuantityDenomi[5]++; break;
+ case 0x06: countSession.QuantityDenomi[6]++; break;
+ case 0x07: countSession.QuantityDenomi[7]++; break;
+ case 0x08: countSession.QuantityDenomi[8]++; break;
+ case 0x09: countSession.QuantityDenomi[9]++; break;
+
+ }
+ break;
+ case 0x03: countSession.TempNotes[2]++; break;
+ case 0x0b: countSession.TempNotes[3]++; break;
+ case 0x0c: countSession.TempNotes[4]++; break;
+ }
+ UpdateListViewCountItems();
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0)
+ {
+ sessions.Remove(countSession);
+ }
+ }catch(Exception ex)
+ {
+ Log.Fatal(ex, "AutoSerialGet");
+ }
+
+ //Log.Information(JsonConvert.SerializeObject(sessions));
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private bool CountStart(bool bInitState=true)
+ {
+ bool bSuccess = true;
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ if(bOpenPort)
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+ }
+
+
+ //SR3 = 0x43 : Stacker full
+
+ //thread = new Thread(new ThreadStart(() =>
+ //{
+ // Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ // bIsCounted = false;
+ // AutoSerialGet();
+ // bIsCounted = true;
+ // Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+
+ // if (bInitState)
+ // {
+ // Dispatcher.Invoke(() =>
+ // {
+ // btnCountStart.IsEnabled = true;
+ // btnCheck.IsEnabled = true;
+ // btnStoreStart.IsEnabled = true;
+ // ResetTimers();
+ // Log.Information("2. Count completed");
+ // });
+ // }
+ //}));
+ //thread.Start();
+ taskCounting = Task.Run(() =>
+ {
+ Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ bIsCounted = false;
+ AutoSerialGet();
+ bIsCounted = true;
+ Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+
+ if (bInitState)
+ {
+ Dispatcher.Invoke(() =>
+ {
+ btnCountStart.IsEnabled = true;
+ btnCheck.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ ResetTimers();
+ Log.Information("2. Count completed");
+ });
+ }
+ });
+
+
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex,currentMethod);
+ }
+ return bSuccess;
+ }
+
+ private void UpdateListViewCountItems()
+ {
+ Dispatcher.Invoke(DispatcherPriority.Normal, () =>
+ {
+ double sum = 0;
+ if (sessions != null && sessions.Count > 0)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ int quantity = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ quantity += sessions[j].QuantityDenomi[9 - i];
+
+ }
+ lvCountItems[i].Quantity = quantity.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+ }
+ else
+ {
+ for (int i = 0; i < 11; i++)
+ {
+ lvCountItems[i].Quantity = "0";
+ lvCountItems[i].Value = "0";
+ }
+ }
+ });
+
+ }
+
+ private bool DoCheck()
+ {
+ bool bSuccess = true;
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ sessions.RemoveAll(item=>!item.IsStored);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ UpdateListViewCountItems();
+
+
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilCountReady(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while (true)
+ {
+ state = GetCDMState();
+ if (state.SR2 == 0x07)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilEnscrowEmpty(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while(true)
+ {
+ state = GetCDMState();
+ if (state.IsNotesInEscrow == 0)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool DoStoreStart()
+ {
+ bool bSuccess = true;
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ //sessions.Add(new CountSession());
+
+ // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ foreach(var item in sessions)
+ {
+ item.IsStored = true;
+ }
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored "+GetShortInforFromCountItems());
+ //Debug.WriteLine(quantityStored);
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ bSuccess=WaitUntilCountReady(10);
+ Thread.Sleep(2000);
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoStart()
+ {
+ bool bSuccess = true;
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoEnd()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ StopTimers();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ var lstEnabledControls = new List { btnEnd, btnCountStart };
+ if (state.IsNotesInEscrow > 0)
+ {
+ btnEnd.IsEnabled = true;
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true,true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ btnEnd.IsEnabled = true;
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true, true);
+ }
+ else if(state.IsNotesInHopper>0)
+ {
+ btnEnd.IsEnabled = true;
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", true, true);
+ }
+ else
+ {
+ bSuccess = true;
+ AppData.WDTCount = 0;
+ EndSession();
+
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+
+ ResetTimers();
+ }
+ return bSuccess;
+ }
+ private bool DoLogout()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ InitLvCountItems();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else //if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess = true;
+ EndSession();
+ BackToWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ if (double.Parse(totalValue) > 0)
+ {
+ var data2Send = new CountingData2Send
+ {
+ TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
+ Sessions = sessions,
+ MachineId = Environment.MachineName,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ //RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ //UnfitNotes = Notes[2],
+ //CounterfeitNotes = Notes[3],
+ // SuspendNotes = Notes[4]
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if (double.Parse(totalValue) > 0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify, false, false);
+ ResetSessions();
+ }
+ //SendData2Server
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, currentMethod);
+ }
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Save2DB Exception");
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Update2DB Exception");
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+ public class CDMSTATE
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ public int IsNotesInHopper = 0;
+ public byte SR1;
+ public byte SR2;
+ public byte SR3;
+ }
+ private CDMSTATE GetCDMState()
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv=cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ var cdmState = new CDMSTATE();
+
+ cdmState.IsCassetteFull = data[17] & 0x08;
+ cdmState.IsNotesInEscrow = data[4] & 0x01;
+ cdmState.IsRejectPocketFull = data[3] & 0x40;
+ cdmState.IsNotesInRejectPocket = data[3] & 0x10;
+ cdmState.IsNotesInHopper = data[3] & 0x01;
+ cdmState.SR1 = data[0];
+ cdmState.SR2 = data[1];
+ cdmState.SR3 = data[2];
+ return cdmState;
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ ResetSessions();
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal(ex,"InitSession");
+ }
+ return false;
+ }
+
+ private void ResetSessions()
+ {
+ InitLvCountItems();
+ sessions.Clear();
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ }
+
+ private void PrintReceipt()
+ {
+ Log.Information("PrintReceipt");
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ public void ResetTimers()
+ {
+ StopTimers();
+ StartTimers();
+ }
+
+ public void StartTimers()
+ {
+ if(warningTimer!=null && timeoutTimer != null)
+ {
+ warningTimer.Start();
+ timeoutTimer.Start();
+ }
+
+ }
+
+ public void StopTimers()
+ {
+ if(warningTimer!=null && timeoutTimer!=null)
+ {
+ warningTimer.Stop();
+ timeoutTimer.Stop();
+ }
+
+ }
+
+ private void ResetButtons()
+ {
+ btnStart.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ btnLogout.IsEnabled = false;
+ }
+
+
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ SoundManager.StartButtonPressSound();
+ // Console.Beep(800, 200);
+ StopTimers();
+ bool bResult = false;
+ if (btn==btnStart)
+ {
+ Log.Information("Deposit starting");
+ Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ Log.Information("1. Start starting");
+ ResetButtons();
+ bResult = DoStart();
+
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("1. Start completed");
+ else
+ Log.Information("1. Start failed");
+ }
+ else if(btn==btnCountStart)
+ {
+
+ Log.Information("2. Count starting");
+ ResetButtons();
+ bResult = CountStart();
+
+ // if (taskCounting != null) taskCounting.Wait();
+ //while (!bIsCounted) // chua thoat duoc loop
+ //{
+ // Thread.Sleep(100);
+ //}
+ //Do in counting thread
+
+ }
+ else if(btn==btnCheck)
+ {
+ Log.Information($"3. Check starting");
+ ResetButtons();
+ bResult = DoCheck();
+ btnCountStart.IsEnabled= true;
+ ResetTimers();
+ if (bResult)
+ Log.Information($"3. Check completed");
+ else
+ Log.Information($"3. Check failed");
+ }
+ else if (btn == btnStoreStart)
+ {
+ //TransitionToState("Store");
+ Log.Information("4. Store starting");
+ ResetButtons();
+ bResult = DoStoreStart();
+ btnEnd.IsEnabled= true;
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("4. Store completed");
+ else
+ Log.Information("4. Store failed");
+ }
+ else if (btn == btnEnd)
+ {
+ // TransitionToState("End");
+ Log.Information("5. End starting");
+ ResetButtons();
+ bResult = DoEnd();
+ //btnStart.IsEnabled = true;
+ //btnLogout.IsEnabled = true;
+ //ResetTimers();
+ if (bResult)
+ Log.Information("5. End Completed");
+ else
+ Log.Information("5. End failed");
+ }
+ else if (btn == btnLogout)
+ {
+ Log.Information("6. Exit starting");
+ bResult = DoLogout();
+ if (bResult)
+ Log.Information("6. Exit Completed");
+ else
+ Log.Information("6. Exit failed");
+ }
+ }
+
+
+ }
+}
+
diff --git a/.svn/pristine/41/4168a43fed1a25a07dd36bd38f44cc5892f1918a.svn-base b/.svn/pristine/41/4168a43fed1a25a07dd36bd38f44cc5892f1918a.svn-base
new file mode 100644
index 0000000..649e4ee
Binary files /dev/null and b/.svn/pristine/41/4168a43fed1a25a07dd36bd38f44cc5892f1918a.svn-base differ
diff --git a/.svn/pristine/43/4374140a0fed76f7fd83820e394cae3f76cdb7c9.svn-base b/.svn/pristine/43/4374140a0fed76f7fd83820e394cae3f76cdb7c9.svn-base
new file mode 100644
index 0000000..31a6ec7
--- /dev/null
+++ b/.svn/pristine/43/4374140a0fed76f7fd83820e394cae3f76cdb7c9.svn-base
@@ -0,0 +1,56 @@
+using DE70_CMDv2;
+using SafeBagDE70.Services;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class MaintainanceUC : UserControl
+ {
+ private bool _bContinue = false;
+ private bool _bPlaySound = false;
+ public MaintainanceUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor, bool bContinue = false, bool bPlaySound=true)
+ {
+ lblInfor.Text = strInfor;
+ _bContinue = bContinue;
+ _bPlaySound = bPlaySound;
+ if (_bPlaySound)
+ SoundManager.StartWarningSound();
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ if(_bContinue)
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen(false);
+ else
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ SoundManager.StopWarningSound();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ SoundManager.StopWarningSound();
+ }
+ }
+}
diff --git a/.svn/pristine/44/445302346de994c5ec49f803922e2891779ddc9e.svn-base b/.svn/pristine/44/445302346de994c5ec49f803922e2891779ddc9e.svn-base
new file mode 100644
index 0000000..c1a6fae
--- /dev/null
+++ b/.svn/pristine/44/445302346de994c5ec49f803922e2891779ddc9e.svn-base
@@ -0,0 +1,909 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositUC : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+
+ public DepositUC()
+ {
+ InitializeComponent();
+
+ }
+
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ InitTransaction();
+
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+ }
+
+ // LoginUsingQRCode();
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+
+ serialPortDE70.PortName = "COM4";
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+
+ serialPortSensor.PortName = "COM3";
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+
+ //Subscrible to the DataReveied event
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+
+ bInitialized = InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ timer.IsEnabled = false;
+ GetSensorValue();
+ if (AppData.IsInTransaction)
+ {
+ if (AppData.WDTCount == 30)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen();
+ }
+ else if (AppData.WDTCount == 60)
+ {
+ //Nhận tiền và Kết thúc
+ StoreStart();
+ EndSession();
+
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ }
+ AppData.WDTCount++;
+ }
+ else
+ {
+ AppData.WDTCount = 0;
+ }
+ timer.IsEnabled = true;
+ }
+ catch (Exception)
+ {
+
+ }
+
+
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException("GetSensorValue", ex.ToString());
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ CountStart();
+ AppData.WDTCount = 0;
+ }
+
+ private void CountStart()
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ AppData.LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ AppData.LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ AppData.WDTCount = 0;
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ StoreStart();
+ AppData.WDTCount = 0;
+ }
+
+ private void StoreStart()
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ AppData.LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+ AppData.IsInTransaction= true;
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ AppData.LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+ AppData.WDTCount = 0;
+ }
+
+ private async void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ EndSession();
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+ try
+ {
+ AppData.LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ AppData.LogException(currentMethod, ex.ToString());
+ }
+
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify);
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ var history = Save2DB(data2Send);
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull = 0;
+ int IsNotesInEscrow = 0;
+ IsCassetteFull = data[17] & 0x08;
+ IsNotesInEscrow = data[4] & 0x01;
+
+ if (IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ AppData.LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ }
+}
+
diff --git a/.svn/pristine/45/45eca837e2bca4e00f1d36eeabd24f18ae74d7e7.svn-base b/.svn/pristine/45/45eca837e2bca4e00f1d36eeabd24f18ae74d7e7.svn-base
new file mode 100644
index 0000000..b0a8013
Binary files /dev/null and b/.svn/pristine/45/45eca837e2bca4e00f1d36eeabd24f18ae74d7e7.svn-base differ
diff --git a/.svn/pristine/46/460f34ccb98844dae059e8047c81f5a5dac9c47f.svn-base b/.svn/pristine/46/460f34ccb98844dae059e8047c81f5a5dac9c47f.svn-base
new file mode 100644
index 0000000..6783010
--- /dev/null
+++ b/.svn/pristine/46/460f34ccb98844dae059e8047c81f5a5dac9c47f.svn-base
@@ -0,0 +1,840 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+ public class CountSession
+ {
+ public CountSession() {
+ for(int i= 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ }
+
+ public partial class MainUserWindow : HandyControl.Controls.Window
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+ public MainUserWindow()
+ {
+ //Need to update: auto detect COM Port
+ try
+ {
+ InitializeComponent();
+ //string queuePath = ConfigurationManager.AppSettings["SensorPort"].ToString();
+ AppData.Init();
+ //this.gridMain.IsEnabled = false;
+
+
+ InitApp();
+
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ //MessageBox.Show("Cổng đang mở, kiểm tra lại cổng kết nối");
+ //this.Close();
+ }
+ }
+ public void InitApp()
+ {
+ LoginUsingQRCode();
+ panelError.Visibility = Visibility.Collapsed;
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+
+ //Subscrible to the DataReveied event
+
+ serialPortDE70.Open();
+ serialPortSensor.Open();
+
+ bInitialized = InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //10 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void ShutdownApp()
+ {
+ try
+ {
+ if (serialPortDE70.IsOpen)
+ serialPortDE70.Close();
+ if (serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ lvCountItems.Clear();
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+ int state = 0;
+ if (serialPortSensor.IsOpen==true)
+ {
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1]-48;
+ if(bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "Két: đóng, Túi: đóng";
+ break;
+ case 1:
+ lblStatus.Content = "Két: đóng, Túi: đã bị lấy ra";
+ break;
+ case 2:
+ lblStatus.Content = "Két: mở, Túi: đóng";
+ break;
+ case 3:
+ lblStatus.Content = "Két: mở, Túi: đã bị lấy ra";
+ break;
+ }
+ break;
+ }
+ }
+
+ }
+
+ timer.IsEnabled = true;
+ }
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+ var str = JsonConvert.SerializeObject(data2Send);
+
+ APIModels.SendCountingData(data2Send);
+ //Reset all and ready to next session
+
+ if(printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ LoginUsingQRCode();
+
+ }
+ private void ShowError(string strError)
+ {
+ gridMain.IsEnabled = false;
+ btnCollect2.Visibility=Visibility.Collapsed;
+ panelError.Visibility = Visibility.Visible;
+ lblError.Text = strError;
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull=data[17] & 0x08;
+ if(IsCassetteFull != 0)
+ {
+ ShowError("TÚI ĐẦY, ĐỀ NGHỊ LẤY TÚI TRƯỚC KHI TIẾP TỤC THAO TÁC");
+ btnCollect2.Visibility=Visibility.Visible;
+ return false;
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60));
+ e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90));
+ e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120));
+ e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150));
+ e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180));
+ e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210));
+ e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270));
+ e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ public void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ private void LoginUsingQRCode()
+ {
+ var wnd = new WelcomeWindow();
+ wnd.ShowDialog();
+
+ lblUser.Content = "";
+ //var wnd = new QRCodeZebraWindow();
+ //wnd.ShowDialog();
+ if (wnd.DialogResult == true)
+ {
+ var strQR = wnd.QRCodeContent;
+ var strPincode = wnd.PinCode;
+ if (AppData.customerAccounts!=null)
+ {
+ CustomerAccount? cca = null;
+ if(strQR!=null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == strQR).FirstOrDefault();
+ }
+ else if(strPincode!=null)
+ {
+ strPincode = strPincode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.CurrentCustomerAccount = cca;
+ lblUser.Content = $"Xin chào khách hàng: {cca.Name} (Gian hàng {cca.CustomerId})";
+ }
+ else
+ {
+ MessageBox.Show("QRCode không đúng, vui lòng thử lại");
+ LoginUsingQRCode();
+ }
+ }
+ }
+ }
+
+ private void btnLoginByPINCode_Click(object sender, RoutedEventArgs e)
+ {
+ var wnd = new PinCodeWindow();
+ wnd.ShowDialog();
+ }
+
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ ShowError("Khởi tạo bộ đếm thành công");
+ ShutdownApp();
+ InitApp();
+ }
+ //Thread.Sleep(5000);
+ //cCmdRsp.GetLockParam().mode = currentMode;
+ //cCmdRsp.SendLock();
+ }
+ }
+}
+
diff --git a/.svn/pristine/46/461456e746607380b127562b31300342880b8d65.svn-base b/.svn/pristine/46/461456e746607380b127562b31300342880b8d65.svn-base
new file mode 100644
index 0000000..6bfd15b
--- /dev/null
+++ b/.svn/pristine/46/461456e746607380b127562b31300342880b8d65.svn-base
@@ -0,0 +1,32 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class ErrorUC : UserControl
+ {
+ public ErrorUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor)
+ {
+ lblError.Text = strInfor;
+ }
+ }
+}
diff --git a/.svn/pristine/46/46408917d2f42e6a38715a2e64f7e3e11fecc71f.svn-base b/.svn/pristine/46/46408917d2f42e6a38715a2e64f7e3e11fecc71f.svn-base
new file mode 100644
index 0000000..b581567
--- /dev/null
+++ b/.svn/pristine/46/46408917d2f42e6a38715a2e64f7e3e11fecc71f.svn-base
@@ -0,0 +1,223 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeUC : UserControl
+ {
+ public string? QRCodeContent = null;
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeUC()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ Loaded += WelcomeUC_Loaded;
+ }
+
+ private void WelcomeUC_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.IsAuthenticated = false;
+ }
+
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ string pin = PinCodeBox.Password;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Password.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.IsAuthenticated=true;
+ AppData.CurrentCustomerAccount=cca;
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Help clicked.");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ {
+ UseShellExecute = true
+ };
+ Process.Start(onScreenKeyboardProcess);
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ QRCodeContent = HexStringToString(rawDataHex);
+ this.Dispatcher.Invoke(() =>
+ {
+
+
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (QRCodeContent != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ AppData.IsAuthenticated = true;
+ AppData.CurrentCustomerAccount = cca;
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/46/46bf69b9c1cc6ed234d3a7ad918f9a715e7f7d4b.svn-base b/.svn/pristine/46/46bf69b9c1cc6ed234d3a7ad918f9a715e7f7d4b.svn-base
new file mode 100644
index 0000000..67d8e41
--- /dev/null
+++ b/.svn/pristine/46/46bf69b9c1cc6ed234d3a7ad918f9a715e7f7d4b.svn-base
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/4b/4b15bcf1fb2ca5b8ccc6b9964f55c1c3d6ee1258.svn-base b/.svn/pristine/4b/4b15bcf1fb2ca5b8ccc6b9964f55c1c3d6ee1258.svn-base
new file mode 100644
index 0000000..adbb543
--- /dev/null
+++ b/.svn/pristine/4b/4b15bcf1fb2ca5b8ccc6b9964f55c1c3d6ee1258.svn-base
@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace VirtualKeyboard.Wpf.Views
+{
+ ///
+ /// Logika interakcji dla klasy KeyboardValueView.xaml
+ ///
+ partial class KeyboardValueView : UserControl
+ {
+ public KeyboardValueView()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/.svn/pristine/4c/4ca475c14f83196c7e0ca38ddfa6442e8a0a5533.svn-base b/.svn/pristine/4c/4ca475c14f83196c7e0ca38ddfa6442e8a0a5533.svn-base
new file mode 100644
index 0000000..5237b71
--- /dev/null
+++ b/.svn/pristine/4c/4ca475c14f83196c7e0ca38ddfa6442e8a0a5533.svn-base
@@ -0,0 +1,229 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeUC : UserControl
+ {
+ public string? QRCodeContent = null;
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeUC()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ Loaded += WelcomeUC_Loaded;
+ }
+
+ private void WelcomeUC_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.IsAuthenticated = false;
+ }
+ public void Init()
+ {
+ AppData.IsAuthenticated = false;
+ AppData.CurrentCustomerAccount = null;
+ lblPincodeError.Content = "";
+ PinCodeBox.Text = "";
+ }
+
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ string pin = PinCodeBox.Text;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Text.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.IsAuthenticated=true;
+ AppData.CurrentCustomerAccount=cca;
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Help clicked.");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ {
+ UseShellExecute = true
+ };
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ QRCodeContent = HexStringToString(rawDataHex);
+ this.Dispatcher.Invoke(() =>
+ {
+
+
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (QRCodeContent != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ AppData.IsAuthenticated = true;
+ AppData.CurrentCustomerAccount = cca;
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/4d/4d556d32fb18f03364703fc77982f83a1ad726c2.svn-base b/.svn/pristine/4d/4d556d32fb18f03364703fc77982f83a1ad726c2.svn-base
new file mode 100644
index 0000000..ab77790
--- /dev/null
+++ b/.svn/pristine/4d/4d556d32fb18f03364703fc77982f83a1ad726c2.svn-base
@@ -0,0 +1,81 @@
+#pragma checksum "..\..\..\..\Views\KeyboardValueView.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7CEB2F6BE0031A78F4843553F03A6F9656DD4608"
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Controls.Ribbon;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Ink;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Media.Effects;
+using System.Windows.Media.Imaging;
+using System.Windows.Media.Media3D;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Windows.Shell;
+using VirtualKeyboard.Wpf.Controls;
+using VirtualKeyboard.Wpf.Views;
+
+
+namespace VirtualKeyboard.Wpf.Views {
+
+
+ internal partial class KeyboardValueView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
+
+ private bool _contentLoaded;
+
+ ///
+ /// InitializeComponent
+ ///
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ public void InitializeComponent() {
+ if (_contentLoaded) {
+ return;
+ }
+ _contentLoaded = true;
+ System.Uri resourceLocater = new System.Uri("/VirtualKeyboard;component/views/keyboardvalueview.xaml", System.UriKind.Relative);
+
+ #line 1 "..\..\..\..\Views\KeyboardValueView.xaml"
+ System.Windows.Application.LoadComponent(this, resourceLocater);
+
+ #line default
+ #line hidden
+ }
+
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal System.Delegate _CreateDelegate(System.Type delegateType, string handler) {
+ return System.Delegate.CreateDelegate(delegateType, this, handler);
+ }
+
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
+ void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
+ this._contentLoaded = true;
+ }
+ }
+}
+
diff --git a/.svn/pristine/4d/4d5bd5be245efb453f8104314c5d90dd4d983fd4.svn-base b/.svn/pristine/4d/4d5bd5be245efb453f8104314c5d90dd4d983fd4.svn-base
new file mode 100644
index 0000000..c69e952
--- /dev/null
+++ b/.svn/pristine/4d/4d5bd5be245efb453f8104314c5d90dd4d983fd4.svn-base
@@ -0,0 +1,46 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for AdminLoginUC.xaml
+ ///
+ public partial class AdminLoginUC : UserControl
+ {
+ public AdminLoginUC()
+ {
+ InitializeComponent();
+ }
+
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+ string username = UsernameTextBox.Text;
+ string password = PasswordBox.Password;
+
+ // Simple authentication logic
+ if (username == "admin" && password == "password") // Replace with actual logic
+ {
+ // Load Settings UserControl
+ var mainWindow = (MainWindow)Window.GetWindow(this);
+ //mainWindow.LoadUserControl(new SettingsUserControl());
+ }
+ else
+ {
+ MessageBox.Show("Invalid username or password.", "Login Failed", MessageBoxButton.OK, MessageBoxImage.Error);
+ }
+ }
+ }
+}
diff --git a/.svn/pristine/4d/4dd3cf11b49e7815e0d6f82d9d1459ac82108123.svn-base b/.svn/pristine/4d/4dd3cf11b49e7815e0d6f82d9d1459ac82108123.svn-base
new file mode 100644
index 0000000..a1b1af6
--- /dev/null
+++ b/.svn/pristine/4d/4dd3cf11b49e7815e0d6f82d9d1459ac82108123.svn-base
@@ -0,0 +1,86 @@
+using DE70_CMDv2;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ }
+ private static DateTime CutOffTime = new DateTime(1, 1, 1, 12, 0, 0); // 12:00 noon as cut-off time
+
+ public static void GetNewTransactionCode()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+}
diff --git a/.svn/pristine/4f/4f6fcf75f064d36c1950f57f34cc19414aa7e78c.svn-base b/.svn/pristine/4f/4f6fcf75f064d36c1950f57f34cc19414aa7e78c.svn-base
new file mode 100644
index 0000000..9879346
Binary files /dev/null and b/.svn/pristine/4f/4f6fcf75f064d36c1950f57f34cc19414aa7e78c.svn-base differ
diff --git a/.svn/pristine/4f/4f9618265457e64f077b4c0414da01814b3cac75.svn-base b/.svn/pristine/4f/4f9618265457e64f077b4c0414da01814b3cac75.svn-base
new file mode 100644
index 0000000..d9e842c
--- /dev/null
+++ b/.svn/pristine/4f/4f9618265457e64f077b4c0414da01814b3cac75.svn-base
@@ -0,0 +1,60 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/4f/4fb95050fe0a88f45edd5afed1a3ba5383a5f9a6.svn-base b/.svn/pristine/4f/4fb95050fe0a88f45edd5afed1a3ba5383a5f9a6.svn-base
new file mode 100644
index 0000000..7e6b0ad
--- /dev/null
+++ b/.svn/pristine/4f/4fb95050fe0a88f45edd5afed1a3ba5383a5f9a6.svn-base
@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70.StateMachine
+{
+ public class StateMachineConfig
+ {
+ public List States { get; set; }
+ public List Transitions { get; set; }
+ public Dictionary Actions { get; set; }
+ }
+}
diff --git a/.svn/pristine/50/5051351613cd3e44b904ac7a0d0460a38746fb7b.svn-base b/.svn/pristine/50/5051351613cd3e44b904ac7a0d0460a38746fb7b.svn-base
new file mode 100644
index 0000000..8a1a2c8
--- /dev/null
+++ b/.svn/pristine/50/5051351613cd3e44b904ac7a0d0460a38746fb7b.svn-base
@@ -0,0 +1,100 @@
+using CoreScanner;
+using SafeBagDE70.Model;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Windows.Threading;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for QRCodeWindow.xaml
+ ///
+ public partial class QRCodeZebraWindow : HandyControl.Controls.Window
+ {
+
+ public string QRCodeContent = null;
+ public CCoreScannerClass cCoreScannerClass;
+ public QRCodeZebraWindow()
+ {
+ InitializeComponent();
+ Init();
+ }
+ public void Init()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ QRCodeContent = HexStringToString(rawDataHex);
+ this.Dispatcher.Invoke(() =>
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ DialogResult = true;
+ this.Close();
+ });
+ }
+
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+
+ }
+}
diff --git a/.svn/pristine/53/53aff25d0a3414e7bc6580936fd9da9dd677fba0.svn-base b/.svn/pristine/53/53aff25d0a3414e7bc6580936fd9da9dd677fba0.svn-base
new file mode 100644
index 0000000..d7bf525
Binary files /dev/null and b/.svn/pristine/53/53aff25d0a3414e7bc6580936fd9da9dd677fba0.svn-base differ
diff --git a/.svn/pristine/53/53f0d81cceb51490143379f84b26bd5f50fcad64.svn-base b/.svn/pristine/53/53f0d81cceb51490143379f84b26bd5f50fcad64.svn-base
new file mode 100644
index 0000000..ef299f2
Binary files /dev/null and b/.svn/pristine/53/53f0d81cceb51490143379f84b26bd5f50fcad64.svn-base differ
diff --git a/.svn/pristine/54/54144da3d27eabd3bc873561c2f5469a540f006e.svn-base b/.svn/pristine/54/54144da3d27eabd3bc873561c2f5469a540f006e.svn-base
new file mode 100644
index 0000000..dc7334d
--- /dev/null
+++ b/.svn/pristine/54/54144da3d27eabd3bc873561c2f5469a540f006e.svn-base
@@ -0,0 +1,62 @@
+using HandyControl.Tools.Extension;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for AdminWindow.xaml
+ ///
+ public partial class AdminWindow : HandyControl.Controls.Window
+ {
+ LogViewerUC loguc;
+ AdminConfigurationUC configuration;
+ public AdminWindow()
+ {
+ InitializeComponent();
+ loguc= new LogViewerUC(AppData.logCollection);
+ configuration = new AdminConfigurationUC();
+ this.MainContentControl.Content = loguc;
+ }
+ private void LogoutButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void UserManagementButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void DashboardButton_Click(object sender, RoutedEventArgs e)
+ {
+ this.MainContentControl.Content = loguc;
+ }
+
+ private void SettingsButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void ReportsButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ }
+
+ private void ConfigurationButton_Click(object sender, RoutedEventArgs e)
+ {
+ this.MainContentControl.Content = configuration;
+ }
+ }
+}
diff --git a/.svn/pristine/54/54ae5b35415a1dfdf99f46165e368ca021e51377.svn-base b/.svn/pristine/54/54ae5b35415a1dfdf99f46165e368ca021e51377.svn-base
new file mode 100644
index 0000000..4eacc7f
Binary files /dev/null and b/.svn/pristine/54/54ae5b35415a1dfdf99f46165e368ca021e51377.svn-base differ
diff --git a/.svn/pristine/55/55ca75934714f40c661f38c905bd175d6bf934e3.svn-base b/.svn/pristine/55/55ca75934714f40c661f38c905bd175d6bf934e3.svn-base
new file mode 100644
index 0000000..9d94061
--- /dev/null
+++ b/.svn/pristine/55/55ca75934714f40c661f38c905bd175d6bf934e3.svn-base
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/56/566d4b6bb2c3646396e1495315a0656fbdf03d20.svn-base b/.svn/pristine/56/566d4b6bb2c3646396e1495315a0656fbdf03d20.svn-base
new file mode 100644
index 0000000..3f1e0a2
--- /dev/null
+++ b/.svn/pristine/56/566d4b6bb2c3646396e1495315a0656fbdf03d20.svn-base
@@ -0,0 +1,9 @@
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\GeneratedInternalTypeHelper.g.cs
+
+FD:\SRC\VirtualKeyboard\DefaultKeyboardHost.xaml;;
+FD:\SRC\VirtualKeyboard\ResourceDictionaries\KeyboardCore.xaml;;
+FD:\SRC\VirtualKeyboard\Views\AlphabetView.xaml;;
+FD:\SRC\VirtualKeyboard\Views\KeyboardValueView.xaml;;
+FD:\SRC\VirtualKeyboard\Views\SpecialCharactersView.xaml;;
+FD:\SRC\VirtualKeyboard\Views\VirtualKeyboardView.xaml;;
+
diff --git a/.svn/pristine/56/56bd7b1d5800299bb481d40f6e03509df3155e6c.svn-base b/.svn/pristine/56/56bd7b1d5800299bb481d40f6e03509df3155e6c.svn-base
new file mode 100644
index 0000000..164674b
--- /dev/null
+++ b/.svn/pristine/56/56bd7b1d5800299bb481d40f6e03509df3155e6c.svn-base
@@ -0,0 +1,230 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeUC : UserControl
+ {
+ public string? QRCodeContent = null;
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeUC()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ Loaded += WelcomeUC_Loaded;
+ }
+
+ private void WelcomeUC_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.IsAuthenticated = false;
+ }
+ public void Init()
+ {
+ AppData.IsAuthenticated = false;
+ AppData.CurrentCustomerAccount = null;
+ lblPincodeError.Content = "";
+ PinCodeBox.Text = "";
+ }
+
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ string pin = PinCodeBox.Text;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Text.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.IsAuthenticated=true;
+ AppData.CurrentCustomerAccount=cca;
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Help clicked.");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ {
+ UseShellExecute = true
+ };
+ Process.Start(onScreenKeyboardProcess);
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ QRCodeContent = HexStringToString(rawDataHex);
+ this.Dispatcher.Invoke(() =>
+ {
+
+
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (QRCodeContent != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ AppData.IsAuthenticated = true;
+ AppData.CurrentCustomerAccount = cca;
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/57/5709dc67df84b1bead58cbb9a9b902f39c7a6dda.svn-base b/.svn/pristine/57/5709dc67df84b1bead58cbb9a9b902f39c7a6dda.svn-base
new file mode 100644
index 0000000..ccfadbd
--- /dev/null
+++ b/.svn/pristine/57/5709dc67df84b1bead58cbb9a9b902f39c7a6dda.svn-base
@@ -0,0 +1,769 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositUC : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+ public DepositUC()
+ {
+ InitializeComponent();
+
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ try
+ {
+ InitApp();
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+ }
+ public void InitApp()
+ {
+ // LoginUsingQRCode();
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+
+ serialPortDE70.PortName = "COM4";
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+
+ serialPortSensor.PortName = "COM3";
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+
+ //Subscrible to the DataReveied event
+ if(!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+
+ bInitialized = InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //10 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void ShutdownApp()
+ {
+ try
+ {
+ if (serialPortDE70.IsOpen)
+ serialPortDE70.Close();
+ if (serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ lvCountItems.Clear();
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+ int state = 0;
+ if (serialPortSensor.IsOpen==true)
+ {
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1]-48;
+ if(bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "Két: đóng, Túi: đóng";
+ break;
+ case 1:
+ lblStatus.Content = "Két: đóng, Túi: đã bị lấy ra";
+ break;
+ case 2:
+ lblStatus.Content = "Két: mở, Túi: đóng";
+ break;
+ case 3:
+ lblStatus.Content = "Két: mở, Túi: đã bị lấy ra";
+ break;
+ }
+ break;
+ }
+ }
+
+ }
+
+ timer.IsEnabled = true;
+ }
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[11].Quantity;
+
+
+ try
+ {
+ LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+ var str = JsonConvert.SerializeObject(data2Send);
+
+ APIModels.SendCountingData(data2Send);
+ //Reset all and ready to next session
+
+ if(printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify);
+ }
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull=data[17] & 0x08;
+ if(IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60));
+ e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90));
+ e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120));
+ e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150));
+ e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180));
+ e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210));
+ e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270));
+ e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ public void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ private void LoginUsingQRCode()
+ {
+
+ }
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ ShowError("Khởi tạo bộ đếm thành công");
+ // ShutdownApp();
+ // InitApp();
+ }
+ //Thread.Sleep(5000);
+ //cCmdRsp.GetLockParam().mode = currentMode;
+ //cCmdRsp.SendLock();
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ ShutdownApp();
+ }
+ }
+}
+
diff --git a/.svn/pristine/57/57ff3059ab75d23e346d0ef5d1d889f457cf0225.svn-base b/.svn/pristine/57/57ff3059ab75d23e346d0ef5d1d889f457cf0225.svn-base
new file mode 100644
index 0000000..52f90d7
--- /dev/null
+++ b/.svn/pristine/57/57ff3059ab75d23e346d0ef5d1d889f457cf0225.svn-base
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/58/586033252023dee1b2648673d2f1edcba8aa5f2e.svn-base b/.svn/pristine/58/586033252023dee1b2648673d2f1edcba8aa5f2e.svn-base
new file mode 100644
index 0000000..cf12d81
--- /dev/null
+++ b/.svn/pristine/58/586033252023dee1b2648673d2f1edcba8aa5f2e.svn-base
@@ -0,0 +1,344 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeUC : UserControl
+ {
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeUC()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ Loaded += WelcomeUC_Loaded;
+ }
+
+ private void WelcomeUC_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.IsAuthenticated = false;
+ txtVersion.Text = "Version " + AppData.CurrentVersion;
+ }
+ public void Init()
+ {
+ AppData.IsAuthenticated = false;
+ AppData.CurrentCustomerAccount = null;
+ lblPincodeError.Content = "";
+ PinCodeBox.Text = "";
+ }
+
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ string pin = PinCodeBox.Text;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Text.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.IsAuthenticated=true;
+ AppData.CurrentCustomerAccount=cca;
+ AppData.GetNewTransactionCode();
+ AppData.GetNewTransactionCode();
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Phiên bản đang sử dụng là phiên bản mới nhất");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ //var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ var QRCodeContentFull = HexStringToString(rawDataHex);
+ string? CustomerID = null;
+ VerifyQRCode(QRCodeContentFull, out CustomerID);
+ if(CustomerID!=null)
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (CustomerID != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == CustomerID).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ AppData.IsAuthenticated = true;
+ AppData.CurrentCustomerAccount = cca;
+ AppData.GetNewTransactionCode();
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ }
+ private void VerifyQRCode(string decodedString,out string? ConsumerID)
+ {
+ ConsumerID = null;
+ try
+ {
+ var qrCodeData = decodedString;
+ // Extract the CRC from the QR code string
+ string extractedCRC = qrCodeData.Substring(qrCodeData.Length - 4);
+ // Get the data without the CRC part
+ string dataWithoutCRC = qrCodeData.Substring(0, qrCodeData.Length - 8);
+
+ // Calculate CRC
+ string calculatedCRC = CalculateCRC(dataWithoutCRC);
+
+ // Verify CRC
+ if (extractedCRC.Equals(calculatedCRC, StringComparison.OrdinalIgnoreCase))
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ lblQRcodeError.Content = "CRC is valid.";
+ });
+
+ Dictionary fields = ExtractFields(qrCodeData);
+
+ foreach (var field in fields)
+ {
+ Console.WriteLine($"ID: {field.Key}, Length: {field.Value.Length}, Value: {field.Value.Value}");
+ }
+ var fields2 = ExtractFields(fields["38"].Value);
+ var fields3 = ExtractFields(fields2["01"].Value);
+ ConsumerID = fields3["01"].Value;
+ }
+ else
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ lblQRcodeError.Content = "CRC is invalid.";
+ });
+
+ }
+
+
+ }
+ catch (Exception e)
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ lblQRcodeError.Content = e.Message;
+ });
+
+ }
+ }
+ Dictionary ExtractFields(string qrCodeData)
+ {
+ Dictionary fields = new Dictionary();
+
+ int currentIndex = 0;
+
+ while (currentIndex < qrCodeData.Length)
+ {
+ // Extract ID
+ string id = qrCodeData.Substring(currentIndex, 2);
+ currentIndex += 2;
+
+ // Extract Length
+ int length = int.Parse(qrCodeData.Substring(currentIndex, 2));
+ currentIndex += 2;
+
+ // Extract Value
+ string value = qrCodeData.Substring(currentIndex, length);
+ currentIndex += length;
+
+ // Add the field to the dictionary
+ fields[id] = (length, value);
+ }
+
+ return fields;
+ }
+ string CalculateCRC(string data)
+ {
+ ushort polynomial = 0x1021; // CRC-16-CCITT polynomial
+ ushort crc = 0xFFFF; // Initial value
+
+ // Convert the string to a byte array
+ byte[] bytes = Encoding.ASCII.GetBytes(data + "6304"); // Append "6304" for CRC calculation as per standard
+
+ foreach (byte b in bytes)
+ {
+ crc ^= (ushort)(b << 8);
+
+ for (int i = 0; i < 8; i++)
+ {
+ if ((crc & 0x8000) != 0)
+ {
+ crc = (ushort)((crc << 1) ^ polynomial);
+ }
+ else
+ {
+ crc <<= 1;
+ }
+ }
+ }
+
+ // Ensure CRC is a 16-bit value
+ crc &= 0xFFFF;
+
+ // Return CRC as a hexadecimal string
+ return crc.ToString("X4");
+ }
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/58/58c282a2e0073d29dae289a015874fd9c7b5b042.svn-base b/.svn/pristine/58/58c282a2e0073d29dae289a015874fd9c7b5b042.svn-base
new file mode 100644
index 0000000..7190955
--- /dev/null
+++ b/.svn/pristine/58/58c282a2e0073d29dae289a015874fd9c7b5b042.svn-base
@@ -0,0 +1,1165 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.StateMachine;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
+using System.Runtime.Intrinsics.Arm;
+using SafeBagDE70.Services;
+using System.Windows.Forms;
+using Button = System.Windows.Controls.Button;
+using UserControl = System.Windows.Controls.UserControl;
+using Application = System.Windows.Application;
+using Control = System.Windows.Controls.Control;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositSMUCv2 : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+ bool bOpenPort = true;
+ bool bIsMaintain = false;
+ MainWindow mainWindow = null;
+ public DepositSMUCv2()
+ {
+ InitializeComponent();
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ mainWindow=((MainWindow)Application.Current.MainWindow);
+ InitTransaction();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ lblName.Content= "Vietinbank " + Environment.MachineName;
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+
+ }
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+ AppData.IsInTransaction = true;
+ ResetButtons();
+ btnStart.IsEnabled = true;
+ ResetTimers();
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if(bOpenPort)
+ {
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+ if(bOpenPort)
+ {
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ }
+ DispatcherTimer? warningTimer = null;
+ DispatcherTimer? timeoutTimer = null;
+ private void InitTimers()
+ {
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ warningTimer = new DispatcherTimer(); // 30 seconds
+ warningTimer.Interval = new TimeSpan(0, 0, 30);
+ warningTimer.Tick += WarningTimer_Tick; ;
+
+ timeoutTimer = new DispatcherTimer(); // 60 seconds
+ timeoutTimer.Interval = new TimeSpan(0, 0, 60);
+ timeoutTimer.Tick += TimeoutTimer_Tick; ;
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ private void TimeoutTimer_Tick(object? sender, EventArgs e)
+ {
+ DoStoreStart();
+ DoEnd();
+ BackToWelcomeScreen();
+ }
+
+ private void BackToWelcomeScreen()
+ {
+ StopTimers();
+ var cdmState = GetCDMState();
+ if (cdmState.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ }
+
+ private void WarningTimer_Tick(object? sender, EventArgs e)
+ {
+
+ mainWindow.ShowTimeoutScreen();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ if (warningTimer != null)
+ {
+ warningTimer.Tick -=WarningTimer_Tick;
+ warningTimer.Stop();
+ }
+ if (timeoutTimer != null)
+ {
+ timeoutTimer.Tick -= TimeoutTimer_Tick;
+ timeoutTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+
+
+ public void InitLvCountItems()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ // public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ // public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ // public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+ public int countSensorTimer = 0;
+ //PrinterManager printerManager = new PrinterManager();
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ timer.IsEnabled = false;
+ GetSensorValue();
+ timer.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Sensor_Timer");
+ }
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ if (!bIsMaintain)
+ {
+ bIsMaintain = true;
+ DoMaintaince();
+ }
+
+ // TransitionToState("Maintainance");
+ }
+ else
+ {
+ if(bIsMaintain)
+ {
+ bIsMaintain = false;
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ }
+
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"GetSensorValue");
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+ private void DoMaintaince()
+ {
+ StopTimers();
+ ((MainWindow)Application.Current.MainWindow).ShowMaintainanceScreen();
+ }
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet()
+ {
+ try
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ var countSession = new CountSession();
+ countSession.IsStored = false;
+ sessions.Add(countSession);
+ while (true)
+ {
+ AppData.WDTCount = 0;
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ AppData.WDTCount = 0;
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: countSession.TempNotes[0]++;break;
+ case 0x02:
+ //TempNote[1] ++;
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}");
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ //case 0x00: TempQuantity[0]++; break;
+ //case 0x01: TempQuantity[1]++; break;
+ //case 0x02: TempQuantity[2]++; break;
+ //case 0x03: TempQuantity[3]++; break;
+ //case 0x04: TempQuantity[4]++; break;
+ //case 0x05: TempQuantity[5]++; break;
+ //case 0x06: TempQuantity[6]++; break;
+ //case 0x07: TempQuantity[7]++; break;
+ //case 0x08: TempQuantity[8]++; break;
+ //case 0x09: TempQuantity[9]++; break;
+
+ case 0x00: countSession.QuantityDenomi[0]++; break;
+ case 0x01: countSession.QuantityDenomi[1]++; break;
+ case 0x02: countSession.QuantityDenomi[2]++; break;
+ case 0x03: countSession.QuantityDenomi[3]++; break;
+ case 0x04: countSession.QuantityDenomi[4]++; break;
+ case 0x05: countSession.QuantityDenomi[5]++; break;
+ case 0x06: countSession.QuantityDenomi[6]++; break;
+ case 0x07: countSession.QuantityDenomi[7]++; break;
+ case 0x08: countSession.QuantityDenomi[8]++; break;
+ case 0x09: countSession.QuantityDenomi[9]++; break;
+
+ }
+ break;
+ //case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ //case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ //case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ case 0x03: countSession.TempNotes[2]++; break;
+ case 0x0b: countSession.TempNotes[3]++; break;
+ case 0x0c: countSession.TempNotes[4]++; break;
+ }
+ UpdateListViewCountItems();
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0)
+ {
+ sessions.Remove(countSession);
+ }
+ }catch(Exception ex)
+ {
+ Log.Fatal(ex, "AutoSerialGet");
+ }
+
+ //Log.Information(JsonConvert.SerializeObject(sessions));
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private bool CountStart()
+ {
+ bool bSuccess = true;
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+
+
+ if(bOpenPort)
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+ }
+
+
+ //SR3 = 0x43 : Stacker full
+ Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ Thread thread = new Thread(new ThreadStart(() =>
+ {
+ AutoSerialGet();
+
+ Dispatcher.Invoke(() =>
+ {
+ btnCountStart.IsEnabled = true;
+ btnCheck.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ ResetTimers();
+ Log.Information("2. Count completed");
+ });
+
+ }));
+ thread.Start();
+ Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex,currentMethod);
+ }
+ return bSuccess;
+ }
+
+ private void UpdateListViewCountItems()
+ {
+ Dispatcher.Invoke(DispatcherPriority.Normal, () =>
+ {
+ double sum = 0;
+ if (sessions != null && sessions.Count > 0)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ int quantity = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ quantity += sessions[j].QuantityDenomi[9 - i];
+
+ }
+ lvCountItems[i].Quantity = quantity.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+ }
+ else
+ {
+ for (int i = 0; i < 11; i++)
+ {
+ lvCountItems[i].Quantity = "0";
+ lvCountItems[i].Value = "0";
+ }
+ }
+ });
+
+ }
+
+ private bool DoCheck()
+ {
+ bool bSuccess = true;
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ sessions.RemoveAll(item=>!item.IsStored);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ UpdateListViewCountItems();
+
+
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+ private bool WaitUntilEnscrowEmpty(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while(true)
+ {
+ state = GetCDMState();
+ if (state.IsNotesInEscrow == 0)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool DoStoreStart()
+ {
+ bool bSuccess = true;
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ //sessions.Add(new CountSession());
+
+ // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ foreach(var item in sessions)
+ {
+ item.IsStored = true;
+ }
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored "+GetShortInforFromCountItems());
+ //Debug.WriteLine(quantityStored);
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ bSuccess=WaitUntilEnscrowEmpty(10);
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoStart()
+ {
+ bool bSuccess = true;
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoEnd()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ var lstEnabledControls = new List { btnEnd, btnCountStart };
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true,true, lstEnabledControls);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true, true, lstEnabledControls);
+ }
+ else
+ {
+ bSuccess = true;
+ AppData.WDTCount = 0;
+ EndSession();
+ }
+ return bSuccess;
+ }
+ private bool DoLogout()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ InitLvCountItems();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else //if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess = true;
+ EndSession();
+ BackToWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ if (double.Parse(totalValue) > 0)
+ {
+ var data2Send = new CountingData2Send
+ {
+ TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
+ Sessions = sessions,
+ MachineId = Environment.MachineName,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ //RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ //UnfitNotes = Notes[2],
+ //CounterfeitNotes = Notes[3],
+ // SuspendNotes = Notes[4]
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if (double.Parse(totalValue) > 0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify, false, false);
+ ResetSessions();
+ }
+ //SendData2Server
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, currentMethod);
+ }
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Save2DB Exception");
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Update2DB Exception");
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+ public class CDMSTATE
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ }
+ private CDMSTATE GetCDMState()
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv=cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ var cdmState = new CDMSTATE();
+
+ cdmState.IsCassetteFull = data[17] & 0x08;
+ cdmState.IsNotesInEscrow = data[4] & 0x01;
+ cdmState.IsRejectPocketFull = data[3] & 0x40;
+ cdmState.IsNotesInRejectPocket = data[3] & 0x10;
+ return cdmState;
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ ResetSessions();
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal(ex,"InitSession");
+ }
+ return false;
+ }
+
+ private void ResetSessions()
+ {
+ InitLvCountItems();
+ sessions.Clear();
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ }
+
+ private void PrintReceipt()
+ {
+ Log.Information("PrintReceipt");
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ public void ResetTimers()
+ {
+ StopTimers();
+ StartTimers();
+ }
+
+ public void StartTimers()
+ {
+ if(warningTimer!=null && timeoutTimer != null)
+ {
+ warningTimer.Start();
+ timeoutTimer.Start();
+ }
+
+ }
+
+ public void StopTimers()
+ {
+ if(warningTimer!=null && timeoutTimer!=null)
+ {
+ warningTimer.Stop();
+ timeoutTimer.Stop();
+ }
+
+ }
+
+ private void ResetButtons()
+ {
+ btnStart.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ btnLogout.IsEnabled = false;
+ }
+
+
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ SoundManager.StartButtonPressSound();
+ // Console.Beep(800, 200);
+ StopTimers();
+ bool bResult = false;
+ if (btn==btnStart)
+ {
+ Log.Information("Deposit starting");
+ Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ Log.Information("1. Start starting");
+ ResetButtons();
+ bResult = DoStart();
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("1. Start completed");
+ else
+ Log.Information("1. Start failed");
+ }
+ else if(btn==btnCountStart)
+ {
+
+ Log.Information("2. Count starting");
+ ResetButtons();
+ bResult = CountStart();
+ //Do in counting thread
+
+ }
+ else if(btn==btnCheck)
+ {
+ Log.Information($"3. Check starting");
+ ResetButtons();
+ bResult = DoCheck();
+ btnCountStart.IsEnabled= true;
+ ResetTimers();
+ if (bResult)
+ Log.Information($"3. Check completed");
+ else
+ Log.Information($"3. Check failed");
+ }
+ else if (btn == btnStoreStart)
+ {
+ //TransitionToState("Store");
+ Log.Information("4. Store starting");
+ ResetButtons();
+ bResult = DoStoreStart();
+ btnEnd.IsEnabled= true;
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("4. Store completed");
+ else
+ Log.Information("4. Store failed");
+ }
+ else if (btn == btnEnd)
+ {
+ // TransitionToState("End");
+ Log.Information("5. End starting");
+ ResetButtons();
+ bResult = DoEnd();
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+ ResetTimers();
+ if (bResult)
+ Log.Information("5. End Completed");
+ else
+ Log.Information("5. End failed");
+ }
+ else if (btn == btnLogout)
+ {
+ Log.Information("6. Exit starting");
+ bResult = DoLogout();
+ if (bResult)
+ Log.Information("6. Exit Completed");
+ else
+ Log.Information("6. Exit failed");
+ }
+ }
+
+
+ }
+}
+
diff --git a/.svn/pristine/58/58c95603005aa4988fb74c29dddcf1b6cde1dff4.svn-base b/.svn/pristine/58/58c95603005aa4988fb74c29dddcf1b6cde1dff4.svn-base
new file mode 100644
index 0000000..de1071f
--- /dev/null
+++ b/.svn/pristine/58/58c95603005aa4988fb74c29dddcf1b6cde1dff4.svn-base
@@ -0,0 +1,135 @@
+using System;
+using System.Collections.Generic;
+using System.ComponentModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using VirtualKeyboard.Wpf.Types;
+
+namespace VirtualKeyboard.Wpf.ViewModels
+{
+ class VirtualKeyboardViewModel : INotifyPropertyChanged
+ {
+ private string _keyboardText;
+ public string KeyboardText {
+ get => _keyboardText;
+ set
+ {
+ _keyboardText = value;
+ NotifyPropertyChanged(nameof(KeyboardText));
+ }
+ }
+ private KeyboardType _keyboardType;
+ public KeyboardType KeyboardType {
+ get => _keyboardType;
+ private set
+ {
+ _keyboardType = value;
+ NotifyPropertyChanged(nameof(KeyboardType));
+ }
+ }
+ private bool _uppercase;
+ public bool Uppercase
+ {
+ get => _uppercase;
+ private set
+ {
+ _uppercase = value;
+ NotifyPropertyChanged(nameof(Uppercase));
+ }
+ }
+ private int _caretPosition;
+ public int CaretPosition
+ {
+ get => _caretPosition;
+ set
+ {
+ if (value < 0) _caretPosition = 0;
+ else if (value > KeyboardText.Length) _caretPosition = KeyboardText.Length;
+ else _caretPosition = value;
+ NotifyPropertyChanged(nameof(CaretPosition));
+ }
+ }
+ private string _selectedValue;
+ public string SelectedValue
+ {
+ get => _selectedValue;
+ set
+ {
+ _selectedValue = value;
+ NotifyPropertyChanged(nameof(SelectedValue));
+ }
+ }
+ public Command AddCharacter { get; }
+ public Command ChangeCasing { get; }
+ public Command RemoveCharacter { get; }
+ public Command ChangeKeyboardType { get; }
+ public Command Accept { get; }
+
+ public VirtualKeyboardViewModel(string initialValue)
+ {
+ _keyboardText = initialValue;
+ _keyboardType = KeyboardType.Alphabet;
+ _uppercase = false;
+ CaretPosition = _keyboardText.Length;
+
+ AddCharacter = new Command(a =>
+ {
+ if (a is string character)
+ if (character.Length == 1)
+ {
+ if (Uppercase) character = character.ToUpper();
+ if (!string.IsNullOrEmpty(SelectedValue))
+ {
+ RemoveSubstring(SelectedValue);
+ KeyboardText = KeyboardText.Insert(CaretPosition, character);
+ CaretPosition++;
+ SelectedValue = "";
+ }
+ else
+ {
+ KeyboardText = KeyboardText.Insert(CaretPosition, character);
+ CaretPosition++;
+ }
+ }
+ });
+ ChangeCasing = new Command(a => Uppercase = !Uppercase);
+ RemoveCharacter = new Command(a =>
+ {
+ if(!string.IsNullOrEmpty(SelectedValue))
+ {
+ RemoveSubstring(SelectedValue);
+ }
+ else
+ {
+ var position = CaretPosition - 1;
+ if (position >= 0)
+ {
+ KeyboardText = KeyboardText.Remove(position, 1);
+ if (position < KeyboardText.Length) CaretPosition--;
+ else CaretPosition = KeyboardText.Length;
+ }
+ }
+ });
+ ChangeKeyboardType = new Command(a =>
+ {
+ if (KeyboardType == KeyboardType.Alphabet) KeyboardType = KeyboardType.Special;
+ else KeyboardType = KeyboardType.Alphabet;
+ });
+ Accept = new Command(a => VKeyboard.Close());
+ }
+
+ private void RemoveSubstring(string substring)
+ {
+ var position = KeyboardText.IndexOf(substring);
+ KeyboardText = KeyboardText.Remove(position, substring.Length);
+ }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+
+ private void NotifyPropertyChanged(string prop)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
+ }
+ }
+}
diff --git a/.svn/pristine/5a/5abe7bc53ee8aa25ea289af0b49974cf589b3d30.svn-base b/.svn/pristine/5a/5abe7bc53ee8aa25ea289af0b49974cf589b3d30.svn-base
new file mode 100644
index 0000000..7f73672
--- /dev/null
+++ b/.svn/pristine/5a/5abe7bc53ee8aa25ea289af0b49974cf589b3d30.svn-base
@@ -0,0 +1,65 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/5c/5c407fa9f9094d9a109ad11cccfc569e69c4edf0.svn-base b/.svn/pristine/5c/5c407fa9f9094d9a109ad11cccfc569e69c4edf0.svn-base
new file mode 100644
index 0000000..d012c18
--- /dev/null
+++ b/.svn/pristine/5c/5c407fa9f9094d9a109ad11cccfc569e69c4edf0.svn-base
@@ -0,0 +1,104 @@
+using System.IO;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json.Nodes;
+using System.Text;
+using System.Net.NetworkInformation;
+using System.Linq;
+using System;
+using System.Windows.Documents;
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+using Newtonsoft.Json;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70.API
+{
+ public static class APIModels
+ {
+ public static string URL = "https://203.171.20.94:9090/Safebag/";
+ public static async void SendHealthCheck(string? ID=null)
+ {
+ try
+ {
+ if (ID == null) ID = GetMACAddress();
+ 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);
+ using HttpResponseMessage response = await httpClient.GetAsync(URL + "HealthCheck?Id=" + ID);
+
+ if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
+ {
+ var jsonResponse = await response.Content.ReadAsStringAsync();
+ }
+ }
+ catch(Exception ex)
+ {
+
+ }
+
+ }
+
+ public static async Task SendCountingData(CountingData2Send data2Send)
+ {
+ bool bSuccess=false;
+ try{
+ 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(data2Send);
+ var content = new StringContent(strJsonObj, Encoding.UTF8, "application/json");
+
+ using HttpResponseMessage response = await httpClient.PostAsync(URL + "UpdateCountingData", content);
+
+ if (response.EnsureSuccessStatusCode().StatusCode == HttpStatusCode.OK)
+ {
+ var jsonResponse = await response.Content.ReadAsStringAsync();
+ bSuccess = true;
+ }
+ }
+ catch(Exception ex)
+ {
+
+ }
+ return bSuccess;
+
+ }
+
+
+
+ private static string GetMACAddress()
+ {
+ string? MACAdress = null;
+ foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
+ {
+ if (nic.OperationalStatus == OperationalStatus.Up)
+ {
+ MACAdress = AddressBytesToString(nic.GetPhysicalAddress().GetAddressBytes());
+ break;
+ }
+ }
+ if (MACAdress == null) MACAdress = "N/A";
+ return MACAdress;
+ }
+
+ private static string? AddressBytesToString(byte[] addressBytes)
+ {
+ if (addressBytes != null)
+ {
+ var str = string.Join(":", (from b in addressBytes
+ select b.ToString("X2")).ToArray());
+ return str;
+ }
+ else
+ return null;
+
+ }
+ }
+
+
+}
diff --git a/.svn/pristine/5c/5cda623ea7bc285aeac5680a29a0c11554f341b6.svn-base b/.svn/pristine/5c/5cda623ea7bc285aeac5680a29a0c11554f341b6.svn-base
new file mode 100644
index 0000000..0ef07db
Binary files /dev/null and b/.svn/pristine/5c/5cda623ea7bc285aeac5680a29a0c11554f341b6.svn-base differ
diff --git a/.svn/pristine/5d/5d79ce5bdc4d7d9d0c9cfbcbdb243e777787bdfc.svn-base b/.svn/pristine/5d/5d79ce5bdc4d7d9d0c9cfbcbdb243e777787bdfc.svn-base
new file mode 100644
index 0000000..7e224d7
--- /dev/null
+++ b/.svn/pristine/5d/5d79ce5bdc4d7d9d0c9cfbcbdb243e777787bdfc.svn-base
@@ -0,0 +1,821 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+ public class CountSession
+ {
+ public int[] QuantityDenomi { get; set; }
+ public int[] SumDenomi { get; set; }
+
+ }
+
+ public class CountingData2Send
+ {
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ }
+
+ public partial class MainUserWindow : HandyControl.Controls.Window
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+ public MainUserWindow()
+ {
+ //Need to update: auto detect COM Port
+ try
+ {
+ InitializeComponent();
+ //string queuePath = ConfigurationManager.AppSettings["SensorPort"].ToString();
+ AppData.Init();
+ //this.gridMain.IsEnabled = false;
+
+
+ InitApp();
+
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ //MessageBox.Show("Cổng đang mở, kiểm tra lại cổng kết nối");
+ //this.Close();
+ }
+ }
+ public void InitApp()
+ {
+ LoginUsingQRCode();
+ panelError.Visibility = Visibility.Collapsed;
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+
+ serialPortDE70.PortName = "COM4";
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+
+ serialPortSensor.PortName = "COM3";
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+
+ //Subscrible to the DataReveied event
+
+ serialPortDE70.Open();
+ serialPortSensor.Open();
+
+ bInitialized = InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //10 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void ShutdownApp()
+ {
+ try
+ {
+ if (serialPortDE70.IsOpen)
+ serialPortDE70.Close();
+ if (serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ lvCountItems.Clear();
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+ int state = 0;
+ if (serialPortSensor.IsOpen==true)
+ {
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1]-48;
+ if(bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "Két: đóng, Túi: đóng";
+ break;
+ case 1:
+ lblStatus.Content = "Két: đóng, Túi: đã bị lấy ra";
+ break;
+ case 2:
+ lblStatus.Content = "Két: mở, Túi: đóng";
+ break;
+ case 3:
+ lblStatus.Content = "Két: mở, Túi: đã bị lấy ra";
+ break;
+ }
+ break;
+ }
+ }
+
+ }
+
+ timer.IsEnabled = true;
+ }
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+ var str = JsonConvert.SerializeObject(data2Send);
+
+ APIModels.SendCountingData(data2Send);
+ //Reset all and ready to next session
+
+ if(printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ LoginUsingQRCode();
+
+ }
+ private void ShowError(string strError)
+ {
+ gridMain.IsEnabled = false;
+ btnCollect2.Visibility=Visibility.Collapsed;
+ panelError.Visibility = Visibility.Visible;
+ lblError.Text = strError;
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull=data[17] & 0x08;
+ if(IsCassetteFull != 0)
+ {
+ ShowError("TÚI ĐẦY, ĐỀ NGHỊ LẤY TÚI TRƯỚC KHI TIẾP TỤC THAO TÁC");
+ btnCollect2.Visibility=Visibility.Visible;
+ return false;
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60));
+ e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90));
+ e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120));
+ e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150));
+ e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180));
+ e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210));
+ e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270));
+ e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ public void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ private void LoginUsingQRCode()
+ {
+ var wnd = new WelcomeWindow();
+ wnd.ShowDialog();
+
+ lblUser.Content = "";
+ //var wnd = new QRCodeZebraWindow();
+ //wnd.ShowDialog();
+ if (wnd.DialogResult == true)
+ {
+ var strQR = wnd.QRCodeContent;
+ var strPincode = wnd.PinCode;
+ if (AppData.customerAccounts!=null)
+ {
+ CustomerAccount? cca = null;
+ if(strQR!=null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == strQR).FirstOrDefault();
+ }
+ else if(strPincode!=null)
+ {
+ strPincode = strPincode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.CurrentCustomerAccount = cca;
+ lblUser.Content = $"Xin chào khách hàng: {cca.Name} (Gian hàng {cca.CustomerId})";
+ }
+ else
+ {
+ MessageBox.Show("QRCode không đúng, vui lòng thử lại");
+ LoginUsingQRCode();
+ }
+ }
+ }
+ }
+
+ private void btnLoginByPINCode_Click(object sender, RoutedEventArgs e)
+ {
+ var wnd = new PinCodeWindow();
+ wnd.ShowDialog();
+ }
+
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ ShowError("Khởi tạo bộ đếm thành công");
+ ShutdownApp();
+ InitApp();
+ }
+ //Thread.Sleep(5000);
+ //cCmdRsp.GetLockParam().mode = currentMode;
+ //cCmdRsp.SendLock();
+ }
+ }
+}
+
diff --git a/.svn/pristine/60/605b2c7de045947c1749ba9c7082564e09a34b2c.svn-base b/.svn/pristine/60/605b2c7de045947c1749ba9c7082564e09a34b2c.svn-base
new file mode 100644
index 0000000..94c6105
--- /dev/null
+++ b/.svn/pristine/60/605b2c7de045947c1749ba9c7082564e09a34b2c.svn-base
@@ -0,0 +1,44 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70
+{
+ static public class DE70Commands
+ {
+ //public static string ReadyToCountResponse = "40 07 41 00 01 00 00 00 00 00 00 10 00";
+ public static string CountingResponse = "40 09 41 01 01 00 00 00 00 00 00 10 00";
+ public static string ExceptionResponse = "40 07 41 10 10 01 00 00 00 00 00 00 10 10 00 00";
+ public static string DESenseResponse1 = "40 04 41 00 00 00 00 00 00 00 00 10 00 00 00 00 01 70 00";
+ public static string DESenseResponse2 = "40 04 41 00 00 00 00 00 00 00 00 10 00 00 01 00 02 70 00 ";
+ public static string DESenseResponse3 = "40 04 41 00 00 00 00 00 00 00 00 10 00 00 02 00 03 70 00 ";
+ public static string DESenseResponse4 = "40 04 41 00 00 00 00 00 00 00 00 10 00 00 03 00 04 70 00 ";
+ public static string DESenseResponse5 = "40 04 41 00 00 00 00 00 00 00 00 10 00 00 04 00 05 70 00 ";
+ public static string DESenseResponse0 = "40 04 41 00 00 00 00 00 00 00 00 10 00 00 05 00 00 70 00 ";
+
+ public static string[] DESenseSatisfyResponse = { "40 04 41 00 00 00 00 00 00 00 00 10 00 00 05 00 05 70 00",
+ "40 04 41 00 00 00 00 00 00 00 00 10 00 00 04 00 04 70 00",
+ "40 04 41 00 00 00 00 00 00 00 00 10 00 00 03 00 03 70 00",
+ "40 04 41 00 00 00 00 00 00 00 00 10 00 00 02 00 02 70 00",
+ "40 04 41 00 00 00 00 00 00 00 00 10 00 00 01 00 01 70 00",
+ "40 04 41 00 00 00 00 00 00 00 00 10 00 00 00 00 00 70 00" };
+
+ //public static byte[] CountStartCmd= new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x73, 0x10, 0x03, 0x41 };
+ //public static byte[] DESenseCmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x60, 0x10, 0x03, 0x52 };
+ //public static byte[] UnlockCmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x71, 0x10, 0x03, 0x43 };
+ //public static byte[] CancelCmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x76, 0x10, 0x03, 0x44 };
+ //public static byte[] StoreStartCmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x31, 0x75, 0x10, 0x03, 0x47 };
+ public static byte[] LockCmd = new byte[] { 0x10, 0x02, 0x30, 0x31, 0x33, 0x70, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x09, 0x00, 0x01, 0x01, 0x00, 0x10, 0x03, 0x48 };
+
+ //Event data fix
+
+ public static byte[] EventDataFixed_01_Cmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x01, 0x10, 0x03, 0x54 };
+ public static byte[] EventDataFixed_02_Cmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x02, 0x10, 0x03, 0x57 };
+ public static byte[] EventDataFixed_03_Cmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x03, 0x10, 0x03, 0x56 };
+ public static byte[] EventDataFixed_04_Cmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x04, 0x10, 0x03, 0x51 };
+ public static byte[] EventDataFixed_05_Cmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x05, 0x10, 0x03, 0x50 };
+ public static byte[] EventDataFixed_00_Cmd = new byte[] { 0x10, 0x02, 0x30, 0x30, 0x33, 0x65, 0x00, 0x00, 0x10, 0x03, 0x55 };
+ }
+}
diff --git a/.svn/pristine/60/607a1fcd1a51b6d170cb6e38c97656f7a636f0c1.svn-base b/.svn/pristine/60/607a1fcd1a51b6d170cb6e38c97656f7a636f0c1.svn-base
new file mode 100644
index 0000000..80b3d8a
--- /dev/null
+++ b/.svn/pristine/60/607a1fcd1a51b6d170cb6e38c97656f7a636f0c1.svn-base
@@ -0,0 +1,290 @@
+using DE70_CMDv2;
+using Newtonsoft.Json.Linq;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ CDMSTATE=new CDMSTATE();
+ }
+ 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()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+ public static CDMSTATE? GetCDMState()
+ {
+ if(cCmdRsp!=null)
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv = cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ if(AppData.CDMSTATE!=null)
+ {
+ AppData.CDMSTATE.IsCassetteFull = data[17] & 0x08;
+ AppData.CDMSTATE.IsNotesInEscrow = data[4] & 0x01;
+ AppData.CDMSTATE.IsRejectPocketFull = data[3] & 0x40;
+ AppData.CDMSTATE.IsNotesInRejectPocket = data[3] & 0x10;
+ AppData.CDMSTATE.IsNotesInHopper = data[3] & 0x01;
+ AppData.CDMSTATE.RequestTime = DateTime.Now;
+ AppData.CDMSTATE.SR1 = data[0];
+ AppData.CDMSTATE.SR2 = data[1];
+ AppData.CDMSTATE.SR3 = data[2];
+ }
+
+ }
+ return AppData.CDMSTATE;
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+ public class CountSession
+ {
+ public CountSession()
+ {
+ for (int i = 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ public int CountingState { get; set; }//0-Normal End, 1-Timeout End
+ }
+
+ public class NotesInSession : INotifyPropertyChanged
+ {
+
+ private int _GenuineNotes;
+ public int GenuineNotes
+ {
+ get
+ {
+ return _GenuineNotes;
+ }
+ set
+ {
+ if (_GenuineNotes != value)
+ {
+ _GenuineNotes = value;
+ OnPropertyChanged(nameof(GenuineNotes));
+ }
+ }
+ }
+ private int _RejectNotes;
+ public int RejectNotes
+ {
+ get
+ {
+ return _RejectNotes;
+ }
+ set
+ {
+ if (_RejectNotes != value)
+ {
+ _RejectNotes = value;
+ OnPropertyChanged(nameof(RejectNotes));
+ }
+ }
+ }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public class CDMSTATE : INotifyPropertyChanged
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ public int IsNotesInHopper = 0;
+ private byte _SR1;
+ public byte SR1 {
+ get
+ {
+ return _SR1;
+ }
+ set
+ {
+ if (_SR1 != value)
+ {
+ _SR1 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR1));
+ }
+ }
+ }
+ private byte _SR2;
+ public byte SR2
+ {
+ get
+ {
+ return _SR2;
+ }
+ set
+ {
+ if (_SR2 != value)
+ {
+ _SR2 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR2));
+ }
+ }
+ }
+ private byte _SR3;
+ public byte SR3
+ {
+ get
+ {
+ return _SR3;
+ }
+ set
+ {
+ if (_SR3 != value)
+ {
+ _SR3 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR3));
+ }
+ }
+ }
+ public void UpdateCDMStatus()
+ {
+ if (AppData.cCmdRsp != null) {
+ CDMStatus = RequestTime.ToString("yyyyMMdd HHmmss")+ " SR1: " + AppData.cCmdRsp.GetSR1Summary(SR1) + " SR2: " + AppData.cCmdRsp.GetSR2Summary(SR2);
+ }
+ }
+ private string? _CDMStatus;
+ public string? CDMStatus
+ {
+ get
+ {
+ return _CDMStatus;
+ }
+ set
+ {
+ if (_CDMStatus != value)
+ {
+ _CDMStatus = value;
+
+ OnPropertyChanged(nameof(CDMStatus));
+ }
+ }
+ }
+
+
+ public DateTime RequestTime = DateTime.Now;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+
+}
diff --git a/.svn/pristine/60/60efb9b85e9f33598617b6a1ade1e9fb6c36e5f7.svn-base b/.svn/pristine/60/60efb9b85e9f33598617b6a1ade1e9fb6c36e5f7.svn-base
new file mode 100644
index 0000000..81f68ca
--- /dev/null
+++ b/.svn/pristine/60/60efb9b85e9f33598617b6a1ade1e9fb6c36e5f7.svn-base
@@ -0,0 +1,15 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace VirtualKeyboard.Wpf.Types
+{
+ enum UppercaseMode
+ {
+ None,
+ FirstUpper,
+ AlwaysUpper
+ }
+}
diff --git a/.svn/pristine/62/62cb1a4806ec0f851e1f286581bce0e1f6a7aef5.svn-base b/.svn/pristine/62/62cb1a4806ec0f851e1f286581bce0e1f6a7aef5.svn-base
new file mode 100644
index 0000000..4648419
--- /dev/null
+++ b/.svn/pristine/62/62cb1a4806ec0f851e1f286581bce0e1f6a7aef5.svn-base
@@ -0,0 +1,76 @@
+{
+ "version": 3,
+ "targets": {
+ "net8.0-windows7.0": {}
+ },
+ "libraries": {},
+ "projectFileDependencyGroups": {
+ "net8.0-windows7.0": []
+ },
+ "packageFolders": {
+ "C:\\Users\\Admin\\.nuget\\packages\\": {}
+ },
+ "project": {
+ "version": "1.0.0",
+ "restore": {
+ "projectUniqueName": "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "projectName": "VirtualKeyboard",
+ "projectPath": "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "packagesPath": "C:\\Users\\Admin\\.nuget\\packages\\",
+ "outputPath": "D:\\SRC\\VirtualKeyboard\\obj\\",
+ "projectStyle": "PackageReference",
+ "configFilePaths": [
+ "C:\\Users\\Admin\\AppData\\Roaming\\NuGet\\NuGet.Config",
+ "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
+ ],
+ "originalTargetFrameworks": [
+ "net8.0-windows"
+ ],
+ "sources": {
+ "C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
+ "https://api.nuget.org/v3/index.json": {}
+ },
+ "frameworks": {
+ "net8.0-windows7.0": {
+ "targetAlias": "net8.0-windows",
+ "projectReferences": {}
+ }
+ },
+ "warningProperties": {
+ "warnAsError": [
+ "NU1605"
+ ]
+ },
+ "restoreAuditProperties": {
+ "enableAudit": "true",
+ "auditLevel": "low",
+ "auditMode": "direct"
+ }
+ },
+ "frameworks": {
+ "net8.0-windows7.0": {
+ "targetAlias": "net8.0-windows",
+ "imports": [
+ "net461",
+ "net462",
+ "net47",
+ "net471",
+ "net472",
+ "net48",
+ "net481"
+ ],
+ "assetTargetFallback": true,
+ "warn": true,
+ "frameworkReferences": {
+ "Microsoft.NETCore.App": {
+ "privateAssets": "all"
+ },
+ "Microsoft.WindowsDesktop.App.WPF": {
+ "privateAssets": "none"
+ }
+ },
+ "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\8.0.303/PortableRuntimeIdentifierGraph.json"
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/62/62ef30fa25d0f007eee14050ca172a04ce1a2708.svn-base b/.svn/pristine/62/62ef30fa25d0f007eee14050ca172a04ce1a2708.svn-base
new file mode 100644
index 0000000..6c484d3
--- /dev/null
+++ b/.svn/pristine/62/62ef30fa25d0f007eee14050ca172a04ce1a2708.svn-base
@@ -0,0 +1,1674 @@
+namespace DE70_CMDv2
+{
+ using Serilog;
+ using SafeBagDE70;
+ using System;
+ using System.Diagnostics;
+ using System.IO;
+ using System.IO.Ports;
+ using System.Text;
+ using System.Linq;
+
+ public class CCmdRsp
+ {
+ public static CDenom[] mDenomTable = new CDenom[128];
+ public static int mDenominationCount;
+ public static string mSelectedCurrency;
+ public static int miSelectedCurrency;
+ private SerialPort serialPort = null;
+ private int m_all_sendsize;
+ private int m_all_recvsize;
+ private byte[] recv_buf = new byte[8192];
+ private byte[] m_send_buf = new byte[8192];
+ public RecvData recv_dat = new RecvData();
+ private SendDataStruct send_dat = new SendDataStruct();
+ private SendStatus cmd_result;
+ private LockParam lock_param = new LockParam();
+ private byte[] recv_serialset = new byte[256];
+ private Com232C m_ccom = null;
+
+ public CCmdRsp(SerialPort _serialPort)
+ {
+ serialPort = _serialPort;
+ m_ccom = new Com232C(_serialPort);
+ m_all_sendsize = 0;
+ m_all_recvsize = 0;
+ Array.Clear(recv_buf, 0, recv_buf.Length);
+ Array.Clear(m_send_buf, 0, m_send_buf.Length);
+ Array.Clear(recv_dat.dat, 0, recv_dat.dat.Length);
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ cmd_result = SendStatus.SEND_NON;
+ lock_param.Register = 1;
+ lock_param.ID = 1;
+ lock_param.TransactionNo = 1;
+ lock_param.mode = Mode.MODE_DEPOSIT;
+ lock_param.Currency = Currency.CURRENCY01; // first currency
+ lock_param.Gengai.amount = 0;
+ lock_param.Batch.Regi_num = 1;
+ Array.Clear(lock_param.Batch.batch_num, 0, lock_param.Batch.batch_num.Length);
+ Array.Clear(lock_param.Cassette.CassetteID, 0, lock_param.Cassette.CassetteID.Length);
+ Array.Clear(recv_serialset, 0, recv_serialset.Length);
+ }
+
+ public byte SendData()
+ {
+ byte ret = m_ccom.send_dat(m_send_buf, m_all_sendsize);
+ return ret;
+ }
+
+ public int SendSerialSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return (int)cmd_result;
+
+ return SendRecvData();
+ //return Constants.E_OK;
+ }
+ public static string ByteArrayToHexString(byte[] byteArray, int startIndex, int length, bool separateWithSpace = false)
+ {
+ if (startIndex < 0 || length < 0 || startIndex + length > byteArray.Length)
+ {
+ return "The specified range is out of bounds.";
+ }
+
+ var hexStringBuilder = new StringBuilder();
+ for (int i = startIndex; i < startIndex + length; i++)
+ {
+ hexStringBuilder.Append(byteArray[i].ToString("X2"));
+ if (separateWithSpace && i < startIndex + length - 1)
+ {
+ hexStringBuilder.Append(" ");
+ }
+ }
+
+ return hexStringBuilder.ToString();
+ }
+
+
+ private int SendRecvData()
+ {
+ SendDataSet();
+ send_dat.ret = SendData();
+ //Log.Information("[CMD_SEND] " + GetSendDat(false));
+
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+
+ recv_dat.ret = WaitRsp();
+ //Log.Information("[CMD_RCV] " +GetRecvDat());
+
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ //return (int)cmd_result;
+ return Constants.E_OK;
+ }
+
+ public int SendSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendDeSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendDeviceSettingDataReq()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = 0x62;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendDenomiRead2()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_BVDATA_READ;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendSerialSet(byte[] dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETDATA;
+ send_dat.leng = 1 + 20;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ Array.Copy(dat, 0, send_dat.dat, 0, 20);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendSetRJSerial()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETRJSERIAL;
+ send_dat.leng = 24;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ send_dat.dat[0] = 0x01;
+ send_dat.dat[1] = (byte)'I';
+ send_dat.dat[2] = (byte)'N';
+ send_dat.dat[3] = (byte)'R';
+ send_dat.dat[4] = 0x00;
+ send_dat.dat[5] = 5;
+ send_dat.dat[6] = 8;
+ send_dat.dat[7] = (byte)'4';
+ send_dat.dat[8] = (byte)'K';
+ send_dat.dat[9] = (byte)'T';
+ send_dat.dat[10] = (byte)'4';
+ send_dat.dat[11] = (byte)'7';
+ send_dat.dat[12] = (byte)'6';
+ send_dat.dat[13] = (byte)'6';
+ send_dat.dat[14] = (byte)'1';
+ send_dat.dat[15] = (byte)'#';
+ send_dat.dat[16] = (byte)'#';
+ send_dat.dat[17] = (byte)'#';
+ send_dat.dat[18] = (byte)'#';
+ send_dat.dat[19] = (byte)'#';
+ send_dat.dat[20] = (byte)'#';
+ send_dat.dat[21] = (byte)'#';
+ send_dat.dat[22] = (byte)'#';
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendSerialSetRead()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETDATAREAD;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ SendRecvData();
+ Array.Copy(recv_dat.dat, 13, recv_serialset, 0, recv_serialset.Length);
+
+ return Constants.E_OK;
+ }
+
+ public int SendGetSerial(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_GETSERIAL;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+ return SendRecvData();
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ }
+
+ public int SendFreeDat()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = 0x00;
+ send_dat.leng = 1 + 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ if (!File.Exists("send.bin"))
+ {
+ cmd_result = SendStatus.SEND_DAT_ERR;
+ return Constants.E_NG_FILE;
+ }
+
+ byte[] fileData = File.ReadAllBytes("send.bin");
+ send_dat.cmd = fileData[0];
+ Array.Copy(fileData, 1, send_dat.dat, 0, fileData.Length - 1);
+ send_dat.leng = fileData.Length;
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendDataSet()
+ {
+ int sendsize = 0;
+ byte bcc = 0;
+ byte[] len_dat = new byte[3];
+ Array.Clear(m_send_buf, 0, m_send_buf.Length);
+
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ m_send_buf[sendsize++] = Constants.D_STX;
+ SetLen(len_dat, send_dat.leng);
+ for (int i = 0; i < 3; i++)
+ {
+ if (len_dat[i] == Constants.D_DLE)
+ {
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ }
+ m_send_buf[sendsize++] = len_dat[i];
+ bcc ^= len_dat[i];
+ }
+
+ m_send_buf[sendsize++] = send_dat.cmd;
+ bcc ^= send_dat.cmd;
+ for (int i = 0; i < send_dat.leng - 1; i++)
+ {
+ if (send_dat.dat[i] == Constants.D_DLE)
+ {
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ }
+ m_send_buf[sendsize++] = send_dat.dat[i];
+ bcc ^= send_dat.dat[i];
+ }
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ m_send_buf[sendsize++] = Constants.D_ETX;
+ bcc ^= Constants.D_ETX;
+ m_send_buf[sendsize++] = bcc;
+ send_dat.bcc = bcc;
+
+ m_all_sendsize = sendsize;
+
+ return Constants.E_OK;
+ }
+
+ public int SetLen(byte[] dat, int size)
+ {
+ if (size <= 999)
+ {
+ dat[0] = (byte)((size / 100) | 0x30);
+ dat[1] = (byte)(((size % 100) / 10) | 0x30);
+ dat[2] = (byte)((size % 100) % 10 | 0x30);
+ }
+ else
+ {
+ dat[0] = (byte)((size / 0x010000) | 0x70);
+ dat[1] = (byte)((size % 0x010000) / 0x100);
+ dat[2] = (byte)((size % 0x010000) % 0x100);
+ }
+ return Constants.E_OK;
+ }
+
+ public byte WaitRsp()
+ {
+ int pos_r = 0;
+ int size;
+ int i;
+ bool dle_flg = false;
+ Array.Clear(recv_buf, 0, recv_buf.Length);
+ recv_dat.ret = Constants.E_OK;
+ recv_dat.cmd = 0x00;
+ recv_dat.leng = 0;
+ recv_dat.bcc = 0x00;
+ Array.Clear(recv_dat.dat, 0, recv_dat.dat.Length);
+
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 1);
+ if (size != 1)
+ {
+ return Constants.E_NG;
+ }
+ if (recv_buf[pos_r] == Constants.D_NAK)
+ {
+ return Constants.E_NG;
+ }
+ if (recv_buf[pos_r] != Constants.D_DLE)
+ {
+ return Constants.E_NG;
+ }
+ pos_r++;
+
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 1);
+ if (recv_buf[pos_r] != Constants.D_STX || size != 1)
+ {
+ return Constants.E_NG;
+ }
+ pos_r++;
+
+ if (WaitRspLen(ref recv_buf, pos_r, ref recv_dat.leng, out size) != Constants.E_OK)
+ {
+ return Constants.E_NG;
+ }
+ pos_r += size;
+
+ if (m_ccom.rcv_dat(recv_buf, pos_r, 1) != 1)
+ {
+ return Constants.E_NG;
+ }
+ recv_dat.cmd = recv_buf[pos_r];
+ pos_r++;
+
+ if (recv_dat.cmd == (byte)Command.CMD_GDB_GETSERIAL)
+ {
+ //Tạo buffer để nhận dữ liệu
+ //size = m_ccom.rcv_dat(recv_buf, pos_r, recv_dat.leng - 1);
+ int _size = 0;
+ int _pos_r = pos_r;
+ while (_size < recv_dat.leng - 1)
+ {
+ var _tsize = m_ccom.rcv_dat(recv_buf, _pos_r, recv_dat.leng - 1 - _size);
+ _size += _tsize;
+ _pos_r += _tsize;
+ }
+ size = _size;
+ //pos_r = _pos_r;
+ if (size != recv_dat.leng - 1)
+ {
+ return Constants.E_NG;
+ }
+ Array.Copy(recv_buf, pos_r, recv_dat.dat, 0, recv_dat.leng - 1);
+ pos_r += size;
+ }
+ else
+ {
+ i = 0;
+ while (i < recv_dat.leng - 1)
+ {
+ if (m_ccom.rcv_dat(recv_buf, pos_r, 1) != 1)
+ {
+ return Constants.E_NG;
+ }
+ if (!dle_flg && recv_buf[pos_r] == Constants.D_DLE)
+ {
+ pos_r++;
+ dle_flg = true;
+ continue;
+ }
+ recv_dat.dat[i] = recv_buf[pos_r];
+ pos_r++;
+ i++;
+ dle_flg = false;
+ }
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 3);
+ recv_dat.bcc = recv_buf[pos_r + 2];
+ pos_r += size;
+ }
+ m_all_recvsize = pos_r;
+ return Constants.E_OK;
+ }
+
+ public int WaitRspLen(ref byte[] dat, int pos, ref int leng, out int size)
+ {
+ int initialPos = pos;
+
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if ((dat[pos] & 0xF0) == 0x70)
+ {
+ leng = (dat[pos] & 0x0F) * 0x10000;
+ pos++;
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (dat[pos] == Constants.D_DLE)
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ pos++;
+ }
+ leng += dat[pos] * 0x100;
+ pos++;
+
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (dat[pos] == Constants.D_DLE)
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ pos++;
+ }
+ leng += dat[pos];
+ pos++;
+ }
+ else
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 2) != 2)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (((dat[pos] & 0x30) != 0x30) || ((dat[pos + 1] & 0x30) != 0x30) || ((dat[pos + 2] & 0x30) != 0x30))
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ leng = (dat[pos] & 0x0F) * 100 + (dat[pos + 1] & 0x0F) * 10 + (dat[pos + 2] & 0x0F);
+ pos += 3;
+ }
+
+ size = pos - initialPos;
+ return Constants.E_OK;
+ }
+
+ public string GetSendDat(bool oneLine)
+ {
+ StringBuilder str = new StringBuilder();
+
+ string cmd = GetCommandName(send_dat.cmd);
+
+ var dat=string.Format("SEND {0} L:{1} ", cmd, send_dat.leng);
+ str.Append(dat);
+
+ if (!oneLine)
+ {
+ str.Append("DATA:");
+ for (int i = 0; i < send_dat.leng - 1; i++)
+ {
+ dat = string.Format("{0:X2} ", send_dat.dat[i]);
+ }
+ str.Append(dat);
+ str.Append(" Raw: ");
+
+ if (cmd_result == SendStatus.SEND_RECV_OK || cmd_result == SendStatus.RECV_ERR)
+ {
+ for (int i = 0; i < m_all_sendsize; i++)
+ {
+ dat = string.Format("{0:X2} ", m_send_buf[i]);
+ }
+ str.Append(dat);
+ }
+ else if (cmd_result == SendStatus.SEND_DAT_ERR || cmd_result == SendStatus.SEND_ERR)
+ {
+ str.Append("send err");
+ }
+ //str.Append("\r\n");
+ }
+ else
+ {
+ str.Append(" >> ");
+ str.Append(SetStText());
+ }
+
+ return str.ToString();
+ }
+
+ public string GetRecvDat()
+ {
+ StringBuilder str = new StringBuilder();
+
+
+ if (cmd_result == SendStatus.SEND_RECV_OK)
+ {
+ var dat=string.Format("RECV CM:0x{0:X2} L:{1} ", recv_dat.cmd, recv_dat.leng);
+ str.Append(dat);
+ str.Append("DATA:");
+ for (int i = 0; i < recv_dat.leng - 1; i++)
+ {
+ dat=string.Format("{0:X2} ", recv_dat.dat[i]);
+ str.Append(dat);
+ }
+ str.Append(" Raw: ");
+
+ for (int i = 0; i < m_all_recvsize; i++)
+ {
+ dat=string.Format("{0:X2} ", recv_buf[i]);
+ str.Append(dat);
+ }
+ }
+ else if (cmd_result == SendStatus.RECV_ERR)
+ {
+ str.Append("recv err");
+ }
+ //str.Append("\r\n");
+ return str.ToString();
+ }
+
+ public int ImgSave(FileStream file)
+ {
+ if (send_dat.ret == Constants.E_OK && recv_dat.ret == Constants.E_OK)
+ {
+ file.Write(recv_dat.dat, 0, recv_dat.leng - 1);
+ }
+ return Constants.E_OK;
+ }
+
+ public int SendXXCmd(byte cmd)
+ {
+ return SendXXCmd(new byte[] { cmd }, 1);
+ }
+
+ public int SendXXCmd(byte[] cmd, int len)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = cmd[0];
+ send_dat.leng = len;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ for (int x = 0; x < len - 1; x++)
+ {
+ send_dat.dat[x] = cmd[x + 1];
+ }
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendEventRead(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_EVDATA_READ;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendEventFix(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_EVDATA_FIX;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+
+ public int SendLock()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_LOCK;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ SetLockParam();
+
+ //SendDataSet();
+ //send_dat.ret = SendData();
+ //if (send_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.SEND_ERR;
+ // return Constants.E_NG_SEND;
+ //}
+ //recv_dat.ret = WaitRsp();
+ //if (recv_dat.ret != Constants.E_OK)
+ //{
+ // cmd_result = SendStatus.RECV_ERR;
+ // return Constants.E_NG_RECV;
+ //}
+ //cmd_result = SendStatus.SEND_RECV_OK;
+ //return Constants.E_OK;
+ return SendRecvData();
+ }
+ public LockParam GetLockParam()
+ {
+ return lock_param;
+ }
+ public void SetLockParam()
+ {
+ int size;
+ uint amount_i = 0;
+ uint amount_f = 0;
+
+ send_dat.dat[0] = 0x00;
+ send_dat.dat[1] = (byte)((lock_param.Register & 0xff00) >> 8);
+ send_dat.dat[2] = (byte)(lock_param.Register & 0xff);
+ send_dat.dat[3] = (byte)((lock_param.ID & 0xff000000) >> 24);
+ send_dat.dat[4] = (byte)((lock_param.ID & 0xff0000) >> 16);
+ send_dat.dat[5] = (byte)((lock_param.ID & 0xff00) >> 8);
+ send_dat.dat[6] = (byte)(lock_param.ID & 0xff);
+ send_dat.dat[7] = 9;
+ send_dat.dat[8] = (byte)((lock_param.TransactionNo & 0xff00) >> 8);
+ send_dat.dat[9] = (byte)(lock_param.TransactionNo & 0xff);
+ send_dat.dat[10] = (byte)lock_param.mode;
+ send_dat.dat[11] = (byte)(lock_param.Currency == Currency.CURRENCY_MLT ? 10 : (byte)lock_param.Currency);
+
+ switch (lock_param.mode)
+ {
+ case Mode.MODE_COUNT:
+ send_dat.dat[12] = 0;
+ size = 1 + 12 + 1;
+ break;
+ case Mode.MODE_MANUAL:
+ send_dat.dat[12] = 0;
+ amount_i = (uint)lock_param.Gengai.amount;
+ amount_f = (uint)((lock_param.Gengai.amount * 1000) - amount_i * 1000);
+ send_dat.dat[13] = (byte)((amount_i & 0xff000000) >> 24);
+ send_dat.dat[14] = (byte)((amount_i & 0xff0000) >> 16);
+ send_dat.dat[15] = (byte)((amount_i & 0xff00) >> 8);
+ send_dat.dat[16] = (byte)(amount_i & 0xff);
+ send_dat.dat[17] = (byte)((amount_f & 0xff00) >> 8);
+ send_dat.dat[18] = (byte)(amount_f & 0xff);
+ size = 1 + 12 + 7;
+ break;
+ case Mode.MODE_BATCH:
+ send_dat.dat[12] = (byte)lock_param.Batch.Regi_num;
+ Array.Copy(lock_param.Batch.batch_num, 0, send_dat.dat, 13, 64);
+ size = 1 + 12 + 65;
+ break;
+ case Mode.MODE_CHANGE:
+ case Mode.MODE_COLLECTION:
+ Array.Copy(lock_param.Cassette.CassetteID, 0, send_dat.dat, 12, 16);
+ size = 1 + 12 + 16;
+ break;
+ case Mode.MODE_SET:
+ send_dat.dat[12] = 5;
+ send_dat.dat[13] = 4;
+ send_dat.dat[14] = 2;
+ send_dat.dat[15] = 0;
+ send_dat.dat[16] = 5;
+ size = 1 + 12 + 5;
+ break;
+ default:
+ size = 1 + 12;
+ break;
+ }
+ send_dat.leng = size;
+ }
+
+ public string SetStText()
+ {
+ StringBuilder text = new StringBuilder();
+
+ switch (cmd_result)
+ {
+ case SendStatus.SEND_ERR:
+ case SendStatus.SEND_DAT_ERR:
+ text.Append("SEND_ERR");
+ break;
+ case SendStatus.RECV_ERR:
+ text.Append("RECV_ERR");
+ break;
+ case SendStatus.SEND_RECV_OK:
+ text.Append("SR1");
+ text.Append(GetSR1Summary(recv_dat.dat[0]));
+ text.Append(", ");
+
+ text.AppendFormat("SR2: ");
+ text.Append(GetSR2Summary(recv_dat.dat[1]));
+ text.Append(", ");
+
+ if (recv_dat.leng >= 15)
+ {
+ if (recv_dat.cmd == (byte)Command.CMD_DE_SENSE || recv_dat.cmd == (byte)Command.CMD_GDB_SENSE)
+ {
+ text.AppendFormat("Sent/unsent events:{0}/{1} ",
+ recv_dat.dat[13] * 0x0100 + recv_dat.dat[14],
+ recv_dat.dat[15] * 0x0100 + recv_dat.dat[16]);
+ if (recv_dat.leng == 84 || recv_dat.leng == 86)
+ {
+ text.Append(GetSummaryTotal(recv_dat.dat, 19));
+ }
+ }
+ }
+ break;
+ case SendStatus.SEND_NON:
+ default:
+ text.Append("SEND_NON");
+ break;
+ }
+ return text.ToString();
+ }
+
+ public string GetSummaryTotal(byte[] counts, int numDenoms, bool wordcounts = true)
+ {
+ StringBuilder ret = new StringBuilder();
+ double[] total = new double[10];
+ string[] pCurrencyID = new string[10];
+
+ Array.Clear(total, 0, total.Length);
+ Array.Clear(pCurrencyID, 0, pCurrencyID.Length);
+
+ if (mDenominationCount > 0 && mDenominationCount < 65)
+ {
+ numDenoms = Math.Min(numDenoms, mDenominationCount);
+
+ for (int x = 0; x < numDenoms; x++)
+ {
+ if (mDenomTable[x].mCurrenyIndex < total.Length)
+ {
+ int noteCount;
+ if (wordcounts)
+ {
+ noteCount = counts[x * 2] * 256 + counts[x * 2 + 1];
+ }
+ else
+ {
+ noteCount = counts[x];
+ }
+ total[mDenomTable[x].mCurrenyIndex] += mDenomTable[x].mDenomValue * noteCount;
+ pCurrencyID[mDenomTable[x].mCurrenyIndex] = mDenomTable[x].currency;
+ }
+ }
+ ret.Append("Counted: ");
+ for (int x = 0; x < total.Length; x++)
+ {
+ if (total[x] != 0)
+ {
+ ret.AppendFormat(" {0}: {1:0.00}", pCurrencyID[x] ?? "???", total[x]);
+ }
+ }
+ }
+ else
+ {
+ ret.Append(" No denom data");
+ }
+
+ return ret.ToString();
+ }
+
+ public string GetSR1Summary(byte sr1)
+ {
+ StringBuilder text = new StringBuilder();
+
+ text.AppendFormat("(0x{0:X2}): ", sr1);
+ switch (sr1)
+ {
+ case 0x40:
+ text.Append("CMD OK");
+ break;
+ case 0x41:
+ text.Append("No execution");
+ break;
+ case 0x42:
+ text.Append("Store fail,");
+ break;
+ case 0x43:
+ text.Append("Unknown command");
+ break;
+ case 0x44:
+ text.Append("Length error");
+ break;
+ case 0x46:
+ text.Append("CMD error (not executed)");
+ break;
+ case 0x47:
+ text.Append("Local processing");
+ break;
+ case 0x48:
+ text.Append("Already occupied");
+ break;
+ case 0x49:
+ text.Append("Abnormal data");
+ break;
+ default:
+ text.Append("Unknown SR1");
+ break;
+ }
+ return text.ToString();
+ }
+ public string GetS1Summary(byte s1)
+ {
+ string text = string.Format("(0x{0:X}): {1}{2}{3}{4}{5}{6}{7}{8}", s1,
+ (s1 & 0x80) != 0 ? "Locked, " : "Not locked, ",
+ (s1 & 0x40) != 0 ? "Escrow door closed, " : "Escrow door open, ",
+ (s1 & 0x20) != 0 ? "" : "bit5=false, ",
+ (s1 & 0x10) != 0 ? "" : "bit4=false, ",
+ (s1 & 0x08) != 0 ? "Cassette full, " : "Cassette not full, ",
+ (s1 & 0x04) != 0 ? "bit2=true, " : "",
+ (s1 & 0x02) != 0 ? "bit1=true, " : "",
+ (s1 & 0x01) != 0 ? "Dirty sensor, " : "No dirty sensor, ");
+
+ text = text.TrimEnd(',', ' ');
+
+ return text;
+ }
+ public string GetS2Summary(byte s2)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", s2);
+
+ switch (s2 & 0xf0)
+ {
+ case 0x00: text.Append("Login mode, "); break;
+ case 0x10: text.Append("Deposit mode, "); break;
+ case 0x20: text.Append("Counting mode, "); break;
+ case 0x30: text.Append("Manual mode, "); break;
+ case 0x40: text.Append("Batch mode, "); break;
+ case 0x50: text.Append("Close mode, "); break;
+ case 0x60: text.Append("Temporary close mode, "); break;
+ case 0x70: text.Append("Change mode, "); break;
+ case 0x80: text.Append("Collection mode, "); break;
+ case 0x90: text.Append("Setting mode, "); break;
+ case 0xa0: text.Append("Error mode, "); break;
+ case 0xb0: text.Append("Currency change mode, "); break;
+ case 0xc0:
+ case 0xd0: text.Append("Spare mode, "); break;
+ case 0xe0: text.Append("Important error mode, "); break;
+ case 0xf0: text.Append("Initial mode, "); break;
+ default: text.Append("Unexpected S2 mode value, "); break;
+ }
+
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetSR2Summary(byte sr2)
+ {
+ StringBuilder text = new StringBuilder();
+
+ text.AppendFormat("(0x{0:X2}): ", sr2);
+ switch (sr2)
+ {
+ case 0x01:
+ text.Append("Initialising");
+ break;
+ case 0x1c:
+ text.Append("Initialisation error (cycle power)");
+ break;
+ case 0x1b:
+ text.Append("Resetting");
+ break;
+ case 0x0a:
+ text.Append("Waiting for notes to be removed");
+ break;
+ case 0x04:
+ text.Append("Stand by");
+ break;
+ case 0x07:
+ text.Append("Ready to count");
+ break;
+ case 0x09:
+ text.Append("Counting/batch");
+ break;
+ case 0x1f:
+ text.Append("Batch processing");
+ break;
+ case 0x0d:
+ text.Append("Setting");
+ break;
+ default:
+ text.Append("Unknown SR2");
+ break;
+ }
+ return text.ToString();
+ }
+ public string GetSR3Summary(byte sr3)
+ {
+ StringBuilder text = new StringBuilder();
+ text.AppendFormat("(0x{0:X2}): ", sr3);
+
+ switch (sr3)
+ {
+ case 0x40:
+ text.Append("Busy");
+ break;
+ case 0x41:
+ text.Append("Normal completion");
+ break;
+ case 0x42:
+ text.Append("Operation could not start");
+ break;
+ case 0x43:
+ text.Append("Stacker full");
+ break;
+ case 0x44:
+ text.Append("Reject pocket full");
+ break;
+ case 0x45:
+ text.Append("Failure to feed notes");
+ break;
+ case 0x4A:
+ text.Append("Waiting for reset");
+ break;
+ case 0x4C:
+ text.Append("Waiting for an error recovery sequence");
+ break;
+ default:
+ text.Append("Unknown SR3");
+ break;
+ }
+
+ return text.ToString();
+ }
+ public string GetD1Summary(byte d1)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d1);
+ text.Append((d1 & 0x80) != 0 ? "bit7=true, " : "");
+ text.Append((d1 & 0x40) != 0 ? "Reject pocket full, " : "reject pocket not full, ");
+ text.Append((d1 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d1 & 0x10) != 0 ? "note(s) in reject pocket, " : "reject pocket empty, ");
+ text.Append((d1 & 0x08) != 0 ? "failure to feed, " : "last feed OK, ");
+ text.Append((d1 & 0x04) != 0 ? "bit3=true, " : "");
+ text.Append((d1 & 0x02) != 0 ? "note in feeder mech, " : "feeder mech clear, ");
+ text.Append((d1 & 0x01) != 0 ? "note(s) in feeder hopper" : "feeder hopper empty");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD2Summary(byte d2)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d2);
+ text.Append((d2 & 0x80) != 0 ? "bit7=true, " : "");
+ text.Append((d2 & 0x40) != 0 ? "bit6=true, " : "");
+ text.Append((d2 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d2 & 0x10) != 0 ? "bit4=true, " : "");
+ text.Append((d2 & 0x08) != 0 ? "bit3=true, " : "");
+ text.Append((d2 & 0x04) != 0 ? "bit2=true, " : "");
+ text.Append((d2 & 0x02) != 0 ? "bit1=true, " : "");
+ text.Append((d2 & 0x01) != 0 ? "notes in escrow" : "escrow empty");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD3Summary(byte d3)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d3);
+ text.Append((d3 & 0x80) != 0 ? "bit7=true, " : "");
+ text.Append((d3 & 0x40) != 0 ? "bit6=true, " : "");
+ text.Append((d3 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d3 & 0x10) != 0 ? "bit4=true, " : "");
+ text.Append((d3 & 0x08) != 0 ? "bit3=true, " : "");
+ text.Append((d3 & 0x04) != 0 ? "bit2=true, " : "");
+ text.Append((d3 & 0x02) != 0 ? "bit1=true, " : "");
+ text.Append((d3 & 0x01) != 0 ? "escrow full" : "escrow not full");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD4Summary(byte d4)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d4);
+ text.Append((d4 & 0x80) != 0 ? "bit7=true, " : "");
+ text.Append((d4 & 0x40) != 0 ? "bit6=true, " : "");
+ text.Append((d4 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d4 & 0x10) != 0 ? "bit4=true, " : "");
+ text.Append((d4 & 0x08) != 0 ? "bit3=true, " : "");
+ text.Append((d4 & 0x04) != 0 ? "bit2=true, " : "");
+ text.Append((d4 & 0x02) != 0 ? "bit1=true, " : "");
+ text.Append((d4 & 0x01) != 0 ? "batch complete" : "batch not complete");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD5Summary(byte d5)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d5);
+ text.Append((d5 & 0x80) != 0 ? "bit7=true, " : "");
+ text.Append((d5 & 0x40) != 0 ? "bit6=true, " : "");
+ text.Append((d5 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d5 & 0x10) != 0 ? "bit4=true, " : "");
+ text.Append((d5 & 0x08) != 0 ? "bit3=true, " : "");
+ text.Append((d5 & 0x04) != 0 ? "bit2=true, " : "");
+ text.Append((d5 & 0x02) != 0 ? "bit1=true, " : "");
+ text.Append((d5 & 0x01) != 0 ? "1+ forgotten notes sequences stored notes in this cassette" : "no forgotten notes are stored in this cassette");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD6Summary(byte d6)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d6);
+ text.Append((d6 & 0x80) != 0 ? "serial number capture data nearly full, " : "serial number capture data space available, ");
+ text.Append((d6 & 0x40) != 0 ? "serial number capture data full, " : "serial number capture data space not full, ");
+ text.Append((d6 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d6 & 0x10) != 0 ? "bit4=true, " : "");
+ text.Append((d6 & 0x08) != 0 ? "bit3=true, " : "");
+ text.Append((d6 & 0x04) != 0 ? "bit2=true, " : "");
+ text.Append((d6 & 0x02) != 0 ? "bit1=true, " : "");
+ text.Append((d6 & 0x01) != 0 ? "transport covers open" : "transport covers closed");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD7D8Summary(byte d7, byte d8)
+ {
+ var text = new StringBuilder();
+ string errorDecode = "The error code was not found in the lookup list.";
+ int errorCode = d7 * 256 + d8;
+
+ try
+ {
+ using (var reader = new StreamReader("ErrorCodesExportedFromServiceManual.csv"))
+ {
+ string line;
+ while ((line = reader.ReadLine()) != null)
+ {
+ var tokens = line.Split(',');
+ if (int.TryParse(tokens[0], out int decimalCode) && decimalCode == errorCode)
+ {
+ errorDecode = tokens[2] + (tokens.Length > 3 ? ", " + tokens[3] : "");
+ break;
+ }
+ }
+ }
+ }
+ catch (FileNotFoundException)
+ {
+ errorDecode = "Cannot open error lookup file ErrorCodesExportedFromServiceManual.csv";
+ }
+
+ text.AppendFormat("(0x{0:X}): {1}", errorCode, errorDecode);
+ return text.ToString().TrimEnd(',', ' ');
+ }
+ public string GetD9Summary(byte d9)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d9);
+
+ switch (d9 & 0xf0)
+ {
+ case 0x10: text.Append("First currency"); break;
+ case 0x20: text.Append("Second currency"); break;
+ case 0x30: text.Append("Third currency"); break;
+ case 0x40: text.Append("Fourth currency"); break;
+ case 0x50: text.Append("Fifth currency"); break;
+ case 0x60: text.Append("Sixth currency"); break;
+ case 0x70: text.Append("Seventh currency"); break;
+ default: text.Append("Unexpected currency value"); break;
+ }
+
+ return text.ToString();
+ }
+ public string GetD10Summary(byte d10)
+ {
+ var text = new StringBuilder();
+ text.AppendFormat("(0x{0:X}): ", d10);
+ text.Append((d10 & 0x80) != 0 ? "bit7=true, " : "");
+ text.Append((d10 & 0x40) != 0 ? "bit6=true, " : "");
+ text.Append((d10 & 0x20) != 0 ? "bit5=true, " : "");
+ text.Append((d10 & 0x10) != 0 ? "bit4=true, " : "");
+ text.Append((d10 & 0x08) != 0 ? "bit3=true, " : "");
+ text.Append((d10 & 0x04) != 0 ? "bit2=true, " : "");
+ text.Append((d10 & 0x02) != 0 ? "bit1=true, " : "");
+ text.Append((d10 & 0x01) != 0 ? "bit0=true, " : "");
+ return text.ToString().TrimEnd(',', ' ');
+ }
+
+ public int GetSerialNum(out ushort num)
+ {
+ ushort serial_num;
+
+ if (recv_dat.cmd == (byte)Command.CMD_GDB_SENSE && recv_dat.leng == Constants.DATLEN_GDBSense_Cnt)
+ {
+ serial_num = (ushort)(recv_dat.dat[83] * 0x100 + recv_dat.dat[84]);
+ if (serial_num <= 1000)
+ {
+ num = serial_num;
+ return Constants.E_OK;
+ }
+ }
+ num = 0x00;
+ return Constants.E_NG;
+ }
+
+ public bool ChkCntEnd()
+ {
+ return recv_dat.cmd != (byte)Command.CMD_GDB_SENSE || recv_dat.dat[1] != (byte)SR2.SR2_cnting;
+ }
+
+ public void GetRecvSerialSet(byte[] dat)
+ {
+ Array.Copy(recv_serialset, dat, recv_serialset.Length);
+ }
+
+ public override string ToString()
+ {
+ return GetSendDat(true);
+ }
+
+ public int GetSendDatLength()
+ {
+ return send_dat.leng;
+ }
+
+ public int GetRecDatLength()
+ {
+ return recv_dat.leng - 1;
+ }
+
+ public byte[] GetSendDatPtr()
+ {
+ return send_dat.dat;
+ }
+
+ public byte[] GetRecDatPtr()
+ {
+ return recv_dat.dat;
+ }
+
+ public Command GetCmdByte()
+ {
+ return (Command)send_dat.cmd;
+ }
+
+ public string GetCommandName(byte cmd)
+ {
+ switch (cmd)
+ {
+ case 0x22:
+ return "CMD_SENSE";
+ case 0x40:
+ return "CMD_ST_UPLOAD";
+ case 0x41:
+ return "CMD_END_UPLOAD";
+ case 0x44:
+ return "CMD_REQ_UPLOAD";
+ case 0x45:
+ return "CMD_ST_DOWNLOAD";
+ case 0x46:
+ return "CMD_END_DOWNLOAD";
+ case 0x49:
+ return "CMD_REQ_DOWNLOAD";
+ case 0x4A:
+ return "CMD_P_UPDATE";
+ case 0x4D:
+ return "CMD_GETFILEINFO";
+ case 0x59:
+ return "CMD_VERSION";
+ case 0x60:
+ return "CMD_DE_SENSE";
+ case 0x61:
+ return "CMD_DE_SET_TIME";
+ case 0x62:
+ return "CMD_DE_SETDATA_READ";
+ case 0x63:
+ return "CMD_DE_BVDATA_READ";
+ case 0x64:
+ return "CMD_DE_EVDATA_READ";
+ case 0x65:
+ return "CMD_DE_EVDATA_FIX";
+ case 0x66:
+ return "CMD_DE_READ_CASSETTE";
+ case 0x70:
+ return "CMD_DE_LOCK";
+ case 0x71:
+ return "CMD_DE_UNLOCK";
+ case 0x73:
+ return "CMD_DE_CNTSTART";
+ case 0x74:
+ return "CMD_DE_CNTEND";
+ case 0x75:
+ return "CMD_DE_STORESTART";
+ case 0x76:
+ return "CMD_DE_CANCEL";
+ case 0x77:
+ return "CMD_DE_RESET";
+ case 0x78:
+ return "CMD_DE_TRANSACTION_READ";
+ case 0x79:
+ return "CMD_DE_DEALFORGOTTEN";
+ case 0x80:
+ return "CMD_GDB_SENSE";
+ case 0x81:
+ return "CMD_GDB_BVDATA_READ";
+ case 0x82:
+ return "CMD_GDB_SETDATA";
+ case 0x83:
+ return "CMD_GDB_SETRJSERIAL";
+ case 0x84:
+ return "CMD_GDB_SETDATAREAD";
+ case 0xA0:
+ return "CMD_GDB_GETSERIAL";
+ default:
+ return "Unknown Command";
+ }
+ }
+
+ public void ClearDenomTable()
+ {
+ for (int x = 0; x < GetDenomTableElements(); x++)
+ {
+ if (mDenomTable[x].currency != null)
+ {
+ mDenomTable[x].currency = null;
+ }
+ mDenomTable[x].mCurrenyIndex = 0;
+ mDenomTable[x].currency = null;
+ mDenomTable[x].issue = 0;
+ mDenomTable[x].mDenomValue = 0;
+ }
+
+ mDenominationCount = 0;
+ }
+
+ public CDenom[] GetDenomTablePtr()
+ {
+ return mDenomTable;
+ }
+
+ public int GetDenomTableElements()
+ {
+ return mDenomTable.Length;
+ }
+
+ public void SetDenominationCount(int c)
+ {
+ mDenominationCount = c;
+ }
+ }
+
+ public class Constants
+ {
+ public const byte D_DLE = 0x10;
+ public const byte D_STX = 0x02;
+ public const byte D_NAK = 0x15;
+ public const byte D_ETX = 0x03;
+ public const byte E_OK = 0x00;
+ public const byte E_NG = 0x01;
+ public const byte E_NG_FILE = 0x02;
+ public const byte E_NG_DAT = 0x03;
+ public const byte E_NG_SEND = 0x04;
+ public const byte E_NG_RECV = 0x05;
+ public const int DATLEN_GDBSense_Cnt = 86;
+ }
+
+ public class SendDataStruct
+ {
+ public byte ret;
+ public byte cmd;
+ public int leng;
+ public byte bcc;
+ public byte[] dat = new byte[1024];
+ }
+
+ public class RecvData
+ {
+ public byte ret;
+ public byte cmd;
+ public int leng;
+ public byte bcc;
+ public byte[] dat = new byte[8192];
+ }
+
+ public enum SendStatus
+ {
+ SEND_NON,
+ SEND_RECV_OK,
+ SEND_DAT_ERR,
+ SEND_ERR,
+ RECV_ERR
+ }
+
+ public enum Mode
+ {
+ MODE_DEPOSIT = 1,
+ MODE_COUNT = 2,
+ MODE_MANUAL = 3,
+ MODE_BATCH = 4,
+ MODE_CLOSE = 5,
+ MODE_TCLS = 6,
+ MODE_CHANGE = 7,
+ MODE_COLLECTION = 8,
+ MODE_SET = 9,
+ MODE_SECERROR = 14
+ }
+
+ public enum Currency
+ {
+ CURRENCY01, //‘æ‚P’ʉÝ
+ CURRENCY02, //‘æ‚Q’ʉÝ
+ CURRENCY03, //‘æ‚R’ʉÝ
+ CURRENCY04, //‘æ‚S’ʉÝ
+ CURRENCY05, //‘æ‚T’ʉÝ
+ CURRENCY06, //‘æ‚U’ʉÝ
+ CURRENCY07, //‘æ‚V’ʉÝ
+ CURRENCY_MLT, //’ʉ݃}ƒ‹ƒ`
+ }
+
+ enum SR2
+ {
+ SR2_init = 0x01,
+ SR2_wait = 0x04,
+ SR2_cntwait = 0x07,
+ SR2_cnting = 0x09,
+ SR2_check = 0x0a,
+ SR2_seting = 0x0d,
+ SR2_reset = 0x1b,
+ SR2_rst_wait = 0x1c,
+ SR2_ras = 0x1d,
+ SR2_batch = 0x1f,
+ };
+
+ public enum Command
+ {
+ CMD_NULL = 0, // uninitialised / not a command value
+ CMD_SENSE = 0x22,
+ CMD_ST_UPLOAD = 0x40,
+ CMD_END_UPLOAD = 0x41,
+ CMD_REQ_UPLOAD = 0x44,
+ CMD_ST_DOWNLOAD = 0x45,
+ CMD_END_DOWNLOAD = 0x46,
+ CMD_REQ_DOWNLOAD = 0x49,
+ CMD_P_UPDATE = 0x4A,
+ CMD_GETFILEINFO = 0x4D,
+ CMD_VERSION = 0x59,
+ CMD_DE_SENSE = 0x60,
+ CMD_DE_SET_TIME = 0x61,
+ CMD_DE_SETDATA_READ = 0x62,
+ CMD_DE_BVDATA_READ = 0x63,
+ CMD_DE_EVDATA_READ = 0x64,
+ CMD_DE_EVDATA_FIX = 0x65,
+ CMD_DE_READ_CASSETTE = 0x66,
+ CMD_DE_LOCK = 0x70,
+ CMD_DE_UNLOCK = 0x71,
+ CMD_DE_CNTSTART = 0x73,
+ CMD_DE_CNTEND = 0x74,
+ CMD_DE_STORESTART = 0x75,
+ CMD_DE_CANCEL = 0x76,
+ CMD_DE_RESET = 0x77,
+ CMD_DE_TRANSACTION_READ = 0x78,
+ CMD_DE_DEALFORGOTTEN = 0x79,
+ CMD_GDB_SENSE = 0x80,
+ CMD_GDB_BVDATA_READ = 0x81,
+ CMD_GDB_SETDATA = 0x82,
+ CMD_GDB_SETRJSERIAL = 0x83,
+ CMD_GDB_SETDATAREAD = 0x84,
+ CMD_GDB_GETSERIAL = 0xA0,
+ }
+
+ public class Com232C
+ {
+ SerialPort serialPort = null;
+ public Com232C(SerialPort _serialPort)
+ {
+ this.serialPort = _serialPort;
+ }
+ public byte send_dat(byte[] buf, int size)
+ {
+ //Debug.WriteLine(DE70_CMD.ByteArrayToString(buf, 0, size));
+ try
+ {
+ serialPort.Write(buf, 0, size);
+ return Constants.E_OK;
+ }
+ catch (Exception e)
+ {
+ try
+ {
+ Log.Fatal(e, "DE70_send_dat");
+ if (serialPort.IsOpen)
+ serialPort.Close();
+ serialPort.Open();
+ }
+ catch (Exception e2)
+ {
+ Log.Fatal(e2,"DE70_send_dat2");
+ }
+
+ }
+
+ // Implement serial communication send function
+ return Constants.E_NG;
+ }
+
+ public int rcv_dat(byte[] buf, int pos, int size)
+ {
+ try
+ {
+ return serialPort.Read(buf, pos, size);
+ }
+ catch (Exception e)
+ {
+ try
+ {
+ Log.Fatal(e, "DE70_rcv_dat");
+ if (serialPort.IsOpen)
+ serialPort.Close();
+ serialPort.Open();
+ }
+ catch (Exception e2)
+ {
+ Log.Fatal(e2, "DE70_rcv_dat2");
+ }
+
+ }
+ return -1;
+ // Implement serial communication receive function
+
+ }
+ }
+
+ public class LockParam
+ {
+ public int Register;
+ public int ID;
+ public int TransactionNo;
+ public Mode mode;
+ public Currency Currency;
+ public Gengai Gengai = new Gengai();
+ public Batch Batch = new Batch();
+ public Cassette Cassette = new Cassette();
+ }
+
+ public class Gengai
+ {
+ public double amount;
+ }
+
+ public class Batch
+ {
+ public int Regi_num;
+ public byte[] batch_num = new byte[64];
+ }
+
+ public class Cassette
+ {
+ public byte[] CassetteID = new byte[16];
+ }
+
+ public class CDenom
+ {
+ public int mCurrenyIndex;
+ public string currency;
+ public int issue;
+ public double mDenomValue;
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/63/635f5ec486f0ccc99f72fa28b483eb5a77e22eb0.svn-base b/.svn/pristine/63/635f5ec486f0ccc99f72fa28b483eb5a77e22eb0.svn-base
new file mode 100644
index 0000000..6373cc5
--- /dev/null
+++ b/.svn/pristine/63/635f5ec486f0ccc99f72fa28b483eb5a77e22eb0.svn-base
@@ -0,0 +1 @@
+df1ae7c01d7f8de40ea1f5101026da0499ffce349329d7a8d73396c57ddce9d2
diff --git a/.svn/pristine/63/63d104a1ed3803ae8d7f980b1bc4ebc1197ee59a.svn-base b/.svn/pristine/63/63d104a1ed3803ae8d7f980b1bc4ebc1197ee59a.svn-base
new file mode 100644
index 0000000..fe06c8e
--- /dev/null
+++ b/.svn/pristine/63/63d104a1ed3803ae8d7f980b1bc4ebc1197ee59a.svn-base
@@ -0,0 +1,44 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class InformationUC : UserControl
+ {
+ public InformationUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor)
+ {
+ lblInfor.Text = strInfor;
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ }
+ }
+}
diff --git a/.svn/pristine/66/6644489ff0bf83970a06f00bd6bf53fe1ee00188.svn-base b/.svn/pristine/66/6644489ff0bf83970a06f00bd6bf53fe1ee00188.svn-base
new file mode 100644
index 0000000..47c4533
--- /dev/null
+++ b/.svn/pristine/66/6644489ff0bf83970a06f00bd6bf53fe1ee00188.svn-base
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
diff --git a/.svn/pristine/66/667edb3ffc5b3d0eecec5908e1bd977875d4ab81.svn-base b/.svn/pristine/66/667edb3ffc5b3d0eecec5908e1bd977875d4ab81.svn-base
new file mode 100644
index 0000000..9c672c4
Binary files /dev/null and b/.svn/pristine/66/667edb3ffc5b3d0eecec5908e1bd977875d4ab81.svn-base differ
diff --git a/.svn/pristine/67/67438f353b8f649f7b3a9a460f19383c17896859.svn-base b/.svn/pristine/67/67438f353b8f649f7b3a9a460f19383c17896859.svn-base
new file mode 100644
index 0000000..ce568e5
--- /dev/null
+++ b/.svn/pristine/67/67438f353b8f649f7b3a9a460f19383c17896859.svn-base
@@ -0,0 +1,1399 @@
+namespace DE70_CMDv2
+{
+ using SafeBagDE70;
+ using System;
+ using System.Diagnostics;
+ using System.IO;
+ using System.IO.Ports;
+ using System.Text;
+
+ public class CCmdRsp
+ {
+ public static CDenom[] mDenomTable = new CDenom[128];
+ public static int mDenominationCount;
+ public static string mSelectedCurrency;
+ public static int miSelectedCurrency;
+ private SerialPort serialPort = null;
+ private int m_all_sendsize;
+ private int m_all_recvsize;
+ private byte[] recv_buf = new byte[8192];
+ private byte[] m_send_buf = new byte[8192];
+ public RecvData recv_dat = new RecvData();
+ private SendDataStruct send_dat = new SendDataStruct();
+ private SendStatus cmd_result;
+ private LockParam lock_param = new LockParam();
+ private byte[] recv_serialset = new byte[256];
+ private Com232C m_ccom = null;
+
+ public CCmdRsp(SerialPort _serialPort)
+ {
+ serialPort = _serialPort;
+ m_ccom = new Com232C(_serialPort);
+ m_all_sendsize = 0;
+ m_all_recvsize = 0;
+ Array.Clear(recv_buf, 0, recv_buf.Length);
+ Array.Clear(m_send_buf, 0, m_send_buf.Length);
+ Array.Clear(recv_dat.dat, 0, recv_dat.dat.Length);
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ cmd_result = SendStatus.SEND_NON;
+ lock_param.Register = 1;
+ lock_param.ID = 1;
+ lock_param.TransactionNo = 1;
+ lock_param.mode = Mode.MODE_DEPOSIT;
+ lock_param.Currency = Currency.CURRENCY01; // first currency
+ lock_param.Gengai.amount = 0;
+ lock_param.Batch.Regi_num = 1;
+ Array.Clear(lock_param.Batch.batch_num, 0, lock_param.Batch.batch_num.Length);
+ Array.Clear(lock_param.Cassette.CassetteID, 0, lock_param.Cassette.CassetteID.Length);
+ Array.Clear(recv_serialset, 0, recv_serialset.Length);
+ }
+
+ public byte SendData()
+ {
+ byte ret = m_ccom.send_dat(m_send_buf, m_all_sendsize);
+ return ret;
+ }
+
+ public int SendSerialSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDeSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDeviceSettingDataReq()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = 0x62;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDenomiRead2()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_BVDATA_READ;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSerialSet(byte[] dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETDATA;
+ send_dat.leng = 1 + 20;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ Array.Copy(dat, 0, send_dat.dat, 0, 20);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSetRJSerial()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETRJSERIAL;
+ send_dat.leng = 24;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ send_dat.dat[0] = 0x01;
+ send_dat.dat[1] = (byte)'I';
+ send_dat.dat[2] = (byte)'N';
+ send_dat.dat[3] = (byte)'R';
+ send_dat.dat[4] = 0x00;
+ send_dat.dat[5] = 5;
+ send_dat.dat[6] = 8;
+ send_dat.dat[7] = (byte)'4';
+ send_dat.dat[8] = (byte)'K';
+ send_dat.dat[9] = (byte)'T';
+ send_dat.dat[10] = (byte)'4';
+ send_dat.dat[11] = (byte)'7';
+ send_dat.dat[12] = (byte)'6';
+ send_dat.dat[13] = (byte)'6';
+ send_dat.dat[14] = (byte)'1';
+ send_dat.dat[15] = (byte)'#';
+ send_dat.dat[16] = (byte)'#';
+ send_dat.dat[17] = (byte)'#';
+ send_dat.dat[18] = (byte)'#';
+ send_dat.dat[19] = (byte)'#';
+ send_dat.dat[20] = (byte)'#';
+ send_dat.dat[21] = (byte)'#';
+ send_dat.dat[22] = (byte)'#';
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSerialSetRead()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETDATAREAD;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ Array.Copy(recv_dat.dat, 13, recv_serialset, 0, recv_serialset.Length);
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendGetSerial(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_GETSERIAL;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendFreeDat()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = 0x00;
+ send_dat.leng = 1 + 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ if (!File.Exists("send.bin"))
+ {
+ cmd_result = SendStatus.SEND_DAT_ERR;
+ return Constants.E_NG_FILE;
+ }
+
+ byte[] fileData = File.ReadAllBytes("send.bin");
+ send_dat.cmd = fileData[0];
+ Array.Copy(fileData, 1, send_dat.dat, 0, fileData.Length - 1);
+ send_dat.leng = fileData.Length;
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDataSet()
+ {
+ int sendsize = 0;
+ byte bcc = 0;
+ byte[] len_dat = new byte[3];
+ Array.Clear(m_send_buf, 0, m_send_buf.Length);
+
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ m_send_buf[sendsize++] = Constants.D_STX;
+ SetLen(len_dat, send_dat.leng);
+ for (int i = 0; i < 3; i++)
+ {
+ if (len_dat[i] == Constants.D_DLE)
+ {
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ }
+ m_send_buf[sendsize++] = len_dat[i];
+ bcc ^= len_dat[i];
+ }
+
+ m_send_buf[sendsize++] = send_dat.cmd;
+ bcc ^= send_dat.cmd;
+ for (int i = 0; i < send_dat.leng - 1; i++)
+ {
+ if (send_dat.dat[i] == Constants.D_DLE)
+ {
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ }
+ m_send_buf[sendsize++] = send_dat.dat[i];
+ bcc ^= send_dat.dat[i];
+ }
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ m_send_buf[sendsize++] = Constants.D_ETX;
+ bcc ^= Constants.D_ETX;
+ m_send_buf[sendsize++] = bcc;
+ send_dat.bcc = bcc;
+
+ m_all_sendsize = sendsize;
+
+ return Constants.E_OK;
+ }
+
+ public int SetLen(byte[] dat, int size)
+ {
+ if (size <= 999)
+ {
+ dat[0] = (byte)((size / 100) | 0x30);
+ dat[1] = (byte)(((size % 100) / 10) | 0x30);
+ dat[2] = (byte)((size % 100) % 10 | 0x30);
+ }
+ else
+ {
+ dat[0] = (byte)((size / 0x010000) | 0x70);
+ dat[1] = (byte)((size % 0x010000) / 0x100);
+ dat[2] = (byte)((size % 0x010000) % 0x100);
+ }
+ return Constants.E_OK;
+ }
+
+ public byte WaitRsp()
+ {
+ int pos_r = 0;
+ int size;
+ int i;
+ bool dle_flg = false;
+ Array.Clear(recv_buf, 0, recv_buf.Length);
+ recv_dat.ret = Constants.E_OK;
+ recv_dat.cmd = 0x00;
+ recv_dat.leng = 0;
+ recv_dat.bcc = 0x00;
+ Array.Clear(recv_dat.dat, 0, recv_dat.dat.Length);
+
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 1);
+ if (size != 1)
+ {
+ return Constants.E_NG;
+ }
+ if (recv_buf[pos_r] == Constants.D_NAK)
+ {
+ return Constants.E_NG;
+ }
+ if (recv_buf[pos_r] != Constants.D_DLE)
+ {
+ return Constants.E_NG;
+ }
+ pos_r++;
+
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 1);
+ if (recv_buf[pos_r] != Constants.D_STX || size != 1)
+ {
+ return Constants.E_NG;
+ }
+ pos_r++;
+
+ if (WaitRspLen(ref recv_buf, pos_r, ref recv_dat.leng, out size) != Constants.E_OK)
+ {
+ return Constants.E_NG;
+ }
+ pos_r += size;
+
+ if (m_ccom.rcv_dat(recv_buf, pos_r, 1) != 1)
+ {
+ return Constants.E_NG;
+ }
+ recv_dat.cmd = recv_buf[pos_r];
+ pos_r++;
+
+ if (recv_dat.cmd == (byte)Command.CMD_GDB_GETSERIAL)
+ {
+ //Tạo buffer để nhận dữ liệu
+ //size = m_ccom.rcv_dat(recv_buf, pos_r, recv_dat.leng - 1);
+ int _size = 0;
+ int _pos_r = pos_r;
+ while (_size < recv_dat.leng - 1)
+ {
+ var _tsize = m_ccom.rcv_dat(recv_buf, _pos_r, recv_dat.leng - 1 - _size);
+ _size += _tsize;
+ _pos_r += _tsize;
+ }
+ size = _size;
+ //pos_r = _pos_r;
+ if (size != recv_dat.leng - 1)
+ {
+ return Constants.E_NG;
+ }
+ Array.Copy(recv_buf, pos_r, recv_dat.dat, 0, recv_dat.leng - 1);
+ pos_r += size;
+ }
+ else
+ {
+ i = 0;
+ while (i < recv_dat.leng - 1)
+ {
+ if (m_ccom.rcv_dat(recv_buf, pos_r, 1) != 1)
+ {
+ return Constants.E_NG;
+ }
+ if (!dle_flg && recv_buf[pos_r] == Constants.D_DLE)
+ {
+ pos_r++;
+ dle_flg = true;
+ continue;
+ }
+ recv_dat.dat[i] = recv_buf[pos_r];
+ pos_r++;
+ i++;
+ dle_flg = false;
+ }
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 3);
+ recv_dat.bcc = recv_buf[pos_r + 2];
+ pos_r += size;
+ }
+ m_all_recvsize = pos_r;
+ return Constants.E_OK;
+ }
+
+ public int WaitRspLen(ref byte[] dat, int pos, ref int leng, out int size)
+ {
+ int initialPos = pos;
+
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if ((dat[pos] & 0xF0) == 0x70)
+ {
+ leng = (dat[pos] & 0x0F) * 0x10000;
+ pos++;
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (dat[pos] == Constants.D_DLE)
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ pos++;
+ }
+ leng += dat[pos] * 0x100;
+ pos++;
+
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (dat[pos] == Constants.D_DLE)
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ pos++;
+ }
+ leng += dat[pos];
+ pos++;
+ }
+ else
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 2) != 2)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (((dat[pos] & 0x30) != 0x30) || ((dat[pos + 1] & 0x30) != 0x30) || ((dat[pos + 2] & 0x30) != 0x30))
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ leng = (dat[pos] & 0x0F) * 100 + (dat[pos + 1] & 0x0F) * 10 + (dat[pos + 2] & 0x0F);
+ pos += 3;
+ }
+
+ size = pos - initialPos;
+ return Constants.E_OK;
+ }
+
+ public string GetSendDat(bool oneLine)
+ {
+ StringBuilder str = new StringBuilder();
+ StringBuilder dat = new StringBuilder();
+
+ string cmd = GetCommandName(send_dat.cmd);
+
+ dat.AppendFormat("SEND {0} L:{1} ", cmd, send_dat.leng);
+ str.Append(dat);
+
+ if (!oneLine)
+ {
+ str.Append("DATA:");
+ for (int i = 0; i < send_dat.leng - 1; i++)
+ {
+ dat.AppendFormat("{0:X2} ", send_dat.dat[i]);
+ }
+ str.Append(dat);
+ str.Append("\r\n");
+
+ if (cmd_result == SendStatus.SEND_RECV_OK || cmd_result == SendStatus.RECV_ERR)
+ {
+ for (int i = 0; i < m_all_sendsize; i++)
+ {
+ dat.AppendFormat("{0:X2} ", m_send_buf[i]);
+ }
+ str.Append(dat);
+ }
+ else if (cmd_result == SendStatus.SEND_DAT_ERR || cmd_result == SendStatus.SEND_ERR)
+ {
+ str.Append("send err");
+ }
+ str.Append("\r\n");
+ }
+ else
+ {
+ str.Append(" >> ");
+ str.Append(SetStText());
+ }
+
+ return str.ToString();
+ }
+
+ public string GetRecvDat()
+ {
+ StringBuilder str = new StringBuilder();
+ StringBuilder dat = new StringBuilder();
+
+ if (cmd_result == SendStatus.SEND_RECV_OK)
+ {
+ dat.AppendFormat("RECV CM:0x{0:X2} L:{1} ", recv_dat.cmd, recv_dat.leng);
+ str.Append(dat);
+ str.Append("DATA:");
+ for (int i = 0; i < recv_dat.leng - 1; i++)
+ {
+ dat.AppendFormat("{0:X2} ", recv_dat.dat[i]);
+ str.Append(dat);
+ }
+ str.Append("Raw: ");
+
+ for (int i = 0; i < m_all_recvsize; i++)
+ {
+ dat.AppendFormat("{0:X2} ", recv_buf[i]);
+ str.Append(dat);
+ }
+ }
+ else if (cmd_result == SendStatus.RECV_ERR)
+ {
+ str.Append("recv err");
+ }
+ str.Append("\r\n");
+ return str.ToString();
+ }
+
+ public int ImgSave(FileStream file)
+ {
+ if (send_dat.ret == Constants.E_OK && recv_dat.ret == Constants.E_OK)
+ {
+ file.Write(recv_dat.dat, 0, recv_dat.leng - 1);
+ }
+ return Constants.E_OK;
+ }
+
+ public int SendXXCmd(byte cmd)
+ {
+ return SendXXCmd(new byte[] { cmd }, 1);
+ }
+
+ public int SendXXCmd(byte[] cmd, int len)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = cmd[0];
+ send_dat.leng = len;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ for (int x = 0; x < len - 1; x++)
+ {
+ send_dat.dat[x] = cmd[x + 1];
+ }
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendEventRead(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_EVDATA_READ;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendEventFix(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_EVDATA_FIX;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendLock()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_LOCK;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ SetLockParam();
+
+ SendDataSet();
+
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+ public LockParam GetLockParam()
+ {
+ return lock_param;
+ }
+ public void SetLockParam()
+ {
+ int size;
+ uint amount_i = 0;
+ uint amount_f = 0;
+
+ send_dat.dat[0] = 0x00;
+ send_dat.dat[1] = (byte)((lock_param.Register & 0xff00) >> 8);
+ send_dat.dat[2] = (byte)(lock_param.Register & 0xff);
+ send_dat.dat[3] = (byte)((lock_param.ID & 0xff000000) >> 24);
+ send_dat.dat[4] = (byte)((lock_param.ID & 0xff0000) >> 16);
+ send_dat.dat[5] = (byte)((lock_param.ID & 0xff00) >> 8);
+ send_dat.dat[6] = (byte)(lock_param.ID & 0xff);
+ send_dat.dat[7] = 9;
+ send_dat.dat[8] = (byte)((lock_param.TransactionNo & 0xff00) >> 8);
+ send_dat.dat[9] = (byte)(lock_param.TransactionNo & 0xff);
+ send_dat.dat[10] = (byte)lock_param.mode;
+ send_dat.dat[11] = (byte)(lock_param.Currency == Currency.CURRENCY_MLT ? 10 : (byte)lock_param.Currency);
+
+ switch (lock_param.mode)
+ {
+ case Mode.MODE_COUNT:
+ send_dat.dat[12] = 0;
+ size = 1 + 12 + 1;
+ break;
+ case Mode.MODE_MANUAL:
+ send_dat.dat[12] = 0;
+ amount_i = (uint)lock_param.Gengai.amount;
+ amount_f = (uint)((lock_param.Gengai.amount * 1000) - amount_i * 1000);
+ send_dat.dat[13] = (byte)((amount_i & 0xff000000) >> 24);
+ send_dat.dat[14] = (byte)((amount_i & 0xff0000) >> 16);
+ send_dat.dat[15] = (byte)((amount_i & 0xff00) >> 8);
+ send_dat.dat[16] = (byte)(amount_i & 0xff);
+ send_dat.dat[17] = (byte)((amount_f & 0xff00) >> 8);
+ send_dat.dat[18] = (byte)(amount_f & 0xff);
+ size = 1 + 12 + 7;
+ break;
+ case Mode.MODE_BATCH:
+ send_dat.dat[12] = (byte)lock_param.Batch.Regi_num;
+ Array.Copy(lock_param.Batch.batch_num, 0, send_dat.dat, 13, 64);
+ size = 1 + 12 + 65;
+ break;
+ case Mode.MODE_CHANGE:
+ case Mode.MODE_COLLECTION:
+ Array.Copy(lock_param.Cassette.CassetteID, 0, send_dat.dat, 12, 16);
+ size = 1 + 12 + 16;
+ break;
+ case Mode.MODE_SET:
+ send_dat.dat[12] = 5;
+ send_dat.dat[13] = 4;
+ send_dat.dat[14] = 2;
+ send_dat.dat[15] = 0;
+ send_dat.dat[16] = 5;
+ size = 1 + 12 + 5;
+ break;
+ default:
+ size = 1 + 12;
+ break;
+ }
+ send_dat.leng = size;
+ }
+
+ public string SetStText()
+ {
+ StringBuilder text = new StringBuilder();
+
+ switch (cmd_result)
+ {
+ case SendStatus.SEND_ERR:
+ case SendStatus.SEND_DAT_ERR:
+ text.Append("SEND_ERR");
+ break;
+ case SendStatus.RECV_ERR:
+ text.Append("RECV_ERR");
+ break;
+ case SendStatus.SEND_RECV_OK:
+ text.Append("SR1");
+ text.Append(GetSR1Summary(recv_dat.dat[0]));
+ text.Append(", ");
+
+ text.AppendFormat("SR2: ");
+ text.Append(GetSR2Summary(recv_dat.dat[1]));
+ text.Append(", ");
+
+ if (recv_dat.leng >= 15)
+ {
+ if (recv_dat.cmd == (byte)Command.CMD_DE_SENSE || recv_dat.cmd == (byte)Command.CMD_GDB_SENSE)
+ {
+ text.AppendFormat("Sent/unsent events:{0}/{1} ",
+ recv_dat.dat[13] * 0x0100 + recv_dat.dat[14],
+ recv_dat.dat[15] * 0x0100 + recv_dat.dat[16]);
+ if (recv_dat.leng == 84 || recv_dat.leng == 86)
+ {
+ text.Append(GetSummaryTotal(recv_dat.dat, 19));
+ }
+ }
+ }
+ break;
+ case SendStatus.SEND_NON:
+ default:
+ text.Append("SEND_NON");
+ break;
+ }
+ return text.ToString();
+ }
+
+ public string GetSummaryTotal(byte[] counts, int numDenoms, bool wordcounts = true)
+ {
+ StringBuilder ret = new StringBuilder();
+ double[] total = new double[10];
+ string[] pCurrencyID = new string[10];
+
+ Array.Clear(total, 0, total.Length);
+ Array.Clear(pCurrencyID, 0, pCurrencyID.Length);
+
+ if (mDenominationCount > 0 && mDenominationCount < 65)
+ {
+ numDenoms = Math.Min(numDenoms, mDenominationCount);
+
+ for (int x = 0; x < numDenoms; x++)
+ {
+ if (mDenomTable[x].mCurrenyIndex < total.Length)
+ {
+ int noteCount;
+ if (wordcounts)
+ {
+ noteCount = counts[x * 2] * 256 + counts[x * 2 + 1];
+ }
+ else
+ {
+ noteCount = counts[x];
+ }
+ total[mDenomTable[x].mCurrenyIndex] += mDenomTable[x].mDenomValue * noteCount;
+ pCurrencyID[mDenomTable[x].mCurrenyIndex] = mDenomTable[x].currency;
+ }
+ }
+ ret.Append("Counted: ");
+ for (int x = 0; x < total.Length; x++)
+ {
+ if (total[x] != 0)
+ {
+ ret.AppendFormat(" {0}: {1:0.00}", pCurrencyID[x] ?? "???", total[x]);
+ }
+ }
+ }
+ else
+ {
+ ret.Append(" No denom data");
+ }
+
+ return ret.ToString();
+ }
+
+ public string GetSR1Summary(byte sr1)
+ {
+ StringBuilder text = new StringBuilder();
+
+ text.AppendFormat("(0x{0:X2}): ", sr1);
+ switch (sr1)
+ {
+ case 0x40:
+ text.Append("CMD OK");
+ break;
+ case 0x41:
+ text.Append("No execution");
+ break;
+ case 0x42:
+ text.Append("Store fail,");
+ break;
+ case 0x43:
+ text.Append("Unknown command");
+ break;
+ case 0x44:
+ text.Append("Length error");
+ break;
+ case 0x46:
+ text.Append("CMD error (not executed)");
+ break;
+ case 0x47:
+ text.Append("Local processing");
+ break;
+ case 0x48:
+ text.Append("Already occupied");
+ break;
+ case 0x49:
+ text.Append("Abnormal data");
+ break;
+ default:
+ text.Append("Unknown SR1");
+ break;
+ }
+ return text.ToString();
+ }
+ public string GetS1Summary(byte s1)
+ {
+ string text = string.Format("(0x{0:X}): {1}{2}{3}{4}{5}{6}{7}{8}", s1,
+ (s1 & 0x80) != 0 ? "Locked, " : "Not locked, ",
+ (s1 & 0x40) != 0 ? "Escrow door closed, " : "Escrow door open, ",
+ (s1 & 0x20) != 0 ? "" : "bit5=false, ",
+ (s1 & 0x10) != 0 ? "" : "bit4=false, ",
+ (s1 & 0x08) != 0 ? "Cassette full, " : "Cassette not full, ",
+ (s1 & 0x04) != 0 ? "bit2=true, " : "",
+ (s1 & 0x02) != 0 ? "bit1=true, " : "",
+ (s1 & 0x01) != 0 ? "Dirty sensor, " : "No dirty sensor, ");
+
+ text = text.TrimEnd(',', ' ');
+
+ return text;
+ }
+ public string GetSR2Summary(byte sr2)
+ {
+ StringBuilder text = new StringBuilder();
+
+ text.AppendFormat("(0x{0:X2}): ", sr2);
+ switch (sr2)
+ {
+ case 0x01:
+ text.Append("Initialising");
+ break;
+ case 0x1c:
+ text.Append("Initialisation error (cycle power)");
+ break;
+ case 0x1b:
+ text.Append("Resetting");
+ break;
+ case 0x0a:
+ text.Append("Waiting for notes to be removed");
+ break;
+ case 0x04:
+ text.Append("Stand by");
+ break;
+ case 0x07:
+ text.Append("Ready to count");
+ break;
+ case 0x09:
+ text.Append("Counting/batch");
+ break;
+ case 0x1f:
+ text.Append("Batch processing");
+ break;
+ case 0x0d:
+ text.Append("Setting");
+ break;
+ default:
+ text.Append("Unknown SR2");
+ break;
+ }
+ return text.ToString();
+ }
+
+ public int GetSerialNum(out ushort num)
+ {
+ ushort serial_num;
+
+ if (recv_dat.cmd == (byte)Command.CMD_GDB_SENSE && recv_dat.leng == Constants.DATLEN_GDBSense_Cnt)
+ {
+ serial_num = (ushort)(recv_dat.dat[83] * 0x100 + recv_dat.dat[84]);
+ if (serial_num <= 1000)
+ {
+ num = serial_num;
+ return Constants.E_OK;
+ }
+ }
+ num = 0x00;
+ return Constants.E_NG;
+ }
+
+ public bool ChkCntEnd()
+ {
+ return recv_dat.cmd != (byte)Command.CMD_GDB_SENSE || recv_dat.dat[1] != (byte)SR2.SR2_cnting;
+ }
+
+ public void GetRecvSerialSet(byte[] dat)
+ {
+ Array.Copy(recv_serialset, dat, recv_serialset.Length);
+ }
+
+ public override string ToString()
+ {
+ return GetSendDat(true);
+ }
+
+ public int GetSendDatLength()
+ {
+ return send_dat.leng;
+ }
+
+ public int GetRecDatLength()
+ {
+ return recv_dat.leng - 1;
+ }
+
+ public byte[] GetSendDatPtr()
+ {
+ return send_dat.dat;
+ }
+
+ public byte[] GetRecDatPtr()
+ {
+ return recv_dat.dat;
+ }
+
+ public Command GetCmdByte()
+ {
+ return (Command)send_dat.cmd;
+ }
+
+ public string GetCommandName(byte cmd)
+ {
+ switch (cmd)
+ {
+ case 0x22:
+ return "CMD_SENSE";
+ case 0x40:
+ return "CMD_ST_UPLOAD";
+ case 0x41:
+ return "CMD_END_UPLOAD";
+ case 0x44:
+ return "CMD_REQ_UPLOAD";
+ case 0x45:
+ return "CMD_ST_DOWNLOAD";
+ case 0x46:
+ return "CMD_END_DOWNLOAD";
+ case 0x49:
+ return "CMD_REQ_DOWNLOAD";
+ case 0x4A:
+ return "CMD_P_UPDATE";
+ case 0x4D:
+ return "CMD_GETFILEINFO";
+ case 0x59:
+ return "CMD_VERSION";
+ case 0x60:
+ return "CMD_DE_SENSE";
+ case 0x61:
+ return "CMD_DE_SET_TIME";
+ case 0x62:
+ return "CMD_DE_SETDATA_READ";
+ case 0x63:
+ return "CMD_DE_BVDATA_READ";
+ case 0x64:
+ return "CMD_DE_EVDATA_READ";
+ case 0x65:
+ return "CMD_DE_EVDATA_FIX";
+ case 0x66:
+ return "CMD_DE_READ_CASSETTE";
+ case 0x70:
+ return "CMD_DE_LOCK";
+ case 0x71:
+ return "CMD_DE_UNLOCK";
+ case 0x73:
+ return "CMD_DE_CNTSTART";
+ case 0x74:
+ return "CMD_DE_CNTEND";
+ case 0x75:
+ return "CMD_DE_STORESTART";
+ case 0x76:
+ return "CMD_DE_CANCEL";
+ case 0x77:
+ return "CMD_DE_RESET";
+ case 0x78:
+ return "CMD_DE_TRANSACTION_READ";
+ case 0x79:
+ return "CMD_DE_DEALFORGOTTEN";
+ case 0x80:
+ return "CMD_GDB_SENSE";
+ case 0x81:
+ return "CMD_GDB_BVDATA_READ";
+ case 0x82:
+ return "CMD_GDB_SETDATA";
+ case 0x83:
+ return "CMD_GDB_SETRJSERIAL";
+ case 0x84:
+ return "CMD_GDB_SETDATAREAD";
+ case 0xA0:
+ return "CMD_GDB_GETSERIAL";
+ default:
+ return "Unknown Command";
+ }
+ }
+
+ public void ClearDenomTable()
+ {
+ for (int x = 0; x < GetDenomTableElements(); x++)
+ {
+ if (mDenomTable[x].currency != null)
+ {
+ mDenomTable[x].currency = null;
+ }
+ mDenomTable[x].mCurrenyIndex = 0;
+ mDenomTable[x].currency = null;
+ mDenomTable[x].issue = 0;
+ mDenomTable[x].mDenomValue = 0;
+ }
+
+ mDenominationCount = 0;
+ }
+
+ public CDenom[] GetDenomTablePtr()
+ {
+ return mDenomTable;
+ }
+
+ public int GetDenomTableElements()
+ {
+ return mDenomTable.Length;
+ }
+
+ public void SetDenominationCount(int c)
+ {
+ mDenominationCount = c;
+ }
+ }
+
+ public class Constants
+ {
+ public const byte D_DLE = 0x10;
+ public const byte D_STX = 0x02;
+ public const byte D_NAK = 0x15;
+ public const byte D_ETX = 0x03;
+ public const byte E_OK = 0x00;
+ public const byte E_NG = 0x01;
+ public const byte E_NG_FILE = 0x02;
+ public const byte E_NG_DAT = 0x03;
+ public const byte E_NG_SEND = 0x04;
+ public const byte E_NG_RECV = 0x05;
+ public const int DATLEN_GDBSense_Cnt = 86;
+ }
+
+ public class SendDataStruct
+ {
+ public byte ret;
+ public byte cmd;
+ public int leng;
+ public byte bcc;
+ public byte[] dat = new byte[1024];
+ }
+
+ public class RecvData
+ {
+ public byte ret;
+ public byte cmd;
+ public int leng;
+ public byte bcc;
+ public byte[] dat = new byte[8192];
+ }
+
+ public enum SendStatus
+ {
+ SEND_NON,
+ SEND_RECV_OK,
+ SEND_DAT_ERR,
+ SEND_ERR,
+ RECV_ERR
+ }
+
+ public enum Mode
+ {
+ MODE_DEPOSIT = 1,
+ MODE_COUNT = 2,
+ MODE_MANUAL = 3,
+ MODE_BATCH = 4,
+ MODE_CLOSE = 5,
+ MODE_TCLS = 6,
+ MODE_CHANGE = 7,
+ MODE_COLLECTION = 8,
+ MODE_SET = 9,
+ MODE_SECERROR = 14
+ }
+
+ public enum Currency
+ {
+ CURRENCY01, //‘æ‚P’ʉÝ
+ CURRENCY02, //‘æ‚Q’ʉÝ
+ CURRENCY03, //‘æ‚R’ʉÝ
+ CURRENCY04, //‘æ‚S’ʉÝ
+ CURRENCY05, //‘æ‚T’ʉÝ
+ CURRENCY06, //‘æ‚U’ʉÝ
+ CURRENCY07, //‘æ‚V’ʉÝ
+ CURRENCY_MLT, //’ʉ݃}ƒ‹ƒ`
+ }
+
+ enum SR2
+ {
+ SR2_init = 0x01,
+ SR2_wait = 0x04,
+ SR2_cntwait = 0x07,
+ SR2_cnting = 0x09,
+ SR2_check = 0x0a,
+ SR2_seting = 0x0d,
+ SR2_reset = 0x1b,
+ SR2_rst_wait = 0x1c,
+ SR2_ras = 0x1d,
+ SR2_batch = 0x1f,
+ };
+
+ public enum Command
+ {
+ CMD_NULL = 0, // uninitialised / not a command value
+ CMD_SENSE = 0x22,
+ CMD_ST_UPLOAD = 0x40,
+ CMD_END_UPLOAD = 0x41,
+ CMD_REQ_UPLOAD = 0x44,
+ CMD_ST_DOWNLOAD = 0x45,
+ CMD_END_DOWNLOAD = 0x46,
+ CMD_REQ_DOWNLOAD = 0x49,
+ CMD_P_UPDATE = 0x4A,
+ CMD_GETFILEINFO = 0x4D,
+ CMD_VERSION = 0x59,
+ CMD_DE_SENSE = 0x60,
+ CMD_DE_SET_TIME = 0x61,
+ CMD_DE_SETDATA_READ = 0x62,
+ CMD_DE_BVDATA_READ = 0x63,
+ CMD_DE_EVDATA_READ = 0x64,
+ CMD_DE_EVDATA_FIX = 0x65,
+ CMD_DE_READ_CASSETTE = 0x66,
+ CMD_DE_LOCK = 0x70,
+ CMD_DE_UNLOCK = 0x71,
+ CMD_DE_CNTSTART = 0x73,
+ CMD_DE_CNTEND = 0x74,
+ CMD_DE_STORESTART = 0x75,
+ CMD_DE_CANCEL = 0x76,
+ CMD_DE_RESET = 0x77,
+ CMD_DE_TRANSACTION_READ = 0x78,
+ CMD_DE_DEALFORGOTTEN = 0x79,
+ CMD_GDB_SENSE = 0x80,
+ CMD_GDB_BVDATA_READ = 0x81,
+ CMD_GDB_SETDATA = 0x82,
+ CMD_GDB_SETRJSERIAL = 0x83,
+ CMD_GDB_SETDATAREAD = 0x84,
+ CMD_GDB_GETSERIAL = 0xA0,
+ }
+
+ public class Com232C
+ {
+ SerialPort serialPort = null;
+ public Com232C(SerialPort _serialPort)
+ {
+ this.serialPort = _serialPort;
+ }
+ public byte send_dat(byte[] buf, int size)
+ {
+ //Debug.WriteLine(DE70_CMD.ByteArrayToString(buf, 0, size));
+ try
+ {
+ serialPort.Write(buf, 0, size);
+ return Constants.E_OK;
+ }
+ catch (Exception e)
+ {
+ try
+ {
+ AppData.LogException("DE70_send_dat",e.ToString());
+ if (serialPort.IsOpen)
+ serialPort.Close();
+ serialPort.Open();
+ }
+ catch (Exception e2)
+ {
+ AppData.LogException("DE70_send_dat2", e2.ToString());
+ }
+
+ }
+
+ // Implement serial communication send function
+ return Constants.E_NG;
+ }
+
+ public int rcv_dat(byte[] buf, int pos, int size)
+ {
+ try
+ {
+ return serialPort.Read(buf, pos, size);
+ }
+ catch (Exception e)
+ {
+ try
+ {
+ AppData.LogException("DE70_rcv_dat", e.ToString());
+ if (serialPort.IsOpen)
+ serialPort.Close();
+ serialPort.Open();
+ }
+ catch (Exception e2)
+ {
+ AppData.LogException("DE70_rcv_dat2", e.ToString());
+ }
+
+ }
+ return -1;
+ // Implement serial communication receive function
+
+ }
+ }
+
+ public class LockParam
+ {
+ public int Register;
+ public int ID;
+ public int TransactionNo;
+ public Mode mode;
+ public Currency Currency;
+ public Gengai Gengai = new Gengai();
+ public Batch Batch = new Batch();
+ public Cassette Cassette = new Cassette();
+ }
+
+ public class Gengai
+ {
+ public double amount;
+ }
+
+ public class Batch
+ {
+ public int Regi_num;
+ public byte[] batch_num = new byte[64];
+ }
+
+ public class Cassette
+ {
+ public byte[] CassetteID = new byte[16];
+ }
+
+ public class CDenom
+ {
+ public int mCurrenyIndex;
+ public string currency;
+ public int issue;
+ public double mDenomValue;
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/69/692f3249b6e532612c852cc6df618abe7022c4cf.svn-base b/.svn/pristine/69/692f3249b6e532612c852cc6df618abe7022c4cf.svn-base
new file mode 100644
index 0000000..af5e0d0
Binary files /dev/null and b/.svn/pristine/69/692f3249b6e532612c852cc6df618abe7022c4cf.svn-base differ
diff --git a/.svn/pristine/6a/6a6a77011655f16d5535c4cbe40943fdfe6b2472.svn-base b/.svn/pristine/6a/6a6a77011655f16d5535c4cbe40943fdfe6b2472.svn-base
new file mode 100644
index 0000000..ff7ba76
--- /dev/null
+++ b/.svn/pristine/6a/6a6a77011655f16d5535c4cbe40943fdfe6b2472.svn-base
@@ -0,0 +1,311 @@
+using DE70_CMDv2;
+using Newtonsoft.Json.Linq;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ CDMSTATE=new CDMSTATE();
+ }
+ 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()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+ public static CDMSTATE? GetCDMState()
+ {
+ if(cCmdRsp!=null)
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv = cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ if(AppData.CDMSTATE!=null)
+ {
+ AppData.CDMSTATE.IsCassetteFull = data[17] & 0x08;
+ AppData.CDMSTATE.IsNotesInEscrow = data[4] & 0x01;
+ AppData.CDMSTATE.IsRejectPocketFull = data[3] & 0x40;
+ AppData.CDMSTATE.IsNotesInRejectPocket = data[3] & 0x10;
+ AppData.CDMSTATE.IsNotesInHopper = data[3] & 0x01;
+ AppData.CDMSTATE.RequestTime = DateTime.Now;
+ AppData.CDMSTATE.SR1 = data[0];
+ AppData.CDMSTATE.SR2 = data[1];
+ AppData.CDMSTATE.SR3 = data[2];
+ }
+
+ }
+ return AppData.CDMSTATE;
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+ public class CountSession
+ {
+ public CountSession()
+ {
+ for (int i = 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ public int CountingState { get; set; }//0-Normal End, 1-Timeout End
+ }
+
+ public class NotesInSession : INotifyPropertyChanged
+ {
+
+ private int _GenuineNotes;
+ public int GenuineNotes
+ {
+ get
+ {
+ return _GenuineNotes;
+ }
+ set
+ {
+ if (_GenuineNotes != value)
+ {
+ _GenuineNotes = value;
+ OnPropertyChanged(nameof(GenuineNotes));
+ }
+ }
+ }
+ private int _RejectNotes;
+ public int RejectNotes
+ {
+ get
+ {
+ return _RejectNotes;
+ }
+ set
+ {
+ if (_RejectNotes != value)
+ {
+ _RejectNotes = value;
+ OnPropertyChanged(nameof(RejectNotes));
+ }
+ }
+ }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public class CDMSTATE : INotifyPropertyChanged
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ public int IsNotesInHopper = 0;
+ private byte _SR1;
+ public byte SR1 {
+ get
+ {
+ return _SR1;
+ }
+ set
+ {
+ if (_SR1 != value)
+ {
+ _SR1 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR1));
+ }
+ }
+ }
+ private byte _SR2;
+ public byte SR2
+ {
+ get
+ {
+ return _SR2;
+ }
+ set
+ {
+ if (_SR2 != value)
+ {
+ _SR2 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR2));
+ }
+ }
+ }
+ private byte _SR3;
+ public byte SR3
+ {
+ get
+ {
+ return _SR3;
+ }
+ set
+ {
+ if (_SR3 != value)
+ {
+ _SR3 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR3));
+ }
+ }
+ }
+ public void UpdateCDMStatus()
+ {
+ if (AppData.cCmdRsp != null) {
+ CDMStatus = RequestTime.ToString("yyyyMMdd HHmmss")+ " SR1: " + AppData.cCmdRsp.GetSR1Summary(SR1) + " SR2: " + AppData.cCmdRsp.GetSR2Summary(SR2);
+ }
+ }
+ private string? _CDMStatus;
+ public string? CDMStatus
+ {
+ get
+ {
+ return _CDMStatus;
+ }
+ set
+ {
+ if (_CDMStatus != value)
+ {
+ _CDMStatus = value;
+
+ OnPropertyChanged(nameof(CDMStatus));
+ }
+ }
+ }
+
+
+ public DateTime RequestTime = DateTime.Now;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public class DeviceStatus
+ {
+ public int TenantId { get; set; }
+ public string Device { get; set; }
+ public int Status { get; set; }
+ public DateTime DeviceTime { get; set; }
+ public int CDMStatus { get; set; }
+ public int PrinterStatus { get; set; }
+ public int SensorStatus { get; set; }
+ public int OtherError { get; set; }
+ public string Description { get; set; }
+ }
+ public enum DeviceStatusCode {
+ NORMAL=0,
+ ERROR=1
+ }
+ public enum PrinterStatusCode
+ {
+ NORMAL = 0,
+ NEARPAPEROUT = 1,
+ PAPEROUT=2
+ }
+}
diff --git a/.svn/pristine/6a/6ab907146e5ca6cccc512ae6c5bc9b76ba808379.svn-base b/.svn/pristine/6a/6ab907146e5ca6cccc512ae6c5bc9b76ba808379.svn-base
new file mode 100644
index 0000000..a09dc0f
--- /dev/null
+++ b/.svn/pristine/6a/6ab907146e5ca6cccc512ae6c5bc9b76ba808379.svn-base
@@ -0,0 +1,65 @@
+using SafeBagDE70.Model;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Windows.Threading;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for QRCodeWindow.xaml
+ ///
+ public partial class QRCodeWindow : HandyControl.Controls.Window
+ {
+ private DispatcherTimer timer;
+ int countTimer = 0;
+ public string QRCodeContent = null;
+ public QRCodeWindow()
+ {
+ InitializeComponent();
+ this.KeyDown += QRCodeWindow_KeyDown;
+ this.Loaded += QRCodeWindow_Loaded;
+ }
+ private void QRCodeWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ Keyboard.Focus(this);
+ timer = new DispatcherTimer();
+
+ // Set the timer interval to 1 second
+ timer.Interval = TimeSpan.FromMilliseconds(100);
+
+ // Define the event handler that's called each time the timer elapses
+ timer.Tick += Timer_Tick;
+
+ // Start the timer
+ timer.Start();
+ }
+ private void Timer_Tick(object sender, EventArgs e)
+ {
+ countTimer++;
+ if (QRCodeContent!=null && countTimer == 5)
+ {
+ DialogResult = true;
+ this.Close();
+ //finish
+ }
+ }
+
+ private void QRCodeWindow_KeyDown(object sender, KeyEventArgs e)
+ {
+ QRCodeContent += KeyModel.GetCharFromKey(e.Key);
+ countTimer = 0;
+ }
+
+ }
+}
diff --git a/.svn/pristine/6e/6e3e239d6551ab5feb324e43cae04e04aa9e6089.svn-base b/.svn/pristine/6e/6e3e239d6551ab5feb324e43cae04e04aa9e6089.svn-base
new file mode 100644
index 0000000..0eca606
--- /dev/null
+++ b/.svn/pristine/6e/6e3e239d6551ab5feb324e43cae04e04aa9e6089.svn-base
@@ -0,0 +1,162 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using SafeBagDE70.Services;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ private WelcomeUC _welcomeUC;
+ private DepositSMUC _depositUC;
+ private CollectionUC _collectionUC;
+ private InformationUC _informationUC;
+ private ErrorUC _errorUC;
+ private UserControl _currentUC;
+ private UserControl _prevUC;
+ private TimeoutUC _timeoutUC;
+ private MaintainanceUC _maintainanceUC;
+ private object objLock = new object();
+ public MainWindow()
+ {
+ InitializeComponent();
+ Loaded += MainWindow_Loaded;
+ }
+
+ private void MainWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.Init();
+ if (_welcomeUC == null) _welcomeUC = new WelcomeUC();
+ if (_collectionUC == null) _collectionUC = new CollectionUC();
+ if (_informationUC == null) _informationUC = new InformationUC();
+ if (_errorUC == null) _errorUC = new ErrorUC();
+ if (_depositUC == null) _depositUC = new DepositSMUC();
+ if (_timeoutUC == null) _timeoutUC = new TimeoutUC();
+ if (_maintainanceUC == null) _maintainanceUC = new MaintainanceUC();
+
+
+ gridMain.Children.Add(_welcomeUC);
+ gridMain.Children.Add(_depositUC);
+ gridMain.Children.Add(_collectionUC);
+ gridMain.Children.Add(_informationUC);
+ gridMain.Children.Add(_errorUC);
+ gridMain.Children.Add(_timeoutUC);
+ gridMain.Children.Add(_maintainanceUC);
+
+ ShowWelcomeScreen();
+ //ShowDepositScreen();
+ }
+
+ public void HideAll()
+ {
+ lock(objLock)
+ {
+ foreach (var item in gridMain.Children)
+ {
+ if (item != null)
+ (item as UserControl).Visibility = Visibility.Hidden;
+ }
+ _collectionUC.Visibility = Visibility.Hidden;
+ _informationUC.Visibility = Visibility.Hidden;
+ _errorUC.Visibility = Visibility.Hidden;
+ _depositUC.Visibility = Visibility.Hidden;
+ _welcomeUC.Visibility = Visibility.Hidden;
+ _maintainanceUC.Visibility=Visibility.Hidden;
+ SoundManager.StopWarningSound();
+ }
+
+ }
+ public void ShowInformationScreen(string strInfor,bool bContinue=false,bool bPlaySound=true)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _informationUC;
+ HideAll();
+ _informationUC.Visibility = Visibility.Visible;
+ _informationUC.ShowInfor(strInfor, bContinue, bPlaySound);
+ }
+ public void ShowErrorScreen(string strError)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _errorUC;
+ HideAll();
+ _errorUC.Visibility = Visibility.Visible;
+ _errorUC.ShowInfor(strError);
+ }
+ public void ShowWelcomeScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _welcomeUC;
+ HideAll();
+ _welcomeUC.Init();
+ _welcomeUC.Visibility = Visibility.Visible;
+ }
+ public void ShowDepositScreen(bool bInit=true)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _depositUC;
+ HideAll();
+ _depositUC.Visibility = Visibility.Visible;
+ if(bInit)
+ {
+ _depositUC.EndTransaction();
+ _depositUC.InitTransaction();
+ }
+ }
+
+ public void ShowCollectionScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _collectionUC;
+ HideAll();
+ _collectionUC.Init();
+ _collectionUC.Visibility = Visibility.Visible;
+ }
+ public bool IsMaintainanceScreen()
+ {
+ return _currentUC == _maintainanceUC;
+ }
+ public DepositSMUC GetDepositScreen()
+ {
+ return _depositUC;
+ }
+ public void ShowMaintainanceScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _maintainanceUC.Visibility = Visibility.Visible;
+ }
+ public void ShowTimeoutScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _timeoutUC.Visibility = Visibility.Visible;
+ }
+ public void BackScreen()
+ {
+ HideAll();
+ _prevUC.Visibility = Visibility.Visible;
+ _currentUC = _prevUC;
+ }
+ }
+}
diff --git a/.svn/pristine/6e/6ed7e6d0846546bac3fc73f26bdf573ad4a1bf7b.svn-base b/.svn/pristine/6e/6ed7e6d0846546bac3fc73f26bdf573ad4a1bf7b.svn-base
new file mode 100644
index 0000000..3ca00ae
--- /dev/null
+++ b/.svn/pristine/6e/6ed7e6d0846546bac3fc73f26bdf573ad4a1bf7b.svn-base
@@ -0,0 +1,77 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for AdminConfigurationUC.xaml
+ ///
+ public partial class AdminConfigurationUC : UserControl
+ {
+ public AdminConfigurationUC()
+ {
+ InitializeComponent();
+ }
+
+ private void btnResetCounter_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ {
+ CCmdRsp cCmdRsp = AppData.cCmdRsp;
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ lblStatus.Text = "TRẠNG THÁI: KHỞI TẠO BỘ ĐẾM THÀNH CÔNG";
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+
+ }
+ }
+ }
+
+ private void btnOpenEscrow_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ }
+ }
+}
diff --git a/.svn/pristine/6f/6f1ba4dacdbda811e1560c6cf13c400416e7c4da.svn-base b/.svn/pristine/6f/6f1ba4dacdbda811e1560c6cf13c400416e7c4da.svn-base
new file mode 100644
index 0000000..4bd1887
--- /dev/null
+++ b/.svn/pristine/6f/6f1ba4dacdbda811e1560c6cf13c400416e7c4da.svn-base
@@ -0,0 +1,1284 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.StateMachine;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
+using System.Runtime.Intrinsics.Arm;
+using SafeBagDE70.Services;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositSMUC : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+ private string? _currentState;
+ private string? _prevState;
+
+ public DepositSMUC()
+ {
+ InitializeComponent();
+ _currentState = App.StateMachineConfig.States.FirstOrDefault();
+ UpdateStateMessage();
+ }
+ public string GetCurrentState()
+ {
+ return _currentState;
+ }
+ public string GetPrevioustState()
+ {
+ return _prevState;
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ InitTransaction();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ lblName.Content= "Vietinbank " + Environment.MachineName;
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+
+ }
+
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+ AppData.IsInTransaction = true;
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ private void InitTimers()
+ {
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+
+
+ public void InitSessionCount()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ // public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ // public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ // public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+ public int countSensorTimer = 0;
+ //PrinterManager printerManager = new PrinterManager();
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+
+ timer.IsEnabled = false;
+
+
+ //countSensorTimer++;
+ //if(countSensorTimer%5==0)
+ //{
+ // Log.Information("SensorTimer_Tick " + PrinterManager.IsPaperOut());
+ // PrinterManager.UpdateStatus();
+ // if (PrinterManager.IsNearPaperOut())
+ // {
+ // ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỔ SUNG GIẤY ĐỂ TIẾP TỤC", true);
+ // }
+ // else if (PrinterManager.IsPaperOut())
+ // {
+ // ((MainWindow)Application.Current.MainWindow).ShowErrorScreen("HẾT GIẤY TRONG MÁY IN");
+ // }
+ //}
+
+
+ GetSensorValue();
+
+ if (_currentState=="End"||_currentState=="AutoEnd"||_currentState=="Logout")
+ {
+ if(countSensorTimer>=15)
+ TransitionToState("Start");
+ countSensorTimer++;
+ }
+ else
+ {
+ countSensorTimer = 0;
+ }
+ if (AppData.IsInTransaction)
+ {
+ if (AppData.WDTCount == 30)
+ {
+ TransitionToState("Timeout");
+ //((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen();
+ }
+ else if (AppData.WDTCount == 60)
+ {
+ TransitionToState("AutoEnd");
+ //Nhận tiền và Kết thúc
+ //DoStoreStart();
+ //EndSession();
+
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ //AppData.IsInTransaction = false;
+ //AppData.WDTCount = 0;
+ }
+ AppData.WDTCount++;
+ }
+ else
+ {
+ AppData.WDTCount = 0;
+ }
+ timer.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Sensor_Timer");
+ }
+
+
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ TransitionToState("Maintainance");
+ }
+ else
+ {
+ if(_currentState== "Maintainance")
+ TransitionToState("Start");
+ //if (((MainWindow)Application.Current.MainWindow).IsMaintainanceScreen())
+ // ((MainWindow)Application.Current.MainWindow).BackScreen();
+ }
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"GetSensorValue");
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet()
+ {
+ try
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ var countSession = new CountSession();
+ countSession.IsStored = false;
+ sessions.Add(countSession);
+ while (true)
+ {
+ AppData.WDTCount = 0;
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ AppData.WDTCount = 0;
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: countSession.TempNotes[0]++;break;
+ case 0x02:
+ //TempNote[1] ++;
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}");
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ //case 0x00: TempQuantity[0]++; break;
+ //case 0x01: TempQuantity[1]++; break;
+ //case 0x02: TempQuantity[2]++; break;
+ //case 0x03: TempQuantity[3]++; break;
+ //case 0x04: TempQuantity[4]++; break;
+ //case 0x05: TempQuantity[5]++; break;
+ //case 0x06: TempQuantity[6]++; break;
+ //case 0x07: TempQuantity[7]++; break;
+ //case 0x08: TempQuantity[8]++; break;
+ //case 0x09: TempQuantity[9]++; break;
+
+ case 0x00: countSession.QuantityDenomi[0]++; break;
+ case 0x01: countSession.QuantityDenomi[1]++; break;
+ case 0x02: countSession.QuantityDenomi[2]++; break;
+ case 0x03: countSession.QuantityDenomi[3]++; break;
+ case 0x04: countSession.QuantityDenomi[4]++; break;
+ case 0x05: countSession.QuantityDenomi[5]++; break;
+ case 0x06: countSession.QuantityDenomi[6]++; break;
+ case 0x07: countSession.QuantityDenomi[7]++; break;
+ case 0x08: countSession.QuantityDenomi[8]++; break;
+ case 0x09: countSession.QuantityDenomi[9]++; break;
+
+ }
+ break;
+ //case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ //case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ //case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ case 0x03: countSession.TempNotes[2]++; break;
+ case 0x0b: countSession.TempNotes[3]++; break;
+ case 0x0c: countSession.TempNotes[4]++; break;
+ }
+ UpdateListViewCountItems();
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0)
+ {
+ sessions.Remove(countSession);
+ }
+ }catch(Exception ex)
+ {
+ Log.Fatal(ex, "AutoSerialGet");
+ }
+
+ //Log.Information(JsonConvert.SerializeObject(sessions));
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private bool CountStart()
+ {
+ bool bSuccess = true;
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+ Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ Thread thread = new Thread(new ThreadStart(() =>
+ {
+ AutoSerialGet();
+
+ }));
+ thread.Start();
+ //InitSessionCount();
+ //UpdateListViewCountItems();
+
+
+ //if (sessions == null || sessions.Count == 0)
+ //{
+ // double tempSum = 0;
+ // for (int i = 0; i < 10; i++)
+ // {
+ // lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ // tempSum += lvCountItems[i].getValue();
+ // }
+
+ // lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ // lvCountItems[10].Value = tempSum.ToString();
+
+ //}
+ //else
+ //{
+ // InitSessionCount();
+ // double sum = 0;
+
+ // for (int i = 0; i < 10; i++)
+ // {
+ // int a = 0;
+ // for (int j = 0; j < sessions.Count; j++)
+ // {
+
+ // a += sessions[j].QuantityDenomi[9 - i];
+
+ // }
+
+ // a += TempQuantity[9 - i];
+
+ // lvCountItems[i].Quantity = a.ToString();
+ // sum += lvCountItems[i].getValue();
+
+ // }
+ // //Update amount of money
+ // lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ // lvCountItems[10].Value = sum.ToString();
+
+ //}
+ Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex,currentMethod);
+ }
+ return bSuccess;
+ }
+
+ private void UpdateListViewCountItems()
+ {
+ Dispatcher.Invoke(DispatcherPriority.Normal, () =>
+ {
+ double sum = 0;
+ if (sessions != null && sessions.Count > 0)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ int quantity = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ quantity += sessions[j].QuantityDenomi[9 - i];
+
+ }
+ //a += TempQuantity[9 - i];
+ lvCountItems[i].Quantity = quantity.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+ }
+ else
+ {
+ for (int i = 0; i < 11; i++)
+ {
+ lvCountItems[i].Quantity = "0";
+ lvCountItems[i].Value = "0";
+ }
+ }
+ });
+
+ }
+
+ private bool DoCheck()
+ {
+ bool bSuccess = true;
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ sessions.RemoveAll(item=>!item.IsStored);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ UpdateListViewCountItems();
+
+ //double sumStored;
+
+ //TempNote[1] = 0;
+
+ //if (sessions != null)
+ //{
+ // sumStored = 0;
+
+ // for (int i = 0; i < 10; i++)
+ // {
+ // int a = 0;
+ // for (int j = 0; j < sessions.Count; j++)
+ // {
+
+ // a += sessions[j].QuantityDenomi[9 - i];
+ // //quantityStored += lvCountItems[i].getQuantity();
+ // }
+ // lvCountItems[i].Quantity = a.ToString();
+ // sumStored += lvCountItems[i].getValue();
+ // }
+ // lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ // lvCountItems[10].Value = sumStored.ToString();
+ //}
+ //else
+ //{
+ // InitSessionCount();
+ //}
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+ private bool WaitUntilEnscrowEmpty(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while(true)
+ {
+ state = GetCDMState();
+ if (state.IsNotesInEscrow == 0)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool DoStoreStart()
+ {
+ bool bSuccess = true;
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ //sessions.Add(new CountSession());
+
+ // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ foreach(var item in sessions)
+ {
+ item.IsStored = true;
+ }
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored "+GetShortInforFromCountItems());
+ //Debug.WriteLine(quantityStored);
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ bSuccess=WaitUntilEnscrowEmpty(10);
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoStart()
+ {
+ bool bSuccess = true;
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoEnd()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else
+ {
+ bSuccess = true;
+ AppData.WDTCount = 0;
+ EndSession();
+ }
+ return bSuccess;
+ }
+ private bool DoLogout()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ InitSessionCount();
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else //if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess = true;
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ EndSession();
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ if (double.Parse(totalValue) > 0)
+ {
+ var data2Send = new CountingData2Send
+ {
+ TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
+ Sessions = sessions,
+ MachineId = Environment.MachineName,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ //RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ //UnfitNotes = Notes[2],
+ //CounterfeitNotes = Notes[3],
+ // SuspendNotes = Notes[4]
+
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if (double.Parse(totalValue) > 0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify, false, false);
+ AppData.WDTCount = 45;
+ }
+ //SendData2Server
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, currentMethod);
+ }
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Save2DB Exception");
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Update2DB Exception");
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+ public class CDMSTATE
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ }
+ private CDMSTATE GetCDMState()
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv=cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ var cdmState = new CDMSTATE();
+
+ cdmState.IsCassetteFull = data[17] & 0x08;
+ cdmState.IsNotesInEscrow = data[4] & 0x01;
+ cdmState.IsRejectPocketFull = data[3] & 0x40;
+ cdmState.IsNotesInRejectPocket = data[3] & 0x10;
+ return cdmState;
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal(ex,"InitSession");
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ Log.Information("PrintReceipt");
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ private void DisableButtons()
+ {
+ btnStart.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ btnLogout.IsEnabled=false;
+ }
+ private void UpdateStateMessage()
+ {
+ // StateMessage.Text = $"Current State: {_processStateMachine.CurrentState}";
+
+ // Enable or disable buttons based on the current state and available transitions
+ btnStart.IsEnabled = CanTransitionTo("Init", out _);
+ btnCountStart.IsEnabled = CanTransitionTo("Count", out _);
+ btnCheck.IsEnabled = CanTransitionTo("Check", out _);
+ btnStoreStart.IsEnabled =CanTransitionTo("Store", out _);
+ }
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ SoundManager.StartButtonPressSound();
+ // Console.Beep(800, 200);
+ AppData.WDTCount = 0;
+ if (btn==btnStart)
+ {
+ TransitionToState("Init");
+ //Log.Information("Deposit starting");
+ //Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ //Log.Information("1. Start starting");
+ //DoStart();
+ //Log.Information("1. Start completed");
+ //AppData.WDTCount = 0;
+ }
+ else if(btn==btnCountStart)
+ {
+ TransitionToState("Count");
+ //Log.Information("2. Count starting");
+ //CountStart();
+ //Log.Information("2. Count completed");
+ //AppData.WDTCount = 0;
+ }
+ else if(btn==btnCheck)
+ {
+ TransitionToState("Check");
+ //Log.Information($"3. Check starting");
+ //DoCheck();
+ //Log.Information($"3. Check completed");
+ //AppData.WDTCount = 0;
+ }
+ else if (btn == btnStoreStart)
+ {
+ TransitionToState("Store");
+
+ //Log.Information("4. Store starting");
+ //DoStoreStart();
+ //Log.Information("4. Store completed");
+ //AppData.WDTCount = 0;
+ }
+ else if (btn == btnEnd)
+ {
+ TransitionToState("End");
+ //Log.Information("5. End starting");
+ //DoEnd();
+ //Log.Information("5. End Completed");
+ }
+ else if (btn == btnLogout)
+ {
+ TransitionToState("Logout");
+ //Log.Information("6. Exit starting");
+ //DoLogout();
+ //Log.Information("6. Exit Completed");
+ }
+ }
+
+
+
+ public string CurrentState => _currentState;
+
+ public bool CanTransitionTo(string newState, out Transition transition)
+ {
+ transition = App.StateMachineConfig.Transitions
+ .FirstOrDefault(t => t.From.Contains(_currentState) && t.To.Contains(newState));
+
+ return transition != null;
+ }
+
+ public void TransitionToState(string newState)
+ {
+ Log.Information("State changing to: " + newState);
+ if (CanTransitionTo(newState, out Transition transition))
+ {
+ if (ExecuteActions(transition))
+ {
+ // Transition to the new state if the required condition is met
+ _prevState = _currentState;
+ _currentState = newState;
+ Log.Information("State changed to: " + newState);
+ }
+ else
+ {
+ Log.Error($"Failed to meet action requirements. Staying in {_currentState}.");
+ }
+ }
+ else
+ {
+ Log.Error($"Cannot transition from {_currentState} to {newState}");
+ }
+ UpdateStateMessage();
+ }
+
+ private bool ExecuteActions(Transition transition)
+ {
+ bool allRequiredActionsSucceeded = true;
+ bool atLeastOneActionSucceeded = false;
+
+ foreach (var action in transition.Actions)
+ {
+ bool success = ExecuteAction(action.Name);
+
+ if (success)
+ {
+ atLeastOneActionSucceeded = true;
+ }
+
+ if (action.IsRequired && !success)
+ {
+ allRequiredActionsSucceeded = false;
+ }
+ }
+
+ // Determine if the transition should happen based on the condition
+ if (transition.RequireAtLeastOneActionSuccess)
+ {
+ return atLeastOneActionSucceeded;
+ }
+ else
+ {
+ return allRequiredActionsSucceeded;
+ }
+ }
+
+ private bool ExecuteAction(string actionName)
+ {
+ // Simulate action execution based on the action name
+ //Console.WriteLine($"Executing action: {App.StateMachineConfig.Actions[actionName]}");
+ Log.Information("Action: "+actionName);
+ bool bSuccess = true;
+ switch (actionName)
+ {
+ case "DoInit":
+ bSuccess=DoStart();
+ break;
+ case "DoCount":
+ bSuccess = CountStart();
+ break;
+ case "DoCheck":
+ bSuccess = DoCheck();
+ break;
+ case "DoStore":
+ bSuccess = DoStoreStart();
+ break;
+ case "DoLogout":
+ bSuccess = DoLogout();
+ break;
+ case "ShowTimeoutScreen":
+ ((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen();
+ break;
+ case "ShowWelcomeScreen":
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ break;
+ case "ShowMaintainanceScreen":
+ ((MainWindow)Application.Current.MainWindow).ShowMaintainanceScreen();
+ break;
+ case "BackScreen":
+ ((MainWindow)Application.Current.MainWindow).BackScreen();
+ break;
+
+ case "DoEnd":
+ bSuccess = DoEnd();
+ break;
+
+ }
+
+ // For the sake of this example, all actions succeed
+ return bSuccess;
+ }
+ }
+}
+
diff --git a/.svn/pristine/71/71255a3486cff521eb7f0d38075fb86c0835fec9.svn-base b/.svn/pristine/71/71255a3486cff521eb7f0d38075fb86c0835fec9.svn-base
new file mode 100644
index 0000000..92e1216
--- /dev/null
+++ b/.svn/pristine/71/71255a3486cff521eb7f0d38075fb86c0835fec9.svn-base
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/73/737ae15160f04efca3e2d838c77c26d2f29d0a27.svn-base b/.svn/pristine/73/737ae15160f04efca3e2d838c77c26d2f29d0a27.svn-base
new file mode 100644
index 0000000..83eb037
--- /dev/null
+++ b/.svn/pristine/73/737ae15160f04efca3e2d838c77c26d2f29d0a27.svn-base
@@ -0,0 +1,51 @@
+using DE70_CMDv2;
+using SafeBagDE70.Model;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ }
+ public static void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public static void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ }
+}
diff --git a/.svn/pristine/73/73f03dc42e6b54e168620b30c736c231a8a5dea9.svn-base b/.svn/pristine/73/73f03dc42e6b54e168620b30c736c231a8a5dea9.svn-base
new file mode 100644
index 0000000..d6ae4a4
Binary files /dev/null and b/.svn/pristine/73/73f03dc42e6b54e168620b30c736c231a8a5dea9.svn-base differ
diff --git a/.svn/pristine/75/75a45496f660b406e6738df28c2e6027a2788464.svn-base b/.svn/pristine/75/75a45496f660b406e6738df28c2e6027a2788464.svn-base
new file mode 100644
index 0000000..e7c82e8
--- /dev/null
+++ b/.svn/pristine/75/75a45496f660b406e6738df28c2e6027a2788464.svn-base
@@ -0,0 +1,210 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeWindow : HandyControl.Controls.Window
+ {
+ public string? QRCodeContent = null;
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeWindow()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ }
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+ string pin = PinCodeBox.Password;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Password.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ DialogResult = true;
+ this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Help clicked.");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ {
+ UseShellExecute = true
+ };
+ Process.Start(onScreenKeyboardProcess);
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ QRCodeContent = HexStringToString(rawDataHex);
+ this.Dispatcher.Invoke(() =>
+ {
+
+
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (QRCodeContent != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == QRCodeContent).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ DialogResult = true;
+ this.Close();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/78/78da6ced5cd4ceef6cfee414de2eac4da8a8f688.svn-base b/.svn/pristine/78/78da6ced5cd4ceef6cfee414de2eac4da8a8f688.svn-base
new file mode 100644
index 0000000..0836a87
--- /dev/null
+++ b/.svn/pristine/78/78da6ced5cd4ceef6cfee414de2eac4da8a8f688.svn-base
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/7c/7ceb2f6be0031a78f4843553f03a6f9656dd4608.svn-base b/.svn/pristine/7c/7ceb2f6be0031a78f4843553f03a6f9656dd4608.svn-base
new file mode 100644
index 0000000..96a01e6
--- /dev/null
+++ b/.svn/pristine/7c/7ceb2f6be0031a78f4843553f03a6f9656dd4608.svn-base
@@ -0,0 +1,21 @@
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/7d/7d031f4d2a5674c048d43d754d5021212ed94f93.svn-base b/.svn/pristine/7d/7d031f4d2a5674c048d43d754d5021212ed94f93.svn-base
new file mode 100644
index 0000000..9338698
--- /dev/null
+++ b/.svn/pristine/7d/7d031f4d2a5674c048d43d754d5021212ed94f93.svn-base
@@ -0,0 +1,71 @@
+{
+ "format": 1,
+ "restore": {
+ "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj": {}
+ },
+ "projects": {
+ "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj": {
+ "version": "1.0.0",
+ "restore": {
+ "projectUniqueName": "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "projectName": "VirtualKeyboard",
+ "projectPath": "D:\\SRC\\VirtualKeyboard\\VirtualKeyboard.csproj",
+ "packagesPath": "C:\\Users\\Admin\\.nuget\\packages\\",
+ "outputPath": "D:\\SRC\\VirtualKeyboard\\obj\\",
+ "projectStyle": "PackageReference",
+ "configFilePaths": [
+ "C:\\Users\\Admin\\AppData\\Roaming\\NuGet\\NuGet.Config",
+ "C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
+ ],
+ "originalTargetFrameworks": [
+ "net8.0-windows"
+ ],
+ "sources": {
+ "C:\\Program Files (x86)\\Microsoft SDKs\\NuGetPackages\\": {},
+ "https://api.nuget.org/v3/index.json": {}
+ },
+ "frameworks": {
+ "net8.0-windows7.0": {
+ "targetAlias": "net8.0-windows",
+ "projectReferences": {}
+ }
+ },
+ "warningProperties": {
+ "warnAsError": [
+ "NU1605"
+ ]
+ },
+ "restoreAuditProperties": {
+ "enableAudit": "true",
+ "auditLevel": "low",
+ "auditMode": "direct"
+ }
+ },
+ "frameworks": {
+ "net8.0-windows7.0": {
+ "targetAlias": "net8.0-windows",
+ "imports": [
+ "net461",
+ "net462",
+ "net47",
+ "net471",
+ "net472",
+ "net48",
+ "net481"
+ ],
+ "assetTargetFallback": true,
+ "warn": true,
+ "frameworkReferences": {
+ "Microsoft.NETCore.App": {
+ "privateAssets": "all"
+ },
+ "Microsoft.WindowsDesktop.App.WPF": {
+ "privateAssets": "none"
+ }
+ },
+ "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\8.0.303/PortableRuntimeIdentifierGraph.json"
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/7e/7e14f07406c71702c8aa0f96513b9765bb03940e.svn-base b/.svn/pristine/7e/7e14f07406c71702c8aa0f96513b9765bb03940e.svn-base
new file mode 100644
index 0000000..18bb5df
--- /dev/null
+++ b/.svn/pristine/7e/7e14f07406c71702c8aa0f96513b9765bb03940e.svn-base
@@ -0,0 +1,210 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/7f/7f6ec43ec1e38da74416d5d21faf02f5ac19c51c.svn-base b/.svn/pristine/7f/7f6ec43ec1e38da74416d5d21faf02f5ac19c51c.svn-base
new file mode 100644
index 0000000..84adeb5
--- /dev/null
+++ b/.svn/pristine/7f/7f6ec43ec1e38da74416d5d21faf02f5ac19c51c.svn-base
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class ErrorUC : UserControl
+ {
+ public ErrorUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor)
+ {
+ lblError.Text = strInfor;
+ }
+
+ private void btnRetry_Click(object sender, RoutedEventArgs e)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ }
+ }
+}
diff --git a/.svn/pristine/80/80274024b11f630d0cdbaf026b65c6930b58d38a.svn-base b/.svn/pristine/80/80274024b11f630d0cdbaf026b65c6930b58d38a.svn-base
new file mode 100644
index 0000000..a9fdb02
--- /dev/null
+++ b/.svn/pristine/80/80274024b11f630d0cdbaf026b65c6930b58d38a.svn-base
@@ -0,0 +1,54 @@
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\ResourceDictionaries\DefaultStyles.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\DefaultKeyboardHost.g.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\AlphabetView.g.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\KeyboardValueView.g.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\SpecialCharactersView.g.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\VirtualKeyboardView.g.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\GeneratedInternalTypeHelper.g.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard_MarkupCompile.cache
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard_MarkupCompile.lref
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\bin\Debug\net8.0-windows\VirtualKeyboard.deps.json
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\bin\Debug\net8.0-windows\VirtualKeyboard.dll
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\bin\Debug\net8.0-windows\VirtualKeyboard.pdb
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\DefaultKeyboardHost.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\ResourceDictionaries\KeyboardCore.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\AlphabetView.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\KeyboardValueView.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\SpecialCharactersView.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\Views\VirtualKeyboardView.baml
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.g.resources
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.GeneratedMSBuildEditorConfig.editorconfig
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.AssemblyInfoInputs.cache
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.AssemblyInfo.cs
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.csproj.CoreCompileInputs.cache
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.dll
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\refint\VirtualKeyboard.dll
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.pdb
+C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\obj\Debug\net8.0-windows\ref\VirtualKeyboard.dll
+D:\SRC\VirtualKeyboard\bin\Debug\net8.0-windows\VirtualKeyboard.deps.json
+D:\SRC\VirtualKeyboard\bin\Debug\net8.0-windows\VirtualKeyboard.dll
+D:\SRC\VirtualKeyboard\bin\Debug\net8.0-windows\VirtualKeyboard.pdb
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\ResourceDictionaries\DefaultStyles.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\DefaultKeyboardHost.g.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\AlphabetView.g.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\KeyboardValueView.g.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\SpecialCharactersView.g.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\VirtualKeyboardView.g.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\GeneratedInternalTypeHelper.g.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard_MarkupCompile.cache
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard_MarkupCompile.lref
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\DefaultKeyboardHost.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\ResourceDictionaries\KeyboardCore.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\AlphabetView.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\KeyboardValueView.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\SpecialCharactersView.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\Views\VirtualKeyboardView.baml
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.g.resources
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.GeneratedMSBuildEditorConfig.editorconfig
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.AssemblyInfoInputs.cache
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.AssemblyInfo.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.csproj.CoreCompileInputs.cache
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.dll
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\refint\VirtualKeyboard.dll
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\VirtualKeyboard.pdb
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\ref\VirtualKeyboard.dll
diff --git a/.svn/pristine/80/80b456239e598a60f6a7fd69ea99447a9d4e0269.svn-base b/.svn/pristine/80/80b456239e598a60f6a7fd69ea99447a9d4e0269.svn-base
new file mode 100644
index 0000000..9ad34e8
--- /dev/null
+++ b/.svn/pristine/80/80b456239e598a60f6a7fd69ea99447a9d4e0269.svn-base
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace VirtualKeyboard.Wpf.Types
+{
+ enum KeyboardType
+ {
+ Alphabet,
+ Special
+ }
+}
diff --git a/.svn/pristine/81/8162605084f50faf2b443acd0713abc1a956cd76.svn-base b/.svn/pristine/81/8162605084f50faf2b443acd0713abc1a956cd76.svn-base
new file mode 100644
index 0000000..d20c9a4
--- /dev/null
+++ b/.svn/pristine/81/8162605084f50faf2b443acd0713abc1a956cd76.svn-base
@@ -0,0 +1,235 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/82/8211b62045ccdf5714263a0c646f586718e9ba7e.svn-base b/.svn/pristine/82/8211b62045ccdf5714263a0c646f586718e9ba7e.svn-base
new file mode 100644
index 0000000..27c4b0e
--- /dev/null
+++ b/.svn/pristine/82/8211b62045ccdf5714263a0c646f586718e9ba7e.svn-base
@@ -0,0 +1,47 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class TimeoutUC : UserControl
+ {
+ public TimeoutUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor)
+ {
+ lblInfor.Text = strInfor;
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ AppData.WDTCount = 0;
+ var state= ((MainWindow)Application.Current.MainWindow).GetDepositScreen().GetPrevioustState();
+ ((MainWindow)Application.Current.MainWindow).GetDepositScreen().TransitionToState(state);
+ //((MainWindow)Application.Current.MainWindow).BackScreen();
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ }
+ }
+}
diff --git a/.svn/pristine/83/832e0d765ccb5611b20d4b14ed52d1c18b040f95.svn-base b/.svn/pristine/83/832e0d765ccb5611b20d4b14ed52d1c18b040f95.svn-base
new file mode 100644
index 0000000..c40d4d4
--- /dev/null
+++ b/.svn/pristine/83/832e0d765ccb5611b20d4b14ed52d1c18b040f95.svn-base
@@ -0,0 +1,287 @@
+using DE70_CMDv2;
+using Newtonsoft.Json.Linq;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ CDMSTATE=new CDMSTATE();
+ }
+ 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()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+ public static CDMSTATE? GetCDMState()
+ {
+ if(cCmdRsp!=null)
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv = cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ if(AppData.CDMSTATE!=null)
+ {
+ AppData.CDMSTATE.IsCassetteFull = data[17] & 0x08;
+ AppData.CDMSTATE.IsNotesInEscrow = data[4] & 0x01;
+ AppData.CDMSTATE.IsRejectPocketFull = data[3] & 0x40;
+ AppData.CDMSTATE.IsNotesInRejectPocket = data[3] & 0x10;
+ AppData.CDMSTATE.IsNotesInHopper = data[3] & 0x01;
+ AppData.CDMSTATE.RequestTime = DateTime.Now;
+ AppData.CDMSTATE.SR1 = data[0];
+ AppData.CDMSTATE.SR2 = data[1];
+ AppData.CDMSTATE.SR3 = data[2];
+ }
+
+ }
+ return AppData.CDMSTATE;
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+ public class CountSession
+ {
+ public CountSession()
+ {
+ for (int i = 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ }
+ public class NotesInSession : INotifyPropertyChanged
+ {
+
+ private int _GenuineNotes;
+ public int GenuineNotes
+ {
+ get
+ {
+ return _GenuineNotes;
+ }
+ set
+ {
+ if (_GenuineNotes != value)
+ {
+ _GenuineNotes = value;
+ OnPropertyChanged(nameof(GenuineNotes));
+ }
+ }
+ }
+ private int _RejectNotes;
+ public int RejectNotes
+ {
+ get
+ {
+ return _RejectNotes;
+ }
+ set
+ {
+ if (_RejectNotes != value)
+ {
+ _RejectNotes = value;
+ OnPropertyChanged(nameof(RejectNotes));
+ }
+ }
+ }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public class CDMSTATE : INotifyPropertyChanged
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ public int IsNotesInHopper = 0;
+ private byte _SR1;
+ public byte SR1 {
+ get
+ {
+ return _SR1;
+ }
+ set
+ {
+ if (_SR1 != value)
+ {
+ _SR1 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR1));
+ }
+ }
+ }
+ private byte _SR2;
+ public byte SR2
+ {
+ get
+ {
+ return _SR2;
+ }
+ set
+ {
+ if (_SR2 != value)
+ {
+ _SR2 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR2));
+ }
+ }
+ }
+ private byte _SR3;
+ public byte SR3
+ {
+ get
+ {
+ return _SR3;
+ }
+ set
+ {
+ if (_SR3 != value)
+ {
+ _SR3 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR3));
+ }
+ }
+ }
+ private void UpdateCDMStatus()
+ {
+ if (AppData.cCmdRsp != null) {
+ CDMStatus = RequestTime.ToString("yyyyMMdd HHmmss")+ " SR1: " + AppData.cCmdRsp.GetSR1Summary(SR1) + " SR2: " + AppData.cCmdRsp.GetSR2Summary(SR2);
+ }
+ }
+ private string? _CDMStatus;
+ public string? CDMStatus
+ {
+ get
+ {
+ return _CDMStatus;
+ }
+ set
+ {
+ if (_CDMStatus != value)
+ {
+ _CDMStatus = value;
+
+ OnPropertyChanged(nameof(CDMStatus));
+ }
+ }
+ }
+
+
+ public DateTime RequestTime = DateTime.Now;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+}
diff --git a/.svn/pristine/83/835b89e2520659dca9d81724bb60e4a81370c9bb.svn-base b/.svn/pristine/83/835b89e2520659dca9d81724bb60e4a81370c9bb.svn-base
new file mode 100644
index 0000000..e501ea7
--- /dev/null
+++ b/.svn/pristine/83/835b89e2520659dca9d81724bb60e4a81370c9bb.svn-base
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/84/841282989c19b61706d1e7e4cc23f8ff02ea0d07.svn-base b/.svn/pristine/84/841282989c19b61706d1e7e4cc23f8ff02ea0d07.svn-base
new file mode 100644
index 0000000..c319ffa
--- /dev/null
+++ b/.svn/pristine/84/841282989c19b61706d1e7e4cc23f8ff02ea0d07.svn-base
@@ -0,0 +1,59 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/84/8417571af310d9b21c05487b427ce03de1362133.svn-base b/.svn/pristine/84/8417571af310d9b21c05487b427ce03de1362133.svn-base
new file mode 100644
index 0000000..5226bfb
Binary files /dev/null and b/.svn/pristine/84/8417571af310d9b21c05487b427ce03de1362133.svn-base differ
diff --git a/.svn/pristine/84/8468a607ce95c019c6decef762dda54b2d5f1add.svn-base b/.svn/pristine/84/8468a607ce95c019c6decef762dda54b2d5f1add.svn-base
new file mode 100644
index 0000000..c53d6d8
--- /dev/null
+++ b/.svn/pristine/84/8468a607ce95c019c6decef762dda54b2d5f1add.svn-base
@@ -0,0 +1,357 @@
+using DE70_CMDv2;
+using Newtonsoft.Json.Linq;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static DeviceStatus? DeviceStatus = null;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ CDMSTATE=new CDMSTATE();
+ DeviceStatus = new DeviceStatus
+ {
+ Device = Environment.MachineName,
+ TenantId = 0,
+ Status = 0,
+ CDMStatus = 0,
+ PrinterStatus = 0,
+ SensorStatus = 0,
+ Notes = 0,
+ OtherError = 0,
+ };
+ }
+ 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()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+ public static CDMSTATE? GetCDMState()
+ {
+ try
+ {
+ if (cCmdRsp != null)
+ {
+ cCmdRsp.SendDeSense();
+ string strSend = cCmdRsp.GetSendDat(false);
+ string strRecv = cCmdRsp.GetRecvDat();
+ Log.Information($"[SEND] {strSend}");
+ Log.Information($"[RECV] {strRecv}");
+ var data = cCmdRsp.recv_dat.dat;
+ if (AppData.CDMSTATE != null)
+ {
+ AppData.CDMSTATE.IsCassetteFull = data[17] & 0x08;
+ AppData.CDMSTATE.IsNotesInEscrow = data[4] & 0x01;
+ AppData.CDMSTATE.IsRejectPocketFull = data[3] & 0x40;
+ AppData.CDMSTATE.IsNotesInRejectPocket = data[3] & 0x10;
+ AppData.CDMSTATE.IsNotesInHopper = data[3] & 0x01;
+ AppData.CDMSTATE.RequestTime = DateTime.Now;
+ AppData.CDMSTATE.UpdateCDMStatus(cCmdRsp.recv_dat);
+
+ }
+
+ }
+ return AppData.CDMSTATE;
+ }
+ catch (Exception ex) {
+ Log.Fatal(ex, "GetCDMState");
+ return null;
+ }
+
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+ public class CountSession
+ {
+ public CountSession()
+ {
+ for (int i = 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ public int CountingState { get; set; }//0-Normal End, 1-Timeout End
+ }
+
+ public class NotesInSession : INotifyPropertyChanged
+ {
+
+ private int _GenuineNotes;
+ public int GenuineNotes
+ {
+ get
+ {
+ return _GenuineNotes;
+ }
+ set
+ {
+ if (_GenuineNotes != value)
+ {
+ _GenuineNotes = value;
+ OnPropertyChanged(nameof(GenuineNotes));
+ }
+ }
+ }
+ private int _RejectNotes;
+ public int RejectNotes
+ {
+ get
+ {
+ return _RejectNotes;
+ }
+ set
+ {
+ if (_RejectNotes != value)
+ {
+ _RejectNotes = value;
+ OnPropertyChanged(nameof(RejectNotes));
+ }
+ }
+ }
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public class CDMSTATE : INotifyPropertyChanged
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ public int IsNotesInHopper = 0;
+ public RecvData? RecvDat = null;
+ public byte GetSR1()
+ {
+ if (RecvDat != null)
+ return RecvDat.dat[0];
+ return 0;
+ }
+ public byte GetSR2()
+ {
+ if (RecvDat != null)
+ return RecvDat.dat[1];
+ return 0;
+ }
+ public byte GetSR3()
+ {
+ if (RecvDat != null)
+ return RecvDat.dat[2];
+ return 0;
+ }
+ public string GetSRStatus()
+ {
+ if (RecvDat != null)
+ return "SR1/2/3: " + AppData.cCmdRsp.GetSR1Summary(RecvDat.dat[0]) + ", " + AppData.cCmdRsp.GetSR2Summary(RecvDat.dat[1]) + ", " + AppData.cCmdRsp.GetSR3Summary(RecvDat.dat[2]);
+ else
+ return "";
+ }
+ public string GetDtatus()
+ {
+ string strStatus = "";
+ if (RecvDat != null)
+ {
+ if(RecvDat.leng>8)
+ {
+ var dat=RecvDat.dat;
+ strStatus += "D1: "+AppData.cCmdRsp.GetD1Summary(dat[3]);
+ strStatus += "\r\nD2: "+AppData.cCmdRsp.GetD2Summary(dat[4]);
+ strStatus += "\r\nD3: " + AppData.cCmdRsp.GetD3Summary(dat[5]);
+ strStatus += "\r\nD4: " + AppData.cCmdRsp.GetD4Summary(dat[6]);
+ strStatus += "\r\nD5: " + AppData.cCmdRsp.GetD5Summary(dat[7]);
+ strStatus += "\r\nD6: " + AppData.cCmdRsp.GetD6Summary(dat[8]);
+ }
+ }
+ return strStatus;
+ }
+ public string GetSStatus()
+ {
+ string strStatus = "";
+ if (RecvDat != null)
+ {
+ if (RecvDat.leng > 18)
+ {
+ var dat = RecvDat.dat;
+ strStatus += "S1: "+ AppData.cCmdRsp.GetD1Summary(dat[17]);
+ strStatus += "\r\nS2: " + AppData.cCmdRsp.GetD2Summary(dat[18]);
+ }
+ }
+ return strStatus;
+ }
+ public string GetFullStatus()
+ {
+ string strStatus = "";
+ strStatus = GetSRStatus();
+ strStatus += "\r\n"+GetDtatus();
+ strStatus += "\r\n"+GetSStatus();
+ return strStatus;
+ }
+ public void UpdateCDMStatus(RecvData recv_data)
+ {
+ RecvDat=recv_data;
+ if (AppData.cCmdRsp != null) {
+ CDMStatus = RequestTime.ToString("yyyy/MM/dd HH:mm:ss ") + GetSRStatus();
+ if (recv_data.leng > 18)
+ {
+
+ }
+ }
+ }
+ private string? _CDMStatus;
+ public string? CDMStatus
+ {
+ get
+ {
+ return _CDMStatus;
+ }
+ set
+ {
+ if (_CDMStatus != value)
+ {
+ _CDMStatus = value;
+
+ OnPropertyChanged(nameof(CDMStatus));
+ }
+ }
+ }
+
+
+ public DateTime RequestTime = DateTime.Now;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+ public class DeviceStatus
+ {
+ public int TenantId { get; set; }
+ public string Device { get; set; }
+ public int Status { get; set; }
+ public DateTime DeviceTime { get; set; }
+ public int CDMStatus { get; set; }
+ public int PrinterStatus { get; set; }
+ public int SensorStatus { get; set; }
+ public int OtherError { get; set; }
+ public int? Notes { get; set; }
+ public string Description { get; set; }
+ }
+ public enum DeviceStatusCode {
+ NORMAL=0,
+ ERROR=1
+ }
+ public enum PrinterStatusCode
+ {
+ NORMAL = 0,
+ NEARPAPEROUT = 1,
+ PAPEROUT=2
+ }
+ public enum SensorStatusCode
+ {
+ NORMAL = 0,
+ ERROR = 1
+ }
+}
diff --git a/.svn/pristine/84/84e6b3210c9c6885af9238529b8a45373b9a66c7.svn-base b/.svn/pristine/84/84e6b3210c9c6885af9238529b8a45373b9a66c7.svn-base
new file mode 100644
index 0000000..c3ed2aa
--- /dev/null
+++ b/.svn/pristine/84/84e6b3210c9c6885af9238529b8a45373b9a66c7.svn-base
@@ -0,0 +1,85 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/85/8509dc7dad84ed248634be5108571e782945bd81.svn-base b/.svn/pristine/85/8509dc7dad84ed248634be5108571e782945bd81.svn-base
new file mode 100644
index 0000000..160c5a7
--- /dev/null
+++ b/.svn/pristine/85/8509dc7dad84ed248634be5108571e782945bd81.svn-base
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/85/85bc586a6168b58b448dad437cf5ac600038dc34.svn-base b/.svn/pristine/85/85bc586a6168b58b448dad437cf5ac600038dc34.svn-base
new file mode 100644
index 0000000..8234b8f
--- /dev/null
+++ b/.svn/pristine/85/85bc586a6168b58b448dad437cf5ac600038dc34.svn-base
@@ -0,0 +1,23 @@
+{
+ "runtimeTarget": {
+ "name": ".NETCoreApp,Version=v8.0",
+ "signature": ""
+ },
+ "compilationOptions": {},
+ "targets": {
+ ".NETCoreApp,Version=v8.0": {
+ "VirtualKeyboard/1.0.0": {
+ "runtime": {
+ "VirtualKeyboard.dll": {}
+ }
+ }
+ }
+ },
+ "libraries": {
+ "VirtualKeyboard/1.0.0": {
+ "type": "project",
+ "serviceable": false,
+ "sha512": ""
+ }
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/86/860d19f975a7a33a40e7c564f52c4a77de81c905.svn-base b/.svn/pristine/86/860d19f975a7a33a40e7c564f52c4a77de81c905.svn-base
new file mode 100644
index 0000000..3fec7c1
--- /dev/null
+++ b/.svn/pristine/86/860d19f975a7a33a40e7c564f52c4a77de81c905.svn-base
@@ -0,0 +1,60 @@
+using Serilog;
+using Serilog.Core;
+using Serilog.Events;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70.Admin
+{
+ ///
+ /// Interaction logic for LogViewerUC.xaml
+ ///
+ public partial class LogViewerUC : UserControl
+ {
+ private ObservableCollection _logItems = new ObservableCollection();
+
+ public LogViewerUC(ObservableCollection logCollection)
+ {
+ InitializeComponent();
+ LogListBox.ItemsSource = logCollection;
+ }
+ private void LogInfoButton_Click(object sender, RoutedEventArgs e)
+ {
+ Log.Information("This is an informational log message");
+ }
+ }
+ public class RealTimeLogSink : ILogEventSink
+ {
+ private readonly IFormatProvider _formatProvider;
+ private readonly ObservableCollection _logCollection;
+
+ public RealTimeLogSink(ObservableCollection logCollection, IFormatProvider formatProvider = null)
+ {
+ _logCollection = logCollection;
+ _formatProvider = formatProvider;
+ }
+
+ public void Emit(LogEvent logEvent)
+ {
+ var message = logEvent.RenderMessage(_formatProvider);
+ var logLevel = logEvent.Level.ToString();
+ var timestampedMessage = $"[{logEvent.Timestamp:HH:mm:ss}] [{logLevel}]{message}";
+
+ // Ensure the message is added on the UI thread
+ App.Current.Dispatcher.Invoke(() => _logCollection.Add(timestampedMessage));
+ }
+ }
+}
diff --git a/.svn/pristine/86/8690345f4c88ff483f6a2c17c8362be37320f81f.svn-base b/.svn/pristine/86/8690345f4c88ff483f6a2c17c8362be37320f81f.svn-base
new file mode 100644
index 0000000..374d71b
Binary files /dev/null and b/.svn/pristine/86/8690345f4c88ff483f6a2c17c8362be37320f81f.svn-base differ
diff --git a/.svn/pristine/86/869c7b33cfd2f27f8c12c13b3354a3bbcb81b2da.svn-base b/.svn/pristine/86/869c7b33cfd2f27f8c12c13b3354a3bbcb81b2da.svn-base
new file mode 100644
index 0000000..f9ab1ba
--- /dev/null
+++ b/.svn/pristine/86/869c7b33cfd2f27f8c12c13b3354a3bbcb81b2da.svn-base
@@ -0,0 +1,94 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70.StateMachine
+{
+ public class ProcessStateMachine
+ {
+ private string? _currentState;
+
+ public ProcessStateMachine()
+ {
+ _currentState = App.StateMachineConfig.States.FirstOrDefault();
+ }
+
+ public string CurrentState => _currentState;
+
+ public bool CanTransitionTo(string newState, out Transition transition)
+ {
+ transition = App.StateMachineConfig.Transitions
+ .FirstOrDefault(t => t.From.Contains(_currentState) && t.To.Contains(newState));
+
+ return transition != null;
+ }
+
+ public void TransitionToState(string newState)
+ {
+ if (CanTransitionTo(newState, out Transition transition))
+ {
+ if (ExecuteActions(transition))
+ {
+ // Transition to the new state if the required condition is met
+ _currentState = newState;
+ }
+ else
+ {
+ Console.WriteLine($"Failed to meet action requirements. Staying in {_currentState}.");
+ }
+ }
+ else
+ {
+ throw new InvalidOperationException($"Cannot transition from {_currentState} to {newState}");
+ }
+ }
+
+ private bool ExecuteActions(Transition transition)
+ {
+ bool allRequiredActionsSucceeded = true;
+ bool atLeastOneActionSucceeded = false;
+
+ foreach (var action in transition.Actions)
+ {
+ bool success = ExecuteAction(action.Name);
+
+ if (success)
+ {
+ atLeastOneActionSucceeded = true;
+ }
+
+ if (action.IsRequired && !success)
+ {
+ allRequiredActionsSucceeded = false;
+ }
+ }
+
+ // Determine if the transition should happen based on the condition
+ if (transition.RequireAtLeastOneActionSuccess)
+ {
+ return atLeastOneActionSucceeded;
+ }
+ else
+ {
+ return allRequiredActionsSucceeded;
+ }
+ }
+
+ private bool ExecuteAction(string actionName)
+ {
+ // Simulate action execution based on the action name
+ //Console.WriteLine($"Executing action: {App.StateMachineConfig.Actions[actionName]}");
+ switch(actionName)
+ {
+ case "DoInit":
+
+ break;
+ }
+
+ // For the sake of this example, all actions succeed
+ return true;
+ }
+ }
+}
diff --git a/.svn/pristine/87/8782736f94d9e19a7d09e468262069c1ae7e1d63.svn-base b/.svn/pristine/87/8782736f94d9e19a7d09e468262069c1ae7e1d63.svn-base
new file mode 100644
index 0000000..498915b
--- /dev/null
+++ b/.svn/pristine/87/8782736f94d9e19a7d09e468262069c1ae7e1d63.svn-base
@@ -0,0 +1,31 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.7.34202.233
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SafeBagDE70", "SafeBagDE70.csproj", "{DCA4F90E-EB1C-4038-BEAC-73BC15158E05}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleZebraTest", "..\ConsoleZebraTest\ConsoleZebraTest.csproj", "{04340425-3D86-4962-A61D-2E9A45B4A566}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {DCA4F90E-EB1C-4038-BEAC-73BC15158E05}.Release|Any CPU.Build.0 = Release|Any CPU
+ {04340425-3D86-4962-A61D-2E9A45B4A566}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {04340425-3D86-4962-A61D-2E9A45B4A566}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {04340425-3D86-4962-A61D-2E9A45B4A566}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {04340425-3D86-4962-A61D-2E9A45B4A566}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {471DAFF3-9038-41B5-8763-7F24A56B5F19}
+ EndGlobalSection
+EndGlobal
diff --git a/.svn/pristine/87/8799162778fe2ca8b630b0a03c3f4ce343e9e5c2.svn-base b/.svn/pristine/87/8799162778fe2ca8b630b0a03c3f4ce343e9e5c2.svn-base
new file mode 100644
index 0000000..099bffd
--- /dev/null
+++ b/.svn/pristine/87/8799162778fe2ca8b630b0a03c3f4ce343e9e5c2.svn-base
@@ -0,0 +1,37 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class InformationUC : UserControl
+ {
+ public InformationUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor)
+ {
+ lblInfor.Text = strInfor;
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ }
+ }
+}
diff --git a/.svn/pristine/89/89155091873a2b68ef93b952d308d729d4a82d7f.svn-base b/.svn/pristine/89/89155091873a2b68ef93b952d308d729d4a82d7f.svn-base
new file mode 100644
index 0000000..8dbed75
--- /dev/null
+++ b/.svn/pristine/89/89155091873a2b68ef93b952d308d729d4a82d7f.svn-base
@@ -0,0 +1,219 @@
+using DE70_CMDv2;
+using Newtonsoft.Json.Linq;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.ComponentModel;
+using System.Globalization;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ CDMSTATE=new CDMSTATE();
+ }
+ 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()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+ public class CountSession
+ {
+ public CountSession()
+ {
+ for (int i = 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ }
+ public class CDMSTATE : INotifyPropertyChanged
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ public int IsNotesInHopper = 0;
+ private byte _SR1;
+ public byte SR1 {
+ get
+ {
+ return _SR1;
+ }
+ set
+ {
+ if (_SR1 != value)
+ {
+ _SR1 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR1));
+ }
+ }
+ }
+ private byte _SR2;
+ public byte SR2
+ {
+ get
+ {
+ return _SR2;
+ }
+ set
+ {
+ if (_SR2 != value)
+ {
+ _SR2 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR2));
+ }
+ }
+ }
+ private byte _SR3;
+ public byte SR3
+ {
+ get
+ {
+ return _SR3;
+ }
+ set
+ {
+ if (_SR3 != value)
+ {
+ _SR3 = value;
+ UpdateCDMStatus();
+ OnPropertyChanged(nameof(SR3));
+ }
+ }
+ }
+ private void UpdateCDMStatus()
+ {
+ if (AppData.cCmdRsp != null) {
+ CDMStatus = "SR1: " + AppData.cCmdRsp.GetSR1Summary(SR1) + " SR2: " + AppData.cCmdRsp.GetSR2Summary(SR2);
+ }
+ }
+ private string? _CDMStatus;
+ public string? CDMStatus
+ {
+ get
+ {
+ return _CDMStatus;
+ }
+ set
+ {
+ if (_CDMStatus != value)
+ {
+ _CDMStatus = value;
+
+ OnPropertyChanged(nameof(CDMStatus));
+ }
+ }
+ }
+
+
+ public DateTime RequestTime = DateTime.Now;
+
+ public event PropertyChangedEventHandler PropertyChanged;
+ protected virtual void OnPropertyChanged(string propertyName)
+ {
+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
+ }
+ }
+}
diff --git a/.svn/pristine/8b/8b1422d42aae79f3f722640ec81745b271fb0f4f.svn-base b/.svn/pristine/8b/8b1422d42aae79f3f722640ec81745b271fb0f4f.svn-base
new file mode 100644
index 0000000..18c291c
--- /dev/null
+++ b/.svn/pristine/8b/8b1422d42aae79f3f722640ec81745b271fb0f4f.svn-base
@@ -0,0 +1,73 @@
+#pragma checksum "..\..\..\..\Views\SpecialCharactersView.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "EC45114FDAD29405F77A7A65B561949101DA8CB3"
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Controls.Ribbon;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Ink;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Media.Effects;
+using System.Windows.Media.Imaging;
+using System.Windows.Media.Media3D;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Windows.Shell;
+using VirtualKeyboard.Wpf.Views;
+
+
+namespace VirtualKeyboard.Wpf.Views {
+
+
+ internal partial class SpecialCharactersView : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
+
+ private bool _contentLoaded;
+
+ ///
+ /// InitializeComponent
+ ///
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ public void InitializeComponent() {
+ if (_contentLoaded) {
+ return;
+ }
+ _contentLoaded = true;
+ System.Uri resourceLocater = new System.Uri("/VirtualKeyboard;component/views/specialcharactersview.xaml", System.UriKind.Relative);
+
+ #line 1 "..\..\..\..\Views\SpecialCharactersView.xaml"
+ System.Windows.Application.LoadComponent(this, resourceLocater);
+
+ #line default
+ #line hidden
+ }
+
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.7.0")]
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
+ void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
+ this._contentLoaded = true;
+ }
+ }
+}
+
diff --git a/.svn/pristine/8e/8e1a3c751c32cd05158aef8414cd4b72d9e0147a.svn-base b/.svn/pristine/8e/8e1a3c751c32cd05158aef8414cd4b72d9e0147a.svn-base
new file mode 100644
index 0000000..13ab7e5
--- /dev/null
+++ b/.svn/pristine/8e/8e1a3c751c32cd05158aef8414cd4b72d9e0147a.svn-base
@@ -0,0 +1,20 @@
+VirtualKeyboard
+1.0.0.0
+
+library
+C#
+.cs
+D:\SRC\VirtualKeyboard\obj\Debug\net8.0-windows\
+VirtualKeyboard
+none
+false
+TRACE;DEBUG;NET;NET8_0;NETCOREAPP
+
+71703013248
+
+1757000672
+198-635017904
+DefaultKeyboardHost.xaml;ResourceDictionaries\DefaultStyles.xaml;ResourceDictionaries\KeyboardCore.xaml;Views\AlphabetView.xaml;Views\KeyboardValueView.xaml;Views\SpecialCharactersView.xaml;Views\VirtualKeyboardView.xaml;
+
+False
+
diff --git a/.svn/pristine/90/901cfab73c1a6033ef0b6c604a934c1049e6253c.svn-base b/.svn/pristine/90/901cfab73c1a6033ef0b6c604a934c1049e6253c.svn-base
new file mode 100644
index 0000000..abaec10
Binary files /dev/null and b/.svn/pristine/90/901cfab73c1a6033ef0b6c604a934c1049e6253c.svn-base differ
diff --git a/.svn/pristine/91/91d7ddb49c62819f00cd975185971b79890e0663.svn-base b/.svn/pristine/91/91d7ddb49c62819f00cd975185971b79890e0663.svn-base
new file mode 100644
index 0000000..1414de6
Binary files /dev/null and b/.svn/pristine/91/91d7ddb49c62819f00cd975185971b79890e0663.svn-base differ
diff --git a/.svn/pristine/91/91e3f0d5c59fd0a8dcca979a18b4bc5c2d08440f.svn-base b/.svn/pristine/91/91e3f0d5c59fd0a8dcca979a18b4bc5c2d08440f.svn-base
new file mode 100644
index 0000000..9292719
--- /dev/null
+++ b/.svn/pristine/91/91e3f0d5c59fd0a8dcca979a18b4bc5c2d08440f.svn-base
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/92/9246812741a295e94657a516fd22c8fdd95bdfdc.svn-base b/.svn/pristine/92/9246812741a295e94657a516fd22c8fdd95bdfdc.svn-base
new file mode 100644
index 0000000..9d4c819
--- /dev/null
+++ b/.svn/pristine/92/9246812741a295e94657a516fd22c8fdd95bdfdc.svn-base
@@ -0,0 +1,13 @@
+is_global = true
+build_property.TargetFramework = net8.0-windows
+build_property.TargetPlatformMinVersion = 7.0
+build_property.UsingMicrosoftNETSdkWeb =
+build_property.ProjectTypeGuids =
+build_property.InvariantGlobalization =
+build_property.PlatformNeutralAssembly =
+build_property.EnforceExtendedAnalyzerRules =
+build_property._SupportedPlatformList = Linux,macOS,Windows
+build_property.RootNamespace = VirtualKeyboard_zjdg1rtr_wpftmp
+build_property.ProjectDir = C:\Users\DELL Precision 7530\Desktop\Test\VK\VK\WPFKeyboard\VirtualKeyboard\
+build_property.EnableComHosting =
+build_property.EnableGeneratedComInterfaceComImportInterop =
diff --git a/.svn/pristine/94/9463600e85a19e65f5a3daf65a0551fa023ffce9.svn-base b/.svn/pristine/94/9463600e85a19e65f5a3daf65a0551fa023ffce9.svn-base
new file mode 100644
index 0000000..e8a3f70
--- /dev/null
+++ b/.svn/pristine/94/9463600e85a19e65f5a3daf65a0551fa023ffce9.svn-base
@@ -0,0 +1,116 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/95/9533fbb2b5d9cb35112fe25a338517eeff1192f1.svn-base b/.svn/pristine/95/9533fbb2b5d9cb35112fe25a338517eeff1192f1.svn-base
new file mode 100644
index 0000000..0eeb9b5
--- /dev/null
+++ b/.svn/pristine/95/9533fbb2b5d9cb35112fe25a338517eeff1192f1.svn-base
@@ -0,0 +1,186 @@
+{
+ "Serilog": {
+ "WriteTo": [
+ {
+ "Name": "File",
+ "Args": {
+ "path": "logs\\log_.txt",
+ "rollingInterval": "Day"
+ }
+ }
+ ]
+ },
+ "SerialPort": {
+ "CDMPort": "COM4",
+ "SensorPort": "COM3"
+ },
+ "StateMachine": {
+ "States": [
+ "Start",
+ "Init",
+ "Count",
+ "Check",
+ "Store",
+ "End",
+ "AutoEnd",
+ "Logout"
+ ],
+ "Transitions": [
+ {
+ "From": [ "Start" ],
+ "To": [ "Init" ],
+ "Actions": [
+ {
+ "Name": "DoInit",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Init" ],
+ "To": [ "Count" ],
+ "Actions": [
+ {
+ "Name": "DoCount",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": true
+ },
+ {
+ "From": [ "Count" ],
+ "To": [ "Check" ],
+ "Actions": [
+ {
+ "Name": "DoCheck",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": true
+ },
+ {
+ "From": [ "Count" ],
+ "To": [ "Store" ],
+ "Actions": [
+ {
+ "Name": "DoStore",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": true
+ },
+ {
+ "From": [ "Store" ],
+ "To": [ "End" ],
+ "Actions": [
+ {
+ "Name": "DoEnd",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": true
+ },
+ {
+ "From": [ "Count", "Check", "Store" ],
+ "To": [ "Count" ],
+ "Actions": [
+ {
+ "Name": "DoCount",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": true
+ },
+ {
+ "From": [ "End", "AutoEnd", "Logout" ],
+ "To": [ "Start" ],
+ "Actions": [
+ {
+ "Name": "DoLogout",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Start", "Init", "Count", "Check", "Store" ],
+ "To": [ "Timeout" ],
+ "Actions": [
+ {
+ "Name": "ShowTimeoutScreen",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Timeout" ],
+ "To": [ "Start", "Init", "Count", "Check", "Store" ],
+ "Actions": [
+ {
+ "Name": "BackScreen",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Init", "Count", "Check", "Store", "Timeout" ],
+ "To": [ "AutoEnd" ],
+ "Actions": [
+ {
+ "Name": "DoStore",
+ "IsRequired": true
+ },
+ {
+ "Name": "DoEnd",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Init", "Count", "Check", "Store", "Timeout" ],
+ "To": [ "Logout" ],
+ "Actions": [
+ {
+ "Name": "DoLogout",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Start", "Init", "Count", "Check", "Store", "Timeout" ],
+ "To": [ "Maintainance" ],
+ "Actions": [
+ {
+ "Name": "ShowMaintainanceScreen",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ },
+ {
+ "From": [ "Maintainance" ],
+ "To": [ "Start" ],
+ "Actions": [
+ {
+ "Name": "ShowWelcomeScreen",
+ "IsRequired": true
+ }
+ ],
+ "RequireAtLeastOneActionSuccess": false
+ }
+ ],
+ "Actions": {
+ "DoInit": "Initialize System",
+ "DoCount": "Start counting",
+ "DoCheck": "Get money for re-count",
+ "DoStore": "Perform Store",
+ "DoEnd": "Perform End",
+ "DoLogout": "Logout"
+ }
+ }
+}
diff --git a/.svn/pristine/96/961a49652ce243efa95878f58edfa9032fea2d9d.svn-base b/.svn/pristine/96/961a49652ce243efa95878f58edfa9032fea2d9d.svn-base
new file mode 100644
index 0000000..ca3b39d
--- /dev/null
+++ b/.svn/pristine/96/961a49652ce243efa95878f58edfa9032fea2d9d.svn-base
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/97/9776dd2270c9a53eb1202d42d75d113c379c3dd7.svn-base b/.svn/pristine/97/9776dd2270c9a53eb1202d42d75d113c379c3dd7.svn-base
new file mode 100644
index 0000000..915b635
--- /dev/null
+++ b/.svn/pristine/97/9776dd2270c9a53eb1202d42d75d113c379c3dd7.svn-base
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/97/97cb3e8f2140fef1fb9fa89c3eb2874ee028dec8.svn-base b/.svn/pristine/97/97cb3e8f2140fef1fb9fa89c3eb2874ee028dec8.svn-base
new file mode 100644
index 0000000..5806fc3
--- /dev/null
+++ b/.svn/pristine/97/97cb3e8f2140fef1fb9fa89c3eb2874ee028dec8.svn-base
@@ -0,0 +1,65 @@
+using SafeBagDE70.Model;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Windows.Threading;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for QRCodeWindow.xaml
+ ///
+ public partial class PinCodeWindow : HandyControl.Controls.Window
+ {
+ private DispatcherTimer timer;
+ int countTimer = 0;
+ public string QRCodeContent = null;
+ public PinCodeWindow()
+ {
+ InitializeComponent();
+ this.KeyDown += QRCodeWindow_KeyDown;
+ this.Loaded += QRCodeWindow_Loaded;
+ }
+ private void QRCodeWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ Keyboard.Focus(this);
+ timer = new DispatcherTimer();
+
+ // Set the timer interval to 1 second
+ timer.Interval = TimeSpan.FromMilliseconds(100);
+
+ // Define the event handler that's called each time the timer elapses
+ timer.Tick += Timer_Tick;
+
+ // Start the timer
+ timer.Start();
+ }
+ private void Timer_Tick(object sender, EventArgs e)
+ {
+ countTimer++;
+ if (QRCodeContent!=null && countTimer == 5)
+ {
+ // DialogResult = true;
+ // this.Close();
+ //finish
+ }
+ }
+
+ private void QRCodeWindow_KeyDown(object sender, KeyEventArgs e)
+ {
+ QRCodeContent += KeyModel.GetCharFromKey(e.Key);
+ countTimer = 0;
+ }
+
+ }
+}
diff --git a/.svn/pristine/97/97e1b01fd929956e63ecc946c60be192a367127f.svn-base b/.svn/pristine/97/97e1b01fd929956e63ecc946c60be192a367127f.svn-base
new file mode 100644
index 0000000..cb45f97
--- /dev/null
+++ b/.svn/pristine/97/97e1b01fd929956e63ecc946c60be192a367127f.svn-base
@@ -0,0 +1,51 @@
+using DE70_CMDv2;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ }
+}
diff --git a/.svn/pristine/98/98e5f6f571b817a33f406f2c356b9cc124d8e216.svn-base b/.svn/pristine/98/98e5f6f571b817a33f406f2c356b9cc124d8e216.svn-base
new file mode 100644
index 0000000..39e7d18
--- /dev/null
+++ b/.svn/pristine/98/98e5f6f571b817a33f406f2c356b9cc124d8e216.svn-base
@@ -0,0 +1,57 @@
+using DE70_CMDv2;
+using SafeBagDE70.Services;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class MaintainanceUC : UserControl
+ {
+ private bool _bContinue = false;
+ private bool _bPlaySound = false;
+ public MaintainanceUC()
+ {
+ InitializeComponent();
+ }
+ public void ShowInfor(string strInfor, bool bContinue = false, bool bPlaySound=true)
+ {
+ lblInfor.Text = strInfor;
+ _bContinue = bContinue;
+ _bPlaySound = bPlaySound;
+ if (_bPlaySound)
+ SoundManager.StartWarningSound();
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ if(_bContinue)
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen(false);
+ else
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ SoundManager.StopWarningSound();
+
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if (AppData.cCmdRsp != null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ SoundManager.StopWarningSound();
+ }
+ }
+}
diff --git a/.svn/pristine/9a/9a4abf1da0e290050ab9cc49fffb6d81ebcaa003.svn-base b/.svn/pristine/9a/9a4abf1da0e290050ab9cc49fffb6d81ebcaa003.svn-base
new file mode 100644
index 0000000..fea4028
Binary files /dev/null and b/.svn/pristine/9a/9a4abf1da0e290050ab9cc49fffb6d81ebcaa003.svn-base differ
diff --git a/.svn/pristine/9a/9ad53227cb472607ff25bb66da75d9cc2504201f.svn-base b/.svn/pristine/9a/9ad53227cb472607ff25bb66da75d9cc2504201f.svn-base
new file mode 100644
index 0000000..6bb9e3f
--- /dev/null
+++ b/.svn/pristine/9a/9ad53227cb472607ff25bb66da75d9cc2504201f.svn-base
@@ -0,0 +1,1358 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.StateMachine;
+using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
+using System.Runtime.Intrinsics.Arm;
+using SafeBagDE70.Services;
+using System.Windows.Forms;
+using Button = System.Windows.Controls.Button;
+using UserControl = System.Windows.Controls.UserControl;
+using Application = System.Windows.Application;
+using Control = System.Windows.Controls.Control;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositSMUCv2 : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer sensorTimer;
+ DispatcherTimer? warningTimer = null;
+ DispatcherTimer? endsessionTimer = null;
+ DispatcherTimer? backToWelcomeTimer = null;
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int countSensorTimer = 0;
+ private PrinterManager printerManager = new PrinterManager();
+
+ private NotesInSession notesInSession= new NotesInSession();
+ //DispatcherTimer?
+ private volatile bool bIsCounted = false;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+ bool bOpenPort = true;
+ bool bIsMaintain = false;
+ MainWindow mainWindow = null;
+ Thread thread = null;
+ Task taskCounting = null;
+ public DepositSMUCv2()
+ {
+ InitializeComponent();
+ }
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ mainWindow=((MainWindow)Application.Current.MainWindow);
+ InitTransaction();
+ StopTimers();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ lblName.Content= "Vietinbank " + Environment.MachineName;
+ if (AppData.IsAuthenticated)
+ {
+ 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}";
+ }
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+
+ notesInSession = new NotesInSession();
+ spNotesInSession.DataContext = notesInSession;
+
+ AppData.IsInTransaction = true;
+ ResetButtons();
+ btnStart.IsEnabled = true;
+ ResetTimers();
+ var state=GetCDMState();
+ if(state.GetSR2()==0x1C)
+ {
+ StopTimers();
+ ShowError(state.CDMStatus);
+ }
+ GetCassetteData();
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if(bOpenPort)
+ {
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+ if(bOpenPort)
+ {
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ }
+
+ private void InitTimers()
+ {
+ warningTimer = new DispatcherTimer(); // 30 seconds
+ warningTimer.Interval = new TimeSpan(0, 0, 30);
+ warningTimer.Tick += WarningTimer_Tick; ;
+ warningTimer.Stop();
+
+ endsessionTimer = new DispatcherTimer(); // 60 seconds
+ endsessionTimer.Interval = new TimeSpan(0, 0, 60);
+ endsessionTimer.Tick += EndSessionTimer_Tick;
+ endsessionTimer.Stop();
+
+ backToWelcomeTimer = new DispatcherTimer();
+ backToWelcomeTimer.Interval = new TimeSpan(0, 0, 15);
+ backToWelcomeTimer.Tick += BackToWelcomeTimer_Tick;
+ backToWelcomeTimer.Stop();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void StopWelcomeTimer()
+ {
+ if(backToWelcomeTimer != null)
+ backToWelcomeTimer.Stop();
+ }
+ public void StartWelcomeTimer()
+ {
+ if (backToWelcomeTimer != null)
+ backToWelcomeTimer.Start();
+ }
+ private void BackToWelcomeTimer_Tick(object? sender, EventArgs e)
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ private void EndSessionTimer_Tick(object? sender, EventArgs e)
+ {
+ Log.Information("7. Timout starting");
+ mainWindow.ShowEndSessionScreen();
+ StopTimers();
+ DoStoreStart();
+ bIsCounted = false;
+ DoCountStart();
+ Task.Run(() =>
+ {
+ taskCounting.Wait();
+ DoStoreStart();
+ Dispatcher.Invoke(() =>
+ {
+ EndSession(1);
+ });
+ Log.Information("7. Timout completed");
+ });
+
+
+ }
+
+ private void BackToWelcomeScreen()
+ {
+ StopTimers();
+
+ var cdmState = GetCDMState();
+ var state = GetCDMState();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsNotesInHopper > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", false, true);
+ }
+ else if (state.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ }
+
+ private void WarningTimer_Tick(object? sender, EventArgs e)
+ {
+
+ mainWindow.ShowTimeoutScreen();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ if (warningTimer != null)
+ {
+ warningTimer.Tick -=WarningTimer_Tick;
+ warningTimer.Stop();
+ }
+ if (endsessionTimer != null)
+ {
+ endsessionTimer.Tick -=EndSessionTimer_Tick;
+ endsessionTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+
+
+ public void InitLvCountItems()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ sensorTimer.IsEnabled = false;
+ try
+ {
+ countSensorTimer++;
+
+ if (countSensorTimer % 10 == 0)
+ {
+ var deviceStatus = new DeviceStatus
+ {
+ Device = Environment.MachineName,
+ Status = 0,
+ CDMStatus = 0,
+ PrinterStatus = 0,
+ DeviceTime = DateTime.Now,
+ OtherError = 0,
+ SensorStatus = 0,
+ TenantId = 5,
+ Description = AppData.CDMSTATE.CDMStatus,
+ Notes = AppData.NotesInCasset
+ };
+ APIModels.SendHealthCheck(deviceStatus);
+ var status = printerManager.GetStatus();
+ if(status.StsNOPAPER)
+ {
+ StopTimers();
+ ShowError("MÁY IN HẾT GIẤY! ĐỀ NGHỊ THAY GIẤY");
+ }
+ }
+
+ sensorTimer.IsEnabled = false;
+ GetSensorValue();
+ sensorTimer.IsEnabled = true;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, "Sensor_Timer");
+ }
+ sensorTimer.IsEnabled = true;
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ if (!bIsMaintain)
+ {
+ bIsMaintain = true;
+ DoMaintaince();
+ }
+
+ // TransitionToState("Maintainance");
+ }
+ else
+ {
+ if(bIsMaintain)
+ {
+ bIsMaintain = false;
+ mainWindow.ShowWelcomeScreen();
+ }
+
+ }
+
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"GetSensorValue");
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+ private void DoMaintaince()
+ {
+ StopTimers();
+ mainWindow.ShowMaintainanceScreen();
+ }
+
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet()
+ {
+ try
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ var countSession = new CountSession();
+ countSession.IsStored = false;
+ sessions.Add(countSession);
+ while (true)
+ {
+ AppData.WDTCount = 0;
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ AppData.WDTCount = 0;
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Status: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: countSession.TempNotes[0]++;break;
+ case 0x02:
+ //TempNote[1] ++;
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[17]}");
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: countSession.QuantityDenomi[0]++; break;
+ case 0x01: countSession.QuantityDenomi[1]++; break;
+ case 0x02: countSession.QuantityDenomi[2]++; break;
+ case 0x03: countSession.QuantityDenomi[3]++; break;
+ case 0x04: countSession.QuantityDenomi[4]++; break;
+ case 0x05: countSession.QuantityDenomi[5]++; break;
+ case 0x06: countSession.QuantityDenomi[6]++; break;
+ case 0x07: countSession.QuantityDenomi[7]++; break;
+ case 0x08: countSession.QuantityDenomi[8]++; break;
+ case 0x09: countSession.QuantityDenomi[9]++; break;
+
+ }
+ break;
+ case 0x03: countSession.TempNotes[2]++; break;
+ case 0x0b: countSession.TempNotes[3]++; break;
+ case 0x0c: countSession.TempNotes[4]++; break;
+ }
+ UpdateListViewCountItems();
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ if (countSession.QuantityDenomi.Sum() == 0 && countSession.TempNotes.Sum() == 0)
+ {
+ sessions.Remove(countSession);
+ }
+ }catch(Exception ex)
+ {
+ Log.Fatal(ex, "AutoSerialGet");
+ }
+
+ //Log.Information(JsonConvert.SerializeObject(sessions));
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private bool DoCountStart()
+ {
+ bool bSuccess = true;
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ if(bOpenPort)
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+ }
+
+
+ taskCounting = Task.Run(() =>
+ {
+ Log.Information("Before AutoCount: " + GetShortInforFromCountItems());
+ bIsCounted = false;
+ AutoSerialGet();
+ bIsCounted = true;
+ Log.Information("After AutoCount: " + GetShortInforFromCountItems());
+ });
+
+
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex,currentMethod);
+ }
+ return bSuccess;
+ }
+ private byte[] GetCassetteData()
+ {
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_READ_CASSETTE);
+ var data=cCmdRsp.recv_dat.dat;
+
+ StringBuilder str=new StringBuilder();
+ var recv_dat = cCmdRsp.recv_dat;
+
+ AppData.NotesInCasset = GetNotes(recv_dat.dat);
+ str.Append("DATA:");
+ for (int i = 0; i < recv_dat.leng - 1; i++)
+ {
+ var dat = string.Format("{0:X2} ", recv_dat.dat[i]);
+ str.Append(dat);
+ }
+ Log.Information("[CASSETTE]" + str.ToString());
+ return (byte[])data.Clone();
+ }
+ private int GetNotes(byte[] cassetData)
+ {
+ int notes = 0;
+ int offset = 14;
+ for (int i = 0; i < 10; i++)
+ {
+ notes += cassetData[2 * i + offset] * 256 + cassetData[2 * i + 1 + offset];
+ }
+ return notes;
+ }
+ private bool CheckStoreValid(byte[] previousCassetData, byte[] newCassetData,List countSessions)
+ {
+ var quantFromSession = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//500.000->500
+ foreach (var session in countSessions) {
+ if ((session.IsStored==false))
+ {
+ for (int i = 0; i < 10; i++)
+ quantFromSession[i] += session.QuantityDenomi[i];
+ }
+ }
+ var nPreviousCassetData = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ var nNewCassetData = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ int offset = 14;
+ bool bValid = true;
+ for(int i=0;i<10;i++)
+ {
+ nPreviousCassetData[i] = previousCassetData[2*i + offset] * 256 + previousCassetData[2*i + 1 + offset];
+ nNewCassetData[i]=newCassetData[2*i + offset] * 256 + newCassetData[2*i+1+ offset];
+ if (nNewCassetData[i] - nPreviousCassetData[i]!=quantFromSession[i])
+ {
+ bValid = false;
+ break;
+ }
+ }
+ return bValid;
+ }
+
+ private void UpdateListViewCountItems()
+ {
+ Dispatcher.Invoke(DispatcherPriority.Normal, () =>
+ {
+ double sum = 0;
+ if (sessions != null && sessions.Count > 0)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ int quantity = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ quantity += sessions[j].QuantityDenomi[9 - i];
+
+ }
+ lvCountItems[i].Quantity = quantity.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ //Update Notes In Sesion
+ notesInSession.GenuineNotes = 0;
+ notesInSession.RejectNotes = 0;
+
+ for (int j = 0; j < sessions.Count; j++)
+ {
+ if (sessions[j].IsStored == false)
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ notesInSession.GenuineNotes += sessions[j].QuantityDenomi[9 - i];
+ }
+ notesInSession.RejectNotes += sessions[j].TempNotes.Sum();
+ }
+ }
+ }
+ else
+ {
+ for (int i = 0; i < 11; i++)
+ {
+ lvCountItems[i].Quantity = "0";
+ lvCountItems[i].Value = "0";
+ }
+ }
+ });
+
+ }
+
+ public bool DoCheck()
+ {
+ bool bSuccess = true;
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ sessions.RemoveAll(item=>!item.IsStored);
+ Log.Information(JsonConvert.SerializeObject(sessions));
+ UpdateListViewCountItems();
+
+
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilCountReady(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while (true)
+ {
+ state = GetCDMState();
+ if (state.GetSR2() == 0x07)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool WaitUntilEnscrowEmpty(int nSecondTimeout)
+ {
+ CDMSTATE state = null;
+ int nTimes = 0;
+ bool bSuccess = false;
+ while(true)
+ {
+ state = GetCDMState();
+ if (state.IsNotesInEscrow == 0)
+ {
+ bSuccess = true;
+ break;
+ }
+ nTimes++;
+ Thread.Sleep(1000);
+ if ((nSecondTimeout > 0) && nTimes >= nSecondTimeout)
+ break;
+ }
+ return bSuccess;
+ }
+ private bool DoStoreStart()
+ {
+
+ bool bSuccess = true;
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ //sessions.Add(new CountSession());
+
+ // sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+
+ //Debug.WriteLine(quantityStored);
+
+ var previousCassetData = GetCassetteData();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ bSuccess=WaitUntilCountReady(10);
+ var newCasstData = GetCassetteData();
+ bool bValid= CheckStoreValid(previousCassetData,newCasstData,sessions);
+ if(bValid)
+ {
+ if (bSuccess)
+ {
+ foreach (var item in sessions)
+ {
+ item.IsStored = true;
+ }
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored " + GetShortInforFromCountItems());
+ }
+ else
+ {
+ Log.Error("Store FAIL " + GetShortInforFromCountItems());
+ }
+ }
+ 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";
+ Log.Information(str);
+ ShowError(str);
+ }
+
+ Thread.Sleep(2000);
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoStart()
+ {
+ bool bSuccess = true;
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ if (cCmdRsp.recv_dat.dat[0]!=0x40)
+ {
+ bSuccess = false;
+ }
+ }
+ catch (Exception ex)
+ {
+ bSuccess = false;
+ Log.Fatal(ex, currentMethod);
+ }
+ return bSuccess;
+ }
+
+
+ private bool DoEnd()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ StopTimers();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ var lstEnabledControls = new List { btnEnd, btnCountStart };
+ if (state.IsNotesInEscrow > 0)
+ {
+ btnEnd.IsEnabled = true;
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true,true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ btnEnd.IsEnabled = true;
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true, true);
+ }
+ else if(state.IsNotesInHopper>0)
+ {
+ btnEnd.IsEnabled = true;
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN NGĂN NỘP ĐỂ TIẾP TỤC", true, true);
+ }
+ else
+ {
+ bSuccess = true;
+ AppData.WDTCount = 0;
+ EndSession();
+
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+
+ ResetTimers();
+ }
+ return bSuccess;
+ }
+ private bool DoLogout()
+ {
+ bool bSuccess = false;
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ InitLvCountItems();
+ if (state.IsNotesInEscrow > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else //if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess = true;
+ ResetSessions();
+ BackToWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession(int _CountingState=0)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ //Remove sessions with store flag is false
+
+ sessions.RemoveAll(item => !item.IsStored);
+ UpdateListViewCountItems();
+
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ if (double.Parse(totalValue) > 0)
+ {
+ var data2Send = new CountingData2Send
+ {
+ TransactionCode = AppData.CurrentCustomerAccount.TransactionCode,
+ Sessions = sessions,
+ MachineId = Environment.MachineName,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ GenuineNotes = quantityStored,
+ CountingState= _CountingState
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if (double.Parse(totalValue) > 0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN NỘP TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+ mainWindow.ShowInformationScreen(strNotify, false, false);
+ ResetSessions();
+ StartWelcomeTimer();
+
+ }
+ else
+ {
+ mainWindow.ShowWelcomeScreen();
+ }
+ //SendData2Server
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex, currentMethod);
+ }
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Save2DB Exception");
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(ex,"Update2DB Exception");
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ mainWindow.ShowErrorScreen(strError);
+ }
+
+ public CDMSTATE GetCDMState()
+ {
+ return AppData.GetCDMState();
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ mainWindow.ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ mainWindow.ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ ResetSessions();
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal(ex,"InitSession");
+ }
+ return false;
+ }
+
+ private void ResetSessions()
+ {
+ InitLvCountItems();
+ sessions.Clear();
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ }
+
+ private void PrintReceipt()
+ {
+ Log.Information("PrintReceipt");
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = AppData.CurrentCustomerAccount.TransactionCode;// "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: "+Environment.MachineName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ public void ResetTimers()
+ {
+ StopTimers();
+ StartTimers();
+ }
+
+ public void StartTimers()
+ {
+ if(warningTimer!=null && endsessionTimer != null)
+ {
+ warningTimer.Start();
+ endsessionTimer.Start();
+ }
+
+ }
+
+ public void StopTimers()
+ {
+ if(warningTimer!=null && endsessionTimer !=null)
+ {
+ warningTimer.Stop();
+ endsessionTimer.Stop();
+ }
+
+ }
+
+ private void ResetButtons()
+ {
+ btnStart.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ btnLogout.IsEnabled = false;
+ }
+
+
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ SoundManager.StartButtonPressSound();
+ // Console.Beep(800, 200);
+ StopTimers();
+ bool bResult = false;
+ if (btn==btnStart)
+ {
+ Log.Information("Deposit starting");
+ Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ Log.Information("1. Start starting");
+ ResetButtons();
+ bResult = DoStart();
+ if (bResult)
+ {
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ }
+ else
+ {
+ btnStart.IsEnabled = true;
+ btnLogout.IsEnabled = true;
+ }
+ if (bResult)
+ Log.Information("1. Start completed");
+ else
+ Log.Information("1. Start failed");
+
+ }
+ else if(btn==btnCountStart)
+ {
+
+ Log.Information("2. Count starting");
+ ResetButtons();
+ bResult = DoCountStart();
+ Task.Run(() =>
+ {
+ taskCounting.Wait();
+ Dispatcher.Invoke(() =>
+ {
+ btnCountStart.IsEnabled = true;
+ btnCheck.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ ResetTimers();
+ Log.Information("2. Count completed");
+ });
+ });
+
+
+ }
+ else if(btn==btnCheck)
+ {
+ Log.Information($"3. Check starting");
+ ResetButtons();
+ bResult = DoCheck();
+ btnCountStart.IsEnabled= true;
+ ResetTimers();
+ if (bResult)
+ Log.Information($"3. Check completed");
+ else
+ Log.Information($"3. Check failed");
+ }
+ else if (btn == btnStoreStart)
+ {
+ //TransitionToState("Store");
+ Log.Information("4. Store starting");
+ ResetButtons();
+ bResult = DoStoreStart();
+ btnEnd.IsEnabled= true;
+ btnCountStart.IsEnabled = true;
+ ResetTimers();
+ if(bResult)
+ Log.Information("4. Store completed");
+ else
+ Log.Information("4. Store failed");
+ }
+ else if (btn == btnEnd)
+ {
+ // TransitionToState("End");
+ Log.Information("5. End starting");
+ ResetButtons();
+ bResult = DoEnd();
+ //btnStart.IsEnabled = true;
+ //btnLogout.IsEnabled = true;
+ //ResetTimers();
+ if (bResult)
+ Log.Information("5. End Completed");
+ else
+ Log.Information("5. End failed");
+ }
+ else if (btn == btnLogout)
+ {
+ Log.Information("6. Exit starting");
+ bResult = DoLogout();
+ if (bResult)
+ Log.Information("6. Exit Completed");
+ else
+ Log.Information("6. Exit failed");
+ }
+ }
+ }
+}
+
diff --git a/.svn/pristine/9d/9d4671c184f84ac6fbb646c52f350c0b6618a31c.svn-base b/.svn/pristine/9d/9d4671c184f84ac6fbb646c52f350c0b6618a31c.svn-base
new file mode 100644
index 0000000..d6d98a6
--- /dev/null
+++ b/.svn/pristine/9d/9d4671c184f84ac6fbb646c52f350c0b6618a31c.svn-base
@@ -0,0 +1,345 @@
+using CoreScanner;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+using System.Xml;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for WelcomeWindow.xaml
+ ///
+ public partial class WelcomeUC : UserControl
+ {
+ public string? PinCode = null;
+ public bool IsAuthenticated = false;
+ public CCoreScannerClass? cCoreScannerClass=null;
+ public WelcomeUC()
+ {
+ InitializeComponent();
+ InitQRCodeScanner();
+ Loaded += WelcomeUC_Loaded;
+ }
+
+ private void WelcomeUC_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.IsAuthenticated = false;
+ txtVersion.Text = "Version " + AppData.CurrentVersion;
+ }
+ public void Init()
+ {
+ AppData.IsAuthenticated = false;
+ AppData.CurrentCustomerAccount = null;
+ lblPincodeError.Content = "";
+ PinCodeBox.Text = "";
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ }
+
+ private void LoginButton_Click(object sender, RoutedEventArgs e)
+ {
+
+ string pin = PinCodeBox.Text;
+
+ if (ValidatePin(pin))
+ {
+ PinCode=PinCodeBox.Text.ToString();
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (PinCode != null)
+ {
+ var strPincode = PinCode.ToUpper();
+ cca = AppData.customerAccounts.Where(x => x.PINCode == strPincode).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ AppData.IsAuthenticated=true;
+ AppData.CurrentCustomerAccount=cca;
+ AppData.GetNewTransactionCode();
+ AppData.GetNewTransactionCode();
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ //DialogResult = true;
+ //this.Close();
+ }
+ else
+ {
+ lblPincodeError.Content = "PINCODE không đúng, vui lòng thử lại";
+ }
+ }
+ }
+ else
+ {
+ MessageBox.Show("Invalid PIN. Please try again.");
+ }
+ }
+
+ private void ForgotPin_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Forgot PIN clicked.");
+ }
+
+ private void Help_Click(object sender, RoutedEventArgs e)
+ {
+ MessageBox.Show("Phiên bản đang sử dụng là phiên bản mới nhất");
+ }
+
+ private bool ValidatePin(string pin)
+ {
+ return true;
+
+ }
+ private async void PinCodeButton_Click(object sender, RoutedEventArgs e)
+ {
+ //var onScreenKeyboardProcess = new ProcessStartInfo("osk.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ try
+ {
+ //var progFiles = @"C:\Program Files\Common Files\Microsoft Shared\ink";
+ //var keyboardPath = System.IO.Path.Combine(progFiles, "TabTip.exe");
+ //Process.Start(keyboardPath);
+ // AutomationElement.FromHandle(-1);
+
+ // string keyboardPath = @"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe";
+ // Process.Start(keyboardPath);
+ //await Launcher.LaunchUriAsync(new Uri("ms-inputapp://"));
+
+ //var onScreenKeyboardProcess = new ProcessStartInfo(@"C:\Program Files\Common Files\Microsoft Shared\ink\TabTip.exe")
+ //{
+ // UseShellExecute = true
+ //};
+ //Process.Start(onScreenKeyboardProcess);
+
+ QrCodePanel.Visibility = Visibility.Collapsed;
+ PinCodePanel.Visibility = Visibility.Visible;
+
+
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ }
+ catch {
+
+ }
+
+ }
+ private void btnQRCodeLogin_Click(object sender, RoutedEventArgs e)
+ {
+ PinCodePanel.Visibility = Visibility.Collapsed;
+ QrCodePanel.Visibility=Visibility.Visible;
+ cCoreScannerClass.BarcodeEvent += new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+
+
+ }
+ public void InitQRCodeScanner()
+ {
+ try
+ {
+ // Instantiate CoreScanner Class
+ cCoreScannerClass = new CCoreScannerClass();
+
+ // Call Open API
+ short[] scannerTypes = new short[1]; // Scanner Types you are interested in
+ scannerTypes[0] = 1; // 1 for all scanner types
+ short numberOfScannerTypes = 1; // Size of the scannerTypes array
+ int status; // Extended API return code
+
+ cCoreScannerClass.Open(0, scannerTypes, numberOfScannerTypes, out status);
+
+ // Subscribe for barcode events in cCoreScannerClass
+
+
+ // Let's subscribe for events
+ int opcode = 1001; // Method for Subscribe events
+ string outXML; // XML Output
+ string inXML = "" +
+ "" +
+ "1" + // Number of events you want to subscribe
+ "1" + // Comma separated event IDs
+ "" +
+ "";
+
+ cCoreScannerClass.ExecCommand(opcode, ref inXML, out outXML, out status);
+ }
+ catch (Exception exp)
+ {
+ Console.WriteLine("Something wrong please check... " + exp.Message);
+ }
+ }
+ private void OnBarcodeEvent(short eventType, ref string pscanData)
+ {
+ string xmlString = pscanData;
+ XmlDocument xmlDoc = new XmlDocument();
+ xmlDoc.LoadXml(xmlString);
+
+ XmlNode rawDataNode = xmlDoc.SelectSingleNode("//datalabel");
+ string rawDataHex = rawDataNode.InnerText.Trim();
+
+ var QRCodeContentFull = HexStringToString(rawDataHex);
+ string? CustomerID = null;
+ VerifyQRCode(QRCodeContentFull, out CustomerID);
+ if(CustomerID!=null)
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ if (AppData.customerAccounts != null)
+ {
+ CustomerAccount? cca = null;
+ if (CustomerID != null)
+ {
+ cca = AppData.customerAccounts.Where(x => x.QRCode == CustomerID).FirstOrDefault();
+ }
+
+ if (cca != null)
+ {
+ cCoreScannerClass.BarcodeEvent -= new _ICoreScannerEvents_BarcodeEventEventHandler(OnBarcodeEvent);
+ AppData.IsAuthenticated = true;
+ AppData.CurrentCustomerAccount = cca;
+ AppData.GetNewTransactionCode();
+ ((MainWindow)Application.Current.MainWindow).ShowDepositScreen();
+ }
+ else
+ {
+ lblQRcodeError.Content = "QRCODE không đúng, vui lòng thử lại";
+ }
+ }
+
+ });
+ }
+
+ }
+ private void VerifyQRCode(string decodedString,out string? ConsumerID)
+ {
+ ConsumerID = null;
+ try
+ {
+ var qrCodeData = decodedString;
+ // Extract the CRC from the QR code string
+ string extractedCRC = qrCodeData.Substring(qrCodeData.Length - 4);
+ // Get the data without the CRC part
+ string dataWithoutCRC = qrCodeData.Substring(0, qrCodeData.Length - 8);
+
+ // Calculate CRC
+ string calculatedCRC = CalculateCRC(dataWithoutCRC);
+
+ // Verify CRC
+ if (extractedCRC.Equals(calculatedCRC, StringComparison.OrdinalIgnoreCase))
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ lblQRcodeError.Content = "CRC is valid.";
+ });
+
+ Dictionary fields = ExtractFields(qrCodeData);
+
+ foreach (var field in fields)
+ {
+ Console.WriteLine($"ID: {field.Key}, Length: {field.Value.Length}, Value: {field.Value.Value}");
+ }
+ var fields2 = ExtractFields(fields["38"].Value);
+ var fields3 = ExtractFields(fields2["01"].Value);
+ ConsumerID = fields3["01"].Value;
+ }
+ else
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ lblQRcodeError.Content = "CRC is invalid.";
+ });
+
+ }
+
+
+ }
+ catch (Exception e)
+ {
+ this.Dispatcher.Invoke(() =>
+ {
+ lblQRcodeError.Content = e.Message;
+ });
+
+ }
+ }
+ Dictionary ExtractFields(string qrCodeData)
+ {
+ Dictionary fields = new Dictionary();
+
+ int currentIndex = 0;
+
+ while (currentIndex < qrCodeData.Length)
+ {
+ // Extract ID
+ string id = qrCodeData.Substring(currentIndex, 2);
+ currentIndex += 2;
+
+ // Extract Length
+ int length = int.Parse(qrCodeData.Substring(currentIndex, 2));
+ currentIndex += 2;
+
+ // Extract Value
+ string value = qrCodeData.Substring(currentIndex, length);
+ currentIndex += length;
+
+ // Add the field to the dictionary
+ fields[id] = (length, value);
+ }
+
+ return fields;
+ }
+ string CalculateCRC(string data)
+ {
+ ushort polynomial = 0x1021; // CRC-16-CCITT polynomial
+ ushort crc = 0xFFFF; // Initial value
+
+ // Convert the string to a byte array
+ byte[] bytes = Encoding.ASCII.GetBytes(data + "6304"); // Append "6304" for CRC calculation as per standard
+
+ foreach (byte b in bytes)
+ {
+ crc ^= (ushort)(b << 8);
+
+ for (int i = 0; i < 8; i++)
+ {
+ if ((crc & 0x8000) != 0)
+ {
+ crc = (ushort)((crc << 1) ^ polynomial);
+ }
+ else
+ {
+ crc <<= 1;
+ }
+ }
+ }
+
+ // Ensure CRC is a 16-bit value
+ crc &= 0xFFFF;
+
+ // Return CRC as a hexadecimal string
+ return crc.ToString("X4");
+ }
+ static string HexStringToString(string hexString)
+ {
+ string[] hexValues = hexString.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
+ byte[] bytes = new byte[hexValues.Length];
+
+ for (int i = 0; i < hexValues.Length; i++)
+ {
+ bytes[i] = Convert.ToByte(hexValues[i], 16);
+ }
+ return Encoding.ASCII.GetString(bytes);
+ }
+ }
+}
diff --git a/.svn/pristine/9e/9e1c6e4c91c0144ec37743db69379ec06343d8cd.svn-base b/.svn/pristine/9e/9e1c6e4c91c0144ec37743db69379ec06343d8cd.svn-base
new file mode 100644
index 0000000..6ed377e
--- /dev/null
+++ b/.svn/pristine/9e/9e1c6e4c91c0144ec37743db69379ec06343d8cd.svn-base
@@ -0,0 +1,33 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class CollectionUC : UserControl
+ {
+ public CollectionUC()
+ {
+ InitializeComponent();
+ }
+ public void Init()
+ {
+ }
+ }
+}
diff --git a/.svn/pristine/9f/9f1d468cf77b4af5281e491c8b6b095129773345.svn-base b/.svn/pristine/9f/9f1d468cf77b4af5281e491c8b6b095129773345.svn-base
new file mode 100644
index 0000000..c67e443
--- /dev/null
+++ b/.svn/pristine/9f/9f1d468cf77b4af5281e491c8b6b095129773345.svn-base
@@ -0,0 +1,31 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Data;
+using VirtualKeyboard.Wpf.Types;
+using VirtualKeyboard.Wpf.Views;
+
+namespace VirtualKeyboard.Wpf.Converters
+{
+ class KeyboardTypeConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ var type = (KeyboardType)value;
+ switch (type)
+ {
+ case KeyboardType.Alphabet: return new AlphabetView();
+ case KeyboardType.Special: return new SpecialCharactersView();
+ }
+ return null;
+ }
+
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/.svn/pristine/9f/9f5913d72db98ac7fb2652ad666f9ecabadc8db4.svn-base b/.svn/pristine/9f/9f5913d72db98ac7fb2652ad666f9ecabadc8db4.svn-base
new file mode 100644
index 0000000..4d1e817
--- /dev/null
+++ b/.svn/pristine/9f/9f5913d72db98ac7fb2652ad666f9ecabadc8db4.svn-base
@@ -0,0 +1,122 @@
+using Custom.CuCustomWndAPI;
+using Microsoft.Extensions.Configuration;
+using Newtonsoft.Json;
+using SafeBagDE70.Admin;
+using SafeBagDE70.Model;
+using SafeBagDE70.StateMachine;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Forms;
+using VirtualKeyboard.Wpf;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for App.xaml
+ ///
+ public partial class App : System.Windows.Application
+ {
+ public static StateMachineConfig StateMachineConfig { get; private set; }
+ private static Mutex mutex;
+ public App()
+ {
+ }
+ protected override void OnStartup(StartupEventArgs e)
+ {
+ base.OnStartup(e);
+
+ CheckInstance();
+ LoadConfig();
+ LoadDualScreens();
+ }
+ private static void CheckInstance()
+ {
+ bool isNewInstance;
+ string mutexName = "9f5b55c9-c6eb-443a-8e28-027defa46fb5";
+
+ mutex = new Mutex(true, mutexName, out isNewInstance);
+
+ if (!isNewInstance)
+ {
+ // If an instance is already running, exit the application
+ System.Windows.MessageBox.Show("Ứng dụng đã khởi chạy");
+ System.Windows.Application.Current.Shutdown();
+ return;
+ }
+ }
+ private static void LoadConfig()
+ {
+ try
+ {
+ AppData.CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version;
+ VKeyboard.Listen(e => e.Text);
+ var configuration = new ConfigurationBuilder()
+ .AddJsonFile("appsettings.json")
+ .Build();
+ Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .WriteTo.Sink(new RealTimeLogSink(AppData.logCollection))
+ .CreateLogger();
+ AppData.CDMPort = configuration["SerialPort:CDMPort"];
+ AppData.SensorPort = configuration["SerialPort:SensorPort"];
+ StateMachineConfig = new StateMachineConfig();
+ configuration.GetSection("StateMachine").Bind(StateMachineConfig);
+ Log.Information("START APP");
+ }
+ catch (Exception ex)
+ {
+ System.Windows.MessageBox.Show(ex.Message);
+ }
+ }
+ private void LoadDualScreens()
+ {
+ // Create instances of the windows you want to open
+ var mainWindow = new MainWindow();
+
+ // Show both windows
+ mainWindow.Show();
+
+ // Get all available screens
+ var screens = Screen.AllScreens;
+
+ // Open the Main Window on the primary screen
+ var primaryScreen = screens.FirstOrDefault(s => s.Primary) ?? screens.First();
+ PositionWindowOnScreen(mainWindow, primaryScreen);
+ mainWindow.Show();
+
+ // Open the Secondary Window on the secondary screen, if available
+ if (screens.Length > 1)
+ {
+ var adminWindow = new AdminWindow(); // Replace this with your actual window class
+ adminWindow.Show();
+ var secondaryScreen = screens.First(s => !s.Primary);
+ PositionWindowOnScreen(adminWindow, secondaryScreen);
+ adminWindow.Show();
+ }
+ }
+
+ private void PositionWindowOnScreen(Window window, Screen screen)
+ {
+ // Convert screen bounds to WPF units (96 DPI)
+ var screenLeft = screen.WorkingArea.Left / (double)Screen.PrimaryScreen.WorkingArea.Width * SystemParameters.PrimaryScreenWidth;
+ var screenTop = screen.WorkingArea.Top / (double)Screen.PrimaryScreen.WorkingArea.Height * SystemParameters.PrimaryScreenHeight;
+
+ // Set window position and state
+ window.WindowStartupLocation = WindowStartupLocation.Manual;
+ window.Left = screenLeft;
+ window.Top = screenTop;
+ window.Width = screen.WorkingArea.Width;
+ window.Height = screen.WorkingArea.Height;
+ }
+ }
+}
diff --git a/.svn/pristine/9f/9f8f845b531b366cc21abbf5d0be0461f72ebee7.svn-base b/.svn/pristine/9f/9f8f845b531b366cc21abbf5d0be0461f72ebee7.svn-base
new file mode 100644
index 0000000..1a47750
--- /dev/null
+++ b/.svn/pristine/9f/9f8f845b531b366cc21abbf5d0be0461f72ebee7.svn-base
@@ -0,0 +1,144 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+
+ //public class CountSession
+ //{
+ // public int[] QuantityDenomi { get; set; }
+ // public int[] SumDenomi { get; set; }
+
+ //}
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ private WelcomeUC _welcomeUC;
+ private DepositUC _depositUC;
+ private CollectionUC _collectionUC;
+ private InformationUC _informationUC;
+ private ErrorUC _errorUC;
+ private UserControl _currentUC;
+ private UserControl _prevUC;
+ private TimeoutUC _timeoutUC;
+ private object objLock = new object();
+ public MainWindow()
+ {
+ InitializeComponent();
+ Loaded += MainWindow_Loaded;
+
+ }
+
+ private void MainWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.Init();
+ if (_welcomeUC == null) _welcomeUC = new WelcomeUC();
+ if (_collectionUC == null) _collectionUC = new CollectionUC();
+ if (_informationUC == null) _informationUC = new InformationUC();
+ if (_errorUC == null) _errorUC = new ErrorUC();
+ if (_depositUC == null) _depositUC = new DepositUC();
+ if (_timeoutUC == null) _timeoutUC = new TimeoutUC();
+
+ gridMain.Children.Add(_welcomeUC);
+ gridMain.Children.Add(_depositUC);
+ gridMain.Children.Add(_collectionUC);
+ gridMain.Children.Add(_informationUC);
+ gridMain.Children.Add(_errorUC);
+ gridMain.Children.Add(_timeoutUC);
+
+ ShowWelcomeScreen();
+ }
+
+ public void HideAll()
+ {
+ lock(objLock)
+ {
+ foreach (var item in gridMain.Children)
+ {
+ if (item != null)
+ (item as UserControl).Visibility = Visibility.Hidden;
+ }
+ _collectionUC.Visibility = Visibility.Hidden;
+ _informationUC.Visibility = Visibility.Hidden;
+ _errorUC.Visibility = Visibility.Hidden;
+ _depositUC.Visibility = Visibility.Hidden;
+ _welcomeUC.Visibility = Visibility.Hidden;
+ }
+
+ }
+ public void ShowInformationScreen(string strInfor)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _informationUC;
+ HideAll();
+ _informationUC.Visibility = Visibility.Visible;
+ _informationUC.ShowInfor(strInfor);
+
+ }
+ public void ShowErrorScreen(string strError)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _errorUC;
+ HideAll();
+ _errorUC.Visibility = Visibility.Visible;
+ _errorUC.ShowInfor(strError);
+ }
+ public void ShowWelcomeScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _welcomeUC;
+ HideAll();
+ _welcomeUC.Visibility = Visibility.Visible;
+ }
+ public void ShowDepositScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _depositUC;
+ HideAll();
+ _depositUC.Visibility = Visibility.Visible;
+ //_depositUC.EndTransaction();
+ _depositUC.InitTransaction();
+ }
+ public void ShowCollectionScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _collectionUC;
+ HideAll();
+ _collectionUC.Visibility = Visibility.Visible;
+ }
+ public void ShowTimeoutScreen()
+ {
+ _prevUC = _currentUC;
+
+ HideAll();
+ _timeoutUC.Visibility = Visibility.Visible;
+ }
+ public void BackScreen()
+ {
+ HideAll();
+ _prevUC.Visibility = Visibility.Visible;
+ _currentUC = _prevUC;
+ }
+ }
+}
diff --git a/.svn/pristine/a0/a04a94bfc23126af90f9b619f2b1b69b9e8dfc70.svn-base b/.svn/pristine/a0/a04a94bfc23126af90f9b619f2b1b69b9e8dfc70.svn-base
new file mode 100644
index 0000000..2b9b639
--- /dev/null
+++ b/.svn/pristine/a0/a04a94bfc23126af90f9b619f2b1b69b9e8dfc70.svn-base
@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Shapes;
+
+namespace VirtualKeyboard.Wpf
+{
+ ///
+ /// Logika interakcji dla klasy DefaultKeyboardHost.xaml
+ ///
+ partial class DefaultKeyboardHost : Window
+ {
+ public DefaultKeyboardHost()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/.svn/pristine/a0/a0b209c65a2c6415a249534f5a032ea4ffcdb074.svn-base b/.svn/pristine/a0/a0b209c65a2c6415a249534f5a032ea4ffcdb074.svn-base
new file mode 100644
index 0000000..652c43a
--- /dev/null
+++ b/.svn/pristine/a0/a0b209c65a2c6415a249534f5a032ea4ffcdb074.svn-base
@@ -0,0 +1,19 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/a1/a1410d66717c07e8574132e2e5753dba8949e0c6.svn-base b/.svn/pristine/a1/a1410d66717c07e8574132e2e5753dba8949e0c6.svn-base
new file mode 100644
index 0000000..e96e65f
--- /dev/null
+++ b/.svn/pristine/a1/a1410d66717c07e8574132e2e5753dba8949e0c6.svn-base
@@ -0,0 +1,31 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/a1/a14745a43502313787df067cfe0716fdd647fb21.svn-base b/.svn/pristine/a1/a14745a43502313787df067cfe0716fdd647fb21.svn-base
new file mode 100644
index 0000000..1807831
--- /dev/null
+++ b/.svn/pristine/a1/a14745a43502313787df067cfe0716fdd647fb21.svn-base
@@ -0,0 +1,1065 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+using Serilog;
+using System.ComponentModel;
+using SafeBagDE70.Services;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositUC : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ public ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+
+ public DepositUC()
+ {
+ InitializeComponent();
+
+ }
+
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ InitTransaction();
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+ }
+
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+ // LoginUsingQRCode();
+ InitSerialPorts();
+ //Subscrible to the DataReveied event\
+ bInitialized = InitSession();
+ InitTimers();
+ AppData.IsInTransaction = true;
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ private void InitSerialPorts()
+ {
+ InitSerialPortDE70();
+ InitSerialPortSensor();
+ }
+
+ private void InitSerialPortSensor()
+ {
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortSensor.PortName = AppData.SensorPort;
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 1000;
+ serialPortSensor.WriteTimeout = 1000;
+
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+ }
+
+ private void InitSerialPortDE70()
+ {
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+
+
+ serialPortDE70.PortName = AppData.CDMPort;
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 10000;
+ serialPortDE70.WriteTimeout = 10000;
+
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+ }
+
+ private void InitTimers()
+ {
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems = new ObservableCollection()
+ {
+ new LvCountItem{Name = "500",Quantity = "0"},
+ new LvCountItem{Name = "1000",Quantity = "0"},
+ new LvCountItem{Name = "2000",Quantity = "0"},
+ new LvCountItem{Name = "5000",Quantity = "0"},
+ new LvCountItem{Name = "10000",Quantity = "0"},
+ new LvCountItem{Name = "20000",Quantity = "0"},
+ new LvCountItem{Name = "50000",Quantity = "0"},
+ new LvCountItem{Name = "100000",Quantity = "0"},
+ new LvCountItem{Name = "200000",Quantity = "0"},
+ new LvCountItem{Name = "500000",Quantity = "0"},
+ new LvCountItem{Name = "Tổng",Quantity = "0",Value="0"},
+ };
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "500",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "1000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "2000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "5000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "10000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "20000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "50000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "100000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "200000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "500000",
+ // Quantity = "0"
+ //});
+ //lvCountItems.Add(new LvCountItem
+ //{
+ // Name = "Tổng",
+ // Quantity = "0"
+ //});
+ //lvCountItems[10].Quantity = "0";
+ //lvCountItems[10].Value = "0";
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ timer.IsEnabled = false;
+ GetSensorValue();
+ if (AppData.IsInTransaction)
+ {
+ if (AppData.WDTCount == 30)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen();
+ }
+ else if (AppData.WDTCount == 60)
+ {
+ //Nhận tiền và Kết thúc
+ DoStoreStart();
+ EndSession();
+
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ }
+ AppData.WDTCount++;
+ }
+ else
+ {
+ AppData.WDTCount = 0;
+ }
+ timer.IsEnabled = true;
+ }
+ catch (Exception)
+ {
+
+ }
+
+
+ }
+ Stopwatch watch = new Stopwatch();
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ //serialPortSensor.DiscardInBuffer();
+ //serialPortSensor.DiscardOutBuffer();
+
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ if (state > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowMaintainanceScreen();
+ }
+ else
+ {
+ if (((MainWindow)Application.Current.MainWindow).IsMaintainanceScreen())
+ ((MainWindow)Application.Current.MainWindow).BackScreen();
+ }
+ break;
+ }
+ }
+
+ // the code that you want to measure comes here
+ watch.Stop();
+
+ var elapsedMs = watch.ElapsedMilliseconds;
+ Debug.WriteLine(elapsedMs);
+ watch.Start();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal("GetSensorValue", ex.ToString());
+ if(serialPortSensor.IsOpen)
+ serialPortSensor.Close();
+ serialPortSensor.Open();
+ serialPortSensor.DiscardInBuffer();
+ serialPortSensor.DiscardOutBuffer();
+ }
+ }
+
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ //Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ //Debug.WriteLine("START");
+ //Debug.WriteLine($"Num Serial: {seri_num}");
+ //Log.Information($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+
+ get_num++;
+
+ Log.Information($"Serial Idx: {get_num}/{seri_num}");
+ ret = cCmdRsp.SendGetSerial(get_num);
+ Log.Information($"Serial Value: {cCmdRsp.recv_dat.dat[18]}");
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ return 0;
+ }
+
+
+
+ private string GetShortInforFromCountItems()
+ {
+ return JsonConvert.SerializeObject(lvCountItems);
+ }
+
+ private void CountStart()
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+ Log.Information("Before AutoCount: "+GetShortInforFromCountItems());
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ Log.Information("After AutoCount: "+GetShortInforFromCountItems());
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(currentMethod, ex.ToString());
+ }
+ }
+
+
+ private void DoCheck()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+ Log.Information("Before Check: "+GetShortInforFromCountItems());
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ Log.Information("After Check: "+GetShortInforFromCountItems());
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(currentMethod, ex.ToString());
+ }
+ }
+
+
+ private void DoStoreStart()
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+ Log.Information("Stored "+GetShortInforFromCountItems());
+ //Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(currentMethod, ex.ToString());
+ }
+ }
+
+
+ private void DoStart()
+ {
+ InitSession();
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ AppData.IsInTransaction = true;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(currentMethod, ex.ToString());
+ }
+ }
+
+
+ private void DoEnd()
+ {
+ var state = GetCDMState();
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else
+ {
+ AppData.WDTCount = 0;
+ EndSession();
+ }
+ }
+ private bool DoLogout()
+ {
+ var state = GetCDMState();
+ Log.Information("CDM State: " + JsonConvert.SerializeObject(state));
+ bool bSuccess = false;
+ if (state.IsNotesInEscrow > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ HOẶC ẤN LƯU TRỮ ĐỂ TIẾP TỤC", true);
+
+ }
+ else if (state.IsNotesInRejectPocket > 0 || state.IsRejectPocketFull > 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN KHÔNG HỢP LỆ ĐỂ TIẾP TỤC", true);
+ }
+ else if (double.Parse(lvCountItems[10].Value)== 0)
+ {
+ bSuccess= true;
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ EndSession();
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ }
+ return bSuccess;
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+ try
+ {
+ Log.Information(currentMethod);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+
+ SyncData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ if(double.Parse(totalValue)>0)
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal(currentMethod, ex.ToString());
+ }
+
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify,false,false);
+ AppData.WDTCount = 45;
+ }
+
+ private async Task SyncData(CountingData2Send data2Send)
+ {
+ Log.Information("Saving data to DB: " + JsonConvert.SerializeObject(data2Send));
+ var history = Save2DB(data2Send);
+ Log.Information("Sending data to server: "+JsonConvert.SerializeObject(data2Send));
+ bool bSuccess = await APIModels.SendCountingData(data2Send);
+ if (bSuccess)
+ {
+ history.IsSent = true;
+ Update2DB(history);
+ Log.Information("Sending data to server successfully");
+ }
+ else
+ {
+ Log.Information("Sending data to server failed");
+ }
+ }
+
+ public History Save2DB(CountingData2Send data2Send)
+ {
+ var data = JsonConvert.SerializeObject(data2Send);
+ var history = new History
+ {
+ Data = data,
+ DepositTime = DateTime.Now,
+ IsSent = false,
+ UserCode = AppData.CurrentCustomerAccount.CustomerId
+ };
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Add(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal("Save2DB Exception", ex);
+ }
+ return history;
+ }
+ public History Update2DB(History history)
+ {
+
+ try
+ {
+ using (var db = new CDMDbContext())
+ {
+ db.Histories.Update(history);
+ db.SaveChanges();
+ }
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal("Update2DB Exception", ex);
+ }
+ return history;
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+ public class CDMSTATE
+ {
+ public int IsCassetteFull = 0;
+ public int IsNotesInEscrow = 0;
+ public int IsRejectPocketFull = 0;
+ public int IsNotesInRejectPocket = 0;
+ }
+ private CDMSTATE GetCDMState()
+ {
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ var cdmState = new CDMSTATE();
+
+ cdmState.IsCassetteFull = data[17] & 0x08;
+ cdmState.IsNotesInEscrow = data[4] & 0x01;
+ cdmState.IsRejectPocketFull = data[3] & 0x40;
+ cdmState.IsNotesInRejectPocket = data[3] & 0x10;
+ return cdmState;
+ }
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ var cdmState = GetCDMState();
+
+ if (cdmState.IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (cdmState.IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ Log.Fatal("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+
+ System.Drawing.Image LogoAeonMall = System.Drawing.Image.FromFile("Logo\\logoAeonmall.png");
+ System.Drawing.Image LogoVietin = System.Drawing.Image.FromFile("Logo\\logoVietin.png");
+
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ int fontSize = 8;
+ int lineSpace = 20;
+ float marginLeft = 25;
+ float marginTop = 5;
+ float width = 275;
+ float height = 280;
+
+ float LogoAeonWidth = 90; // Chiều rộng của LogoAeon
+ float LogoAeonHeight = 30; // Chiều cao của LogoAeon
+ float LogoAeonX = marginLeft + 25; // Đặt LogoAeon ở giữa theo chiều ngang
+ float LogoAeonY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoAeon
+
+ float LogoVietinWidth = 90; // Chiều rộng của LogoVietin
+ float LogoVietinHeight = 30; // Chiều cao của LogoVietin
+ float LogoVietinX = marginLeft + 165; // Đặt LogoVietin ở giữa theo chiều ngang
+ float LogoVietinY = marginTop + 10; // Khoảng cách từ mép trên của viền đến LogoVietin
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+
+ e.Graphics.DrawImage(LogoVietin, LogoVietinX, LogoVietinY, LogoVietinWidth, LogoVietinHeight);
+ e.Graphics.DrawImage(LogoAeonMall, LogoAeonX, LogoAeonY, LogoAeonWidth, LogoAeonHeight);
+
+ e.Graphics.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Black, 1), marginLeft, marginTop, width, height);
+
+
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 12, System.Drawing.FontStyle.Bold), System.Drawing.Brushes.Black, new PointF(80, 50));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 1 + 65));
+ e.Graphics.DrawString("Thời gian giao dịch: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 2 + 65));
+ e.Graphics.DrawString("Mã giao dịch: " + tradingCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 3 + 65));
+ e.Graphics.DrawString("Mã Gian hàng: " + shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 4 + 65));
+ e.Graphics.DrawString("Tên Gian hàng: " + shopName, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 5 + 65));
+ e.Graphics.DrawString("Số tài khoản gian hàng: " + storeAccountNumber, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 6 + 65));
+ e.Graphics.DrawString("Nội dung giao dịch: Nop doanh so tien mat_", new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 7 + 65));
+ e.Graphics.DrawString(shopCode, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 8 + 65));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", fontSize), System.Drawing.Brushes.Black, new PointF(50, lineSpace * 9 + 65));
+ e.Graphics.DrawString("*****Xin cám ơn*****", new Font("Arial", 7), System.Drawing.Brushes.Black, new PointF(120, lineSpace * 10 + 65));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+
+ private Button _previousClickedButton = null;
+ private void btnCommon_Click(object sender, RoutedEventArgs e)
+ {
+
+ var btn = sender as Button;
+ if (_previousClickedButton != null)
+ {
+ _previousClickedButton.BorderBrush = System.Windows.Media.Brushes.Transparent;
+ _previousClickedButton.BorderThickness = new Thickness(1);
+ }
+
+ // Set the border of the currently clicked button
+ btn.BorderBrush = System.Windows.Media.Brushes.DarkRed;
+ btn.BorderThickness = new Thickness(3);
+
+ // Update the previously clicked button reference
+ _previousClickedButton = btn;
+ //Console.Beep(800, 200);
+
+ if (btn==btnStart)
+ {
+
+ Log.Information("Deposit starting");
+ Log.Information("User: " + AppData.CurrentCustomerAccount.CustomerId);
+ Log.Information("1. Start starting");
+ DoStart();
+ Log.Information("1. Start completed");
+ AppData.WDTCount = 0;
+ }
+ else if(btn==btnCountStart)
+ {
+ Log.Information("2. Count starting");
+ CountStart();
+ Log.Information("2. Count completed");
+ AppData.WDTCount = 0;
+ }
+ else if(btn==btnCheck)
+ {
+ Log.Information($"3. Check starting");
+ DoCheck();
+ Log.Information($"3. Check completed");
+ AppData.WDTCount = 0;
+ }
+ else if (btn == btnStoreStart)
+ {
+ Log.Information("4. Store starting");
+ DoStoreStart();
+ Log.Information("4. Store completed");
+ AppData.WDTCount = 0;
+ }
+ else if (btn == btnEnd)
+ {
+ Log.Information("5. End starting");
+ DoEnd();
+ Log.Information("5. End Completed");
+ }
+ else if (btn == btnLogout)
+ {
+ Log.Information("6. Exit starting");
+ DoLogout();
+ Log.Information("6. Exit Completed");
+ }
+ }
+ }
+}
+
diff --git a/.svn/pristine/a1/a1c5657a0e69dada6422fdfbb628948bc992ce03.svn-base b/.svn/pristine/a1/a1c5657a0e69dada6422fdfbb628948bc992ce03.svn-base
new file mode 100644
index 0000000..f36be87
--- /dev/null
+++ b/.svn/pristine/a1/a1c5657a0e69dada6422fdfbb628948bc992ce03.svn-base
@@ -0,0 +1,1361 @@
+namespace DE70_CMDv2
+{
+ using SafeBagDE70;
+ using System;
+ using System.Diagnostics;
+ using System.IO;
+ using System.IO.Ports;
+ using System.Text;
+
+ public class CCmdRsp
+ {
+ public static CDenom[] mDenomTable = new CDenom[128];
+ public static int mDenominationCount;
+ public static string mSelectedCurrency;
+ public static int miSelectedCurrency;
+ private SerialPort serialPort = null;
+ private int m_all_sendsize;
+ private int m_all_recvsize;
+ private byte[] recv_buf = new byte[8192];
+ private byte[] m_send_buf = new byte[8192];
+ public RecvData recv_dat = new RecvData();
+ private SendDataStruct send_dat = new SendDataStruct();
+ private SendStatus cmd_result;
+ private LockParam lock_param = new LockParam();
+ private byte[] recv_serialset = new byte[256];
+ private Com232C m_ccom = null;
+
+ public CCmdRsp(SerialPort _serialPort)
+ {
+ serialPort = _serialPort;
+ m_ccom = new Com232C(_serialPort);
+ m_all_sendsize = 0;
+ m_all_recvsize = 0;
+ Array.Clear(recv_buf, 0, recv_buf.Length);
+ Array.Clear(m_send_buf, 0, m_send_buf.Length);
+ Array.Clear(recv_dat.dat, 0, recv_dat.dat.Length);
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ cmd_result = SendStatus.SEND_NON;
+ lock_param.Register = 1;
+ lock_param.ID = 1;
+ lock_param.TransactionNo = 1;
+ lock_param.mode = Mode.MODE_DEPOSIT;
+ lock_param.Currency = Currency.CURRENCY01; // first currency
+ lock_param.Gengai.amount = 0;
+ lock_param.Batch.Regi_num = 1;
+ Array.Clear(lock_param.Batch.batch_num, 0, lock_param.Batch.batch_num.Length);
+ Array.Clear(lock_param.Cassette.CassetteID, 0, lock_param.Cassette.CassetteID.Length);
+ Array.Clear(recv_serialset, 0, recv_serialset.Length);
+ }
+
+ public byte SendData()
+ {
+ byte ret = m_ccom.send_dat(m_send_buf, m_all_sendsize);
+ return ret;
+ }
+
+ public int SendSerialSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDeSense()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_SENSE;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDeviceSettingDataReq()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = 0x62;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDenomiRead2()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_BVDATA_READ;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSerialSet(byte[] dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETDATA;
+ send_dat.leng = 1 + 20;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ Array.Copy(dat, 0, send_dat.dat, 0, 20);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSetRJSerial()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETRJSERIAL;
+ send_dat.leng = 24;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ send_dat.dat[0] = 0x01;
+ send_dat.dat[1] = (byte)'I';
+ send_dat.dat[2] = (byte)'N';
+ send_dat.dat[3] = (byte)'R';
+ send_dat.dat[4] = 0x00;
+ send_dat.dat[5] = 5;
+ send_dat.dat[6] = 8;
+ send_dat.dat[7] = (byte)'4';
+ send_dat.dat[8] = (byte)'K';
+ send_dat.dat[9] = (byte)'T';
+ send_dat.dat[10] = (byte)'4';
+ send_dat.dat[11] = (byte)'7';
+ send_dat.dat[12] = (byte)'6';
+ send_dat.dat[13] = (byte)'6';
+ send_dat.dat[14] = (byte)'1';
+ send_dat.dat[15] = (byte)'#';
+ send_dat.dat[16] = (byte)'#';
+ send_dat.dat[17] = (byte)'#';
+ send_dat.dat[18] = (byte)'#';
+ send_dat.dat[19] = (byte)'#';
+ send_dat.dat[20] = (byte)'#';
+ send_dat.dat[21] = (byte)'#';
+ send_dat.dat[22] = (byte)'#';
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendSerialSetRead()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_SETDATAREAD;
+ send_dat.leng = 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ Array.Copy(recv_dat.dat, 13, recv_serialset, 0, recv_serialset.Length);
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendGetSerial(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_GDB_GETSERIAL;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendFreeDat()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = 0x00;
+ send_dat.leng = 1 + 1;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ if (!File.Exists("send.bin"))
+ {
+ cmd_result = SendStatus.SEND_DAT_ERR;
+ return Constants.E_NG_FILE;
+ }
+
+ byte[] fileData = File.ReadAllBytes("send.bin");
+ send_dat.cmd = fileData[0];
+ Array.Copy(fileData, 1, send_dat.dat, 0, fileData.Length - 1);
+ send_dat.leng = fileData.Length;
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendDataSet()
+ {
+ int sendsize = 0;
+ byte bcc = 0;
+ byte[] len_dat = new byte[3];
+ Array.Clear(m_send_buf, 0, m_send_buf.Length);
+
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ m_send_buf[sendsize++] = Constants.D_STX;
+ SetLen(len_dat, send_dat.leng);
+ for (int i = 0; i < 3; i++)
+ {
+ if (len_dat[i] == Constants.D_DLE)
+ {
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ }
+ m_send_buf[sendsize++] = len_dat[i];
+ bcc ^= len_dat[i];
+ }
+
+ m_send_buf[sendsize++] = send_dat.cmd;
+ bcc ^= send_dat.cmd;
+ for (int i = 0; i < send_dat.leng - 1; i++)
+ {
+ if (send_dat.dat[i] == Constants.D_DLE)
+ {
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ }
+ m_send_buf[sendsize++] = send_dat.dat[i];
+ bcc ^= send_dat.dat[i];
+ }
+ m_send_buf[sendsize++] = Constants.D_DLE;
+ m_send_buf[sendsize++] = Constants.D_ETX;
+ bcc ^= Constants.D_ETX;
+ m_send_buf[sendsize++] = bcc;
+ send_dat.bcc = bcc;
+
+ m_all_sendsize = sendsize;
+
+ return Constants.E_OK;
+ }
+
+ public int SetLen(byte[] dat, int size)
+ {
+ if (size <= 999)
+ {
+ dat[0] = (byte)((size / 100) | 0x30);
+ dat[1] = (byte)(((size % 100) / 10) | 0x30);
+ dat[2] = (byte)((size % 100) % 10 | 0x30);
+ }
+ else
+ {
+ dat[0] = (byte)((size / 0x010000) | 0x70);
+ dat[1] = (byte)((size % 0x010000) / 0x100);
+ dat[2] = (byte)((size % 0x010000) % 0x100);
+ }
+ return Constants.E_OK;
+ }
+
+ public byte WaitRsp()
+ {
+ int pos_r = 0;
+ int size;
+ int i;
+ bool dle_flg = false;
+ Array.Clear(recv_buf, 0, recv_buf.Length);
+ recv_dat.ret = Constants.E_OK;
+ recv_dat.cmd = 0x00;
+ recv_dat.leng = 0;
+ recv_dat.bcc = 0x00;
+ Array.Clear(recv_dat.dat, 0, recv_dat.dat.Length);
+
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 1);
+ if (size != 1)
+ {
+ return Constants.E_NG;
+ }
+ if (recv_buf[pos_r] == Constants.D_NAK)
+ {
+ return Constants.E_NG;
+ }
+ if (recv_buf[pos_r] != Constants.D_DLE)
+ {
+ return Constants.E_NG;
+ }
+ pos_r++;
+
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 1);
+ if (recv_buf[pos_r] != Constants.D_STX || size != 1)
+ {
+ return Constants.E_NG;
+ }
+ pos_r++;
+
+ if (WaitRspLen(ref recv_buf, pos_r, ref recv_dat.leng, out size) != Constants.E_OK)
+ {
+ return Constants.E_NG;
+ }
+ pos_r += size;
+
+ if (m_ccom.rcv_dat(recv_buf, pos_r, 1) != 1)
+ {
+ return Constants.E_NG;
+ }
+ recv_dat.cmd = recv_buf[pos_r];
+ pos_r++;
+
+ if (recv_dat.cmd == (byte)Command.CMD_GDB_GETSERIAL)
+ {
+ //Tạo buffer để nhận dữ liệu
+ //size = m_ccom.rcv_dat(recv_buf, pos_r, recv_dat.leng - 1);
+ int _size = 0;
+ int _pos_r = pos_r;
+ while (_size < recv_dat.leng - 1)
+ {
+ var _tsize = m_ccom.rcv_dat(recv_buf, _pos_r, recv_dat.leng - 1 - _size);
+ _size += _tsize;
+ _pos_r += _tsize;
+ }
+ size = _size;
+ //pos_r = _pos_r;
+ if (size != recv_dat.leng - 1)
+ {
+ return Constants.E_NG;
+ }
+ Array.Copy(recv_buf, pos_r, recv_dat.dat, 0, recv_dat.leng - 1);
+ pos_r += size;
+ }
+ else
+ {
+ i = 0;
+ while (i < recv_dat.leng - 1)
+ {
+ if (m_ccom.rcv_dat(recv_buf, pos_r, 1) != 1)
+ {
+ return Constants.E_NG;
+ }
+ if (!dle_flg && recv_buf[pos_r] == Constants.D_DLE)
+ {
+ pos_r++;
+ dle_flg = true;
+ continue;
+ }
+ recv_dat.dat[i] = recv_buf[pos_r];
+ pos_r++;
+ i++;
+ dle_flg = false;
+ }
+ size = m_ccom.rcv_dat(recv_buf, pos_r, 3);
+ recv_dat.bcc = recv_buf[pos_r + 2];
+ pos_r += size;
+ }
+ m_all_recvsize = pos_r;
+ return Constants.E_OK;
+ }
+
+ public int WaitRspLen(ref byte[] dat, int pos, ref int leng, out int size)
+ {
+ int initialPos = pos;
+
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if ((dat[pos] & 0xF0) == 0x70)
+ {
+ leng = (dat[pos] & 0x0F) * 0x10000;
+ pos++;
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (dat[pos] == Constants.D_DLE)
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ pos++;
+ }
+ leng += dat[pos] * 0x100;
+ pos++;
+
+ if (m_ccom.rcv_dat(dat, pos, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (dat[pos] == Constants.D_DLE)
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 1) != 1)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ pos++;
+ }
+ leng += dat[pos];
+ pos++;
+ }
+ else
+ {
+ if (m_ccom.rcv_dat(dat, pos + 1, 2) != 2)
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ if (((dat[pos] & 0x30) != 0x30) || ((dat[pos + 1] & 0x30) != 0x30) || ((dat[pos + 2] & 0x30) != 0x30))
+ {
+ size = 0;
+ return Constants.E_NG;
+ }
+ leng = (dat[pos] & 0x0F) * 100 + (dat[pos + 1] & 0x0F) * 10 + (dat[pos + 2] & 0x0F);
+ pos += 3;
+ }
+
+ size = pos - initialPos;
+ return Constants.E_OK;
+ }
+
+ public string GetSendDat(bool oneLine)
+ {
+ StringBuilder str = new StringBuilder();
+ StringBuilder dat = new StringBuilder();
+
+ string cmd = GetCommandName(send_dat.cmd);
+
+ dat.AppendFormat("SEND {0} L:{1} ", cmd, send_dat.leng);
+ str.Append(dat);
+
+ if (!oneLine)
+ {
+ str.Append("DATA:");
+ for (int i = 0; i < send_dat.leng - 1; i++)
+ {
+ dat.AppendFormat("{0:X2} ", send_dat.dat[i]);
+ str.Append(dat);
+ }
+
+ str.Append("\r\n");
+
+ if (cmd_result == SendStatus.SEND_RECV_OK || cmd_result == SendStatus.RECV_ERR)
+ {
+ for (int i = 0; i < m_all_sendsize; i++)
+ {
+ dat.AppendFormat("{0:X2} ", m_send_buf[i]);
+ str.Append(dat);
+ }
+ }
+ else if (cmd_result == SendStatus.SEND_DAT_ERR || cmd_result == SendStatus.SEND_ERR)
+ {
+ str.Append("send err");
+ }
+ str.Append("\r\n");
+ }
+ else
+ {
+ str.Append(" >> ");
+ str.Append(SetStText());
+ }
+
+ return str.ToString();
+ }
+
+ public string GetRecvDat()
+ {
+ StringBuilder str = new StringBuilder();
+ StringBuilder dat = new StringBuilder();
+
+ if (cmd_result == SendStatus.SEND_RECV_OK)
+ {
+ dat.AppendFormat("RECV CM:0x{0:X2} L:{1} ", recv_dat.cmd, recv_dat.leng);
+ str.Append(dat);
+ str.Append("DATA:");
+ for (int i = 0; i < recv_dat.leng - 1; i++)
+ {
+ dat.AppendFormat("{0:X2} ", recv_dat.dat[i]);
+ str.Append(dat);
+ }
+ str.Append("Raw: ");
+
+ for (int i = 0; i < m_all_recvsize; i++)
+ {
+ dat.AppendFormat("{0:X2} ", recv_buf[i]);
+ str.Append(dat);
+ }
+ }
+ else if (cmd_result == SendStatus.RECV_ERR)
+ {
+ str.Append("recv err");
+ }
+ str.Append("\r\n");
+ return str.ToString();
+ }
+
+ public int ImgSave(FileStream file)
+ {
+ if (send_dat.ret == Constants.E_OK && recv_dat.ret == Constants.E_OK)
+ {
+ file.Write(recv_dat.dat, 0, recv_dat.leng - 1);
+ }
+ return Constants.E_OK;
+ }
+
+ public int SendXXCmd(byte cmd)
+ {
+ return SendXXCmd(new byte[] { cmd }, 1);
+ }
+
+ public int SendXXCmd(byte[] cmd, int len)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = cmd[0];
+ send_dat.leng = len;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+
+ for (int x = 0; x < len - 1; x++)
+ {
+ send_dat.dat[x] = cmd[x + 1];
+ }
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendEventRead(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_EVDATA_READ;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendEventFix(ushort dat)
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_EVDATA_FIX;
+ send_dat.leng = 1 + 2;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ send_dat.dat[0] = (byte)((dat & 0xFF00) >> 8);
+ send_dat.dat[1] = (byte)(dat & 0x00FF);
+
+ SendDataSet();
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+
+ public int SendLock()
+ {
+ send_dat.ret = Constants.E_OK;
+ send_dat.cmd = (byte)Command.CMD_DE_LOCK;
+ send_dat.bcc = 0x00;
+ Array.Clear(send_dat.dat, 0, send_dat.dat.Length);
+ SetLockParam();
+
+ SendDataSet();
+
+ send_dat.ret = SendData();
+ if (send_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.SEND_ERR;
+ return Constants.E_NG_SEND;
+ }
+ recv_dat.ret = WaitRsp();
+ if (recv_dat.ret != Constants.E_OK)
+ {
+ cmd_result = SendStatus.RECV_ERR;
+ return Constants.E_NG_RECV;
+ }
+ cmd_result = SendStatus.SEND_RECV_OK;
+ return Constants.E_OK;
+ }
+ public LockParam GetLockParam()
+ {
+ return lock_param;
+ }
+ public void SetLockParam()
+ {
+ int size;
+ uint amount_i = 0;
+ uint amount_f = 0;
+
+ send_dat.dat[0] = 0x00;
+ send_dat.dat[1] = (byte)((lock_param.Register & 0xff00) >> 8);
+ send_dat.dat[2] = (byte)(lock_param.Register & 0xff);
+ send_dat.dat[3] = (byte)((lock_param.ID & 0xff000000) >> 24);
+ send_dat.dat[4] = (byte)((lock_param.ID & 0xff0000) >> 16);
+ send_dat.dat[5] = (byte)((lock_param.ID & 0xff00) >> 8);
+ send_dat.dat[6] = (byte)(lock_param.ID & 0xff);
+ send_dat.dat[7] = 9;
+ send_dat.dat[8] = (byte)((lock_param.TransactionNo & 0xff00) >> 8);
+ send_dat.dat[9] = (byte)(lock_param.TransactionNo & 0xff);
+ send_dat.dat[10] = (byte)lock_param.mode;
+ send_dat.dat[11] = (byte)(lock_param.Currency == Currency.CURRENCY_MLT ? 10 : (byte)lock_param.Currency);
+
+ switch (lock_param.mode)
+ {
+ case Mode.MODE_COUNT:
+ send_dat.dat[12] = 0;
+ size = 1 + 12 + 1;
+ break;
+ case Mode.MODE_MANUAL:
+ send_dat.dat[12] = 0;
+ amount_i = (uint)lock_param.Gengai.amount;
+ amount_f = (uint)((lock_param.Gengai.amount * 1000) - amount_i * 1000);
+ send_dat.dat[13] = (byte)((amount_i & 0xff000000) >> 24);
+ send_dat.dat[14] = (byte)((amount_i & 0xff0000) >> 16);
+ send_dat.dat[15] = (byte)((amount_i & 0xff00) >> 8);
+ send_dat.dat[16] = (byte)(amount_i & 0xff);
+ send_dat.dat[17] = (byte)((amount_f & 0xff00) >> 8);
+ send_dat.dat[18] = (byte)(amount_f & 0xff);
+ size = 1 + 12 + 7;
+ break;
+ case Mode.MODE_BATCH:
+ send_dat.dat[12] = (byte)lock_param.Batch.Regi_num;
+ Array.Copy(lock_param.Batch.batch_num, 0, send_dat.dat, 13, 64);
+ size = 1 + 12 + 65;
+ break;
+ case Mode.MODE_CHANGE:
+ case Mode.MODE_COLLECTION:
+ Array.Copy(lock_param.Cassette.CassetteID, 0, send_dat.dat, 12, 16);
+ size = 1 + 12 + 16;
+ break;
+ case Mode.MODE_SET:
+ send_dat.dat[12] = 5;
+ send_dat.dat[13] = 4;
+ send_dat.dat[14] = 2;
+ send_dat.dat[15] = 0;
+ send_dat.dat[16] = 5;
+ size = 1 + 12 + 5;
+ break;
+ default:
+ size = 1 + 12;
+ break;
+ }
+ send_dat.leng = size;
+ }
+
+ public string SetStText()
+ {
+ StringBuilder text = new StringBuilder();
+
+ switch (cmd_result)
+ {
+ case SendStatus.SEND_ERR:
+ case SendStatus.SEND_DAT_ERR:
+ text.Append("SEND_ERR");
+ break;
+ case SendStatus.RECV_ERR:
+ text.Append("RECV_ERR");
+ break;
+ case SendStatus.SEND_RECV_OK:
+ text.Append("SR1");
+ text.Append(GetSR1Summary(recv_dat.dat[0]));
+ text.Append(", ");
+
+ text.AppendFormat("SR2: ");
+ text.Append(GetSR2Summary(recv_dat.dat[1]));
+ text.Append(", ");
+
+ if (recv_dat.leng >= 15)
+ {
+ if (recv_dat.cmd == (byte)Command.CMD_DE_SENSE || recv_dat.cmd == (byte)Command.CMD_GDB_SENSE)
+ {
+ text.AppendFormat("Sent/unsent events:{0}/{1} ",
+ recv_dat.dat[13] * 0x0100 + recv_dat.dat[14],
+ recv_dat.dat[15] * 0x0100 + recv_dat.dat[16]);
+ if (recv_dat.leng == 84 || recv_dat.leng == 86)
+ {
+ text.Append(GetSummaryTotal(recv_dat.dat, 19));
+ }
+ }
+ }
+ break;
+ case SendStatus.SEND_NON:
+ default:
+ text.Append("SEND_NON");
+ break;
+ }
+ return text.ToString();
+ }
+
+ public string GetSummaryTotal(byte[] counts, int numDenoms, bool wordcounts = true)
+ {
+ StringBuilder ret = new StringBuilder();
+ double[] total = new double[10];
+ string[] pCurrencyID = new string[10];
+
+ Array.Clear(total, 0, total.Length);
+ Array.Clear(pCurrencyID, 0, pCurrencyID.Length);
+
+ if (mDenominationCount > 0 && mDenominationCount < 65)
+ {
+ numDenoms = Math.Min(numDenoms, mDenominationCount);
+
+ for (int x = 0; x < numDenoms; x++)
+ {
+ if (mDenomTable[x].mCurrenyIndex < total.Length)
+ {
+ int noteCount;
+ if (wordcounts)
+ {
+ noteCount = counts[x * 2] * 256 + counts[x * 2 + 1];
+ }
+ else
+ {
+ noteCount = counts[x];
+ }
+ total[mDenomTable[x].mCurrenyIndex] += mDenomTable[x].mDenomValue * noteCount;
+ pCurrencyID[mDenomTable[x].mCurrenyIndex] = mDenomTable[x].currency;
+ }
+ }
+ ret.Append("Counted: ");
+ for (int x = 0; x < total.Length; x++)
+ {
+ if (total[x] != 0)
+ {
+ ret.AppendFormat(" {0}: {1:0.00}", pCurrencyID[x] ?? "???", total[x]);
+ }
+ }
+ }
+ else
+ {
+ ret.Append(" No denom data");
+ }
+
+ return ret.ToString();
+ }
+
+ public string GetSR1Summary(byte sr1)
+ {
+ StringBuilder text = new StringBuilder();
+
+ text.AppendFormat("(0x{0:X2}): ", sr1);
+ switch (sr1)
+ {
+ case 0x40:
+ text.Append("CMD OK");
+ break;
+ case 0x41:
+ text.Append("No execution");
+ break;
+ case 0x42:
+ text.Append("Store fail,");
+ break;
+ case 0x43:
+ text.Append("Unknown command");
+ break;
+ case 0x44:
+ text.Append("Length error");
+ break;
+ case 0x46:
+ text.Append("CMD error (not executed)");
+ break;
+ case 0x47:
+ text.Append("Local processing");
+ break;
+ case 0x48:
+ text.Append("Already occupied");
+ break;
+ case 0x49:
+ text.Append("Abnormal data");
+ break;
+ default:
+ text.Append("Unknown SR1");
+ break;
+ }
+ return text.ToString();
+ }
+ public string GetS1Summary(byte s1)
+ {
+ string text = string.Format("(0x{0:X}): {1}{2}{3}{4}{5}{6}{7}{8}", s1,
+ (s1 & 0x80) != 0 ? "Locked, " : "Not locked, ",
+ (s1 & 0x40) != 0 ? "Escrow door closed, " : "Escrow door open, ",
+ (s1 & 0x20) != 0 ? "" : "bit5=false, ",
+ (s1 & 0x10) != 0 ? "" : "bit4=false, ",
+ (s1 & 0x08) != 0 ? "Cassette full, " : "Cassette not full, ",
+ (s1 & 0x04) != 0 ? "bit2=true, " : "",
+ (s1 & 0x02) != 0 ? "bit1=true, " : "",
+ (s1 & 0x01) != 0 ? "Dirty sensor, " : "No dirty sensor, ");
+
+ text = text.TrimEnd(',', ' ');
+
+ return text;
+ }
+ public string GetSR2Summary(byte sr2)
+ {
+ StringBuilder text = new StringBuilder();
+
+ text.AppendFormat("(0x{0:X2}): ", sr2);
+ switch (sr2)
+ {
+ case 0x01:
+ text.Append("Initialising");
+ break;
+ case 0x1c:
+ text.Append("Initialisation error (cycle power)");
+ break;
+ case 0x1b:
+ text.Append("Resetting");
+ break;
+ case 0x0a:
+ text.Append("Waiting for notes to be removed");
+ break;
+ case 0x04:
+ text.Append("Stand by");
+ break;
+ case 0x07:
+ text.Append("Ready to count");
+ break;
+ case 0x09:
+ text.Append("Counting/batch");
+ break;
+ case 0x1f:
+ text.Append("Batch processing");
+ break;
+ case 0x0d:
+ text.Append("Setting");
+ break;
+ default:
+ text.Append("Unknown SR2");
+ break;
+ }
+ return text.ToString();
+ }
+
+ public int GetSerialNum(out ushort num)
+ {
+ ushort serial_num;
+
+ if (recv_dat.cmd == (byte)Command.CMD_GDB_SENSE && recv_dat.leng == Constants.DATLEN_GDBSense_Cnt)
+ {
+ serial_num = (ushort)(recv_dat.dat[83] * 0x100 + recv_dat.dat[84]);
+ if (serial_num <= 1000)
+ {
+ num = serial_num;
+ return Constants.E_OK;
+ }
+ }
+ num = 0x00;
+ return Constants.E_NG;
+ }
+
+ public bool ChkCntEnd()
+ {
+ return recv_dat.cmd != (byte)Command.CMD_GDB_SENSE || recv_dat.dat[1] != (byte)SR2.SR2_cnting;
+ }
+
+ public void GetRecvSerialSet(byte[] dat)
+ {
+ Array.Copy(recv_serialset, dat, recv_serialset.Length);
+ }
+
+ public override string ToString()
+ {
+ return GetSendDat(true);
+ }
+
+ public int GetSendDatLength()
+ {
+ return send_dat.leng;
+ }
+
+ public int GetRecDatLength()
+ {
+ return recv_dat.leng - 1;
+ }
+
+ public byte[] GetSendDatPtr()
+ {
+ return send_dat.dat;
+ }
+
+ public byte[] GetRecDatPtr()
+ {
+ return recv_dat.dat;
+ }
+
+ public Command GetCmdByte()
+ {
+ return (Command)send_dat.cmd;
+ }
+
+ public string GetCommandName(byte cmd)
+ {
+ switch (cmd)
+ {
+ case 0x22:
+ return "CMD_SENSE";
+ case 0x40:
+ return "CMD_ST_UPLOAD";
+ case 0x41:
+ return "CMD_END_UPLOAD";
+ case 0x44:
+ return "CMD_REQ_UPLOAD";
+ case 0x45:
+ return "CMD_ST_DOWNLOAD";
+ case 0x46:
+ return "CMD_END_DOWNLOAD";
+ case 0x49:
+ return "CMD_REQ_DOWNLOAD";
+ case 0x4A:
+ return "CMD_P_UPDATE";
+ case 0x4D:
+ return "CMD_GETFILEINFO";
+ case 0x59:
+ return "CMD_VERSION";
+ case 0x60:
+ return "CMD_DE_SENSE";
+ case 0x61:
+ return "CMD_DE_SET_TIME";
+ case 0x62:
+ return "CMD_DE_SETDATA_READ";
+ case 0x63:
+ return "CMD_DE_BVDATA_READ";
+ case 0x64:
+ return "CMD_DE_EVDATA_READ";
+ case 0x65:
+ return "CMD_DE_EVDATA_FIX";
+ case 0x66:
+ return "CMD_DE_READ_CASSETTE";
+ case 0x70:
+ return "CMD_DE_LOCK";
+ case 0x71:
+ return "CMD_DE_UNLOCK";
+ case 0x73:
+ return "CMD_DE_CNTSTART";
+ case 0x74:
+ return "CMD_DE_CNTEND";
+ case 0x75:
+ return "CMD_DE_STORESTART";
+ case 0x76:
+ return "CMD_DE_CANCEL";
+ case 0x77:
+ return "CMD_DE_RESET";
+ case 0x78:
+ return "CMD_DE_TRANSACTION_READ";
+ case 0x79:
+ return "CMD_DE_DEALFORGOTTEN";
+ case 0x80:
+ return "CMD_GDB_SENSE";
+ case 0x81:
+ return "CMD_GDB_BVDATA_READ";
+ case 0x82:
+ return "CMD_GDB_SETDATA";
+ case 0x83:
+ return "CMD_GDB_SETRJSERIAL";
+ case 0x84:
+ return "CMD_GDB_SETDATAREAD";
+ case 0xA0:
+ return "CMD_GDB_GETSERIAL";
+ default:
+ return "Unknown Command";
+ }
+ }
+
+ public void ClearDenomTable()
+ {
+ for (int x = 0; x < GetDenomTableElements(); x++)
+ {
+ if (mDenomTable[x].currency != null)
+ {
+ mDenomTable[x].currency = null;
+ }
+ mDenomTable[x].mCurrenyIndex = 0;
+ mDenomTable[x].currency = null;
+ mDenomTable[x].issue = 0;
+ mDenomTable[x].mDenomValue = 0;
+ }
+
+ mDenominationCount = 0;
+ }
+
+ public CDenom[] GetDenomTablePtr()
+ {
+ return mDenomTable;
+ }
+
+ public int GetDenomTableElements()
+ {
+ return mDenomTable.Length;
+ }
+
+ public void SetDenominationCount(int c)
+ {
+ mDenominationCount = c;
+ }
+ }
+
+ public class Constants
+ {
+ public const byte D_DLE = 0x10;
+ public const byte D_STX = 0x02;
+ public const byte D_NAK = 0x15;
+ public const byte D_ETX = 0x03;
+ public const byte E_OK = 0x00;
+ public const byte E_NG = 0x01;
+ public const byte E_NG_FILE = 0x02;
+ public const byte E_NG_DAT = 0x03;
+ public const byte E_NG_SEND = 0x04;
+ public const byte E_NG_RECV = 0x05;
+ public const int DATLEN_GDBSense_Cnt = 86;
+ }
+
+ public class SendDataStruct
+ {
+ public byte ret;
+ public byte cmd;
+ public int leng;
+ public byte bcc;
+ public byte[] dat = new byte[1024];
+ }
+
+ public class RecvData
+ {
+ public byte ret;
+ public byte cmd;
+ public int leng;
+ public byte bcc;
+ public byte[] dat = new byte[8192];
+ }
+
+ public enum SendStatus
+ {
+ SEND_NON,
+ SEND_RECV_OK,
+ SEND_DAT_ERR,
+ SEND_ERR,
+ RECV_ERR
+ }
+
+ public enum Mode
+ {
+ MODE_DEPOSIT = 1,
+ MODE_COUNT = 2,
+ MODE_MANUAL = 3,
+ MODE_BATCH = 4,
+ MODE_CLOSE = 5,
+ MODE_TCLS = 6,
+ MODE_CHANGE = 7,
+ MODE_COLLECTION = 8,
+ MODE_SET = 9,
+ MODE_SECERROR = 14
+ }
+
+ public enum Currency
+ {
+ CURRENCY01, //‘æ‚P’ʉÝ
+ CURRENCY02, //‘æ‚Q’ʉÝ
+ CURRENCY03, //‘æ‚R’ʉÝ
+ CURRENCY04, //‘æ‚S’ʉÝ
+ CURRENCY05, //‘æ‚T’ʉÝ
+ CURRENCY06, //‘æ‚U’ʉÝ
+ CURRENCY07, //‘æ‚V’ʉÝ
+ CURRENCY_MLT, //’ʉ݃}ƒ‹ƒ`
+ }
+
+ enum SR2
+ {
+ SR2_init = 0x01,
+ SR2_wait = 0x04,
+ SR2_cntwait = 0x07,
+ SR2_cnting = 0x09,
+ SR2_check = 0x0a,
+ SR2_seting = 0x0d,
+ SR2_reset = 0x1b,
+ SR2_rst_wait = 0x1c,
+ SR2_ras = 0x1d,
+ SR2_batch = 0x1f,
+ };
+
+ public enum Command
+ {
+ CMD_NULL = 0, // uninitialised / not a command value
+ CMD_SENSE = 0x22,
+ CMD_ST_UPLOAD = 0x40,
+ CMD_END_UPLOAD = 0x41,
+ CMD_REQ_UPLOAD = 0x44,
+ CMD_ST_DOWNLOAD = 0x45,
+ CMD_END_DOWNLOAD = 0x46,
+ CMD_REQ_DOWNLOAD = 0x49,
+ CMD_P_UPDATE = 0x4A,
+ CMD_GETFILEINFO = 0x4D,
+ CMD_VERSION = 0x59,
+ CMD_DE_SENSE = 0x60,
+ CMD_DE_SET_TIME = 0x61,
+ CMD_DE_SETDATA_READ = 0x62,
+ CMD_DE_BVDATA_READ = 0x63,
+ CMD_DE_EVDATA_READ = 0x64,
+ CMD_DE_EVDATA_FIX = 0x65,
+ CMD_DE_READ_CASSETTE = 0x66,
+ CMD_DE_LOCK = 0x70,
+ CMD_DE_UNLOCK = 0x71,
+ CMD_DE_CNTSTART = 0x73,
+ CMD_DE_CNTEND = 0x74,
+ CMD_DE_STORESTART = 0x75,
+ CMD_DE_CANCEL = 0x76,
+ CMD_DE_RESET = 0x77,
+ CMD_DE_TRANSACTION_READ = 0x78,
+ CMD_DE_DEALFORGOTTEN = 0x79,
+ CMD_GDB_SENSE = 0x80,
+ CMD_GDB_BVDATA_READ = 0x81,
+ CMD_GDB_SETDATA = 0x82,
+ CMD_GDB_SETRJSERIAL = 0x83,
+ CMD_GDB_SETDATAREAD = 0x84,
+ CMD_GDB_GETSERIAL = 0xA0,
+ }
+
+ public class Com232C
+ {
+ SerialPort serialPort = null;
+ public Com232C(SerialPort _serialPort)
+ {
+ this.serialPort = _serialPort;
+ }
+ public byte send_dat(byte[] buf, int size)
+ {
+ //Debug.WriteLine(DE70_CMD.ByteArrayToString(buf, 0, size));
+ serialPort.Write(buf, 0, size);
+ // Implement serial communication send function
+ return Constants.E_OK;
+ }
+
+ public int rcv_dat(byte[] buf, int pos, int size)
+ {
+ return serialPort.Read(buf, pos, size);
+ // Implement serial communication receive function
+
+ }
+ }
+
+ public class LockParam
+ {
+ public int Register;
+ public int ID;
+ public int TransactionNo;
+ public Mode mode;
+ public Currency Currency;
+ public Gengai Gengai = new Gengai();
+ public Batch Batch = new Batch();
+ public Cassette Cassette = new Cassette();
+ }
+
+ public class Gengai
+ {
+ public double amount;
+ }
+
+ public class Batch
+ {
+ public int Regi_num;
+ public byte[] batch_num = new byte[64];
+ }
+
+ public class Cassette
+ {
+ public byte[] CassetteID = new byte[16];
+ }
+
+ public class CDenom
+ {
+ public int mCurrenyIndex;
+ public string currency;
+ public int issue;
+ public double mDenomValue;
+ }
+}
\ No newline at end of file
diff --git a/.svn/pristine/a2/a26939ed19dd5bf21ca25f3ca6aaee94e1f293bc.svn-base b/.svn/pristine/a2/a26939ed19dd5bf21ca25f3ca6aaee94e1f293bc.svn-base
new file mode 100644
index 0000000..b5e63d9
Binary files /dev/null and b/.svn/pristine/a2/a26939ed19dd5bf21ca25f3ca6aaee94e1f293bc.svn-base differ
diff --git a/.svn/pristine/a2/a27c17c69ab7edbbb974fcb07f88fae76875aac8.svn-base b/.svn/pristine/a2/a27c17c69ab7edbbb974fcb07f88fae76875aac8.svn-base
new file mode 100644
index 0000000..73ba0fc
--- /dev/null
+++ b/.svn/pristine/a2/a27c17c69ab7edbbb974fcb07f88fae76875aac8.svn-base
@@ -0,0 +1,27 @@
+
+
+
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+ Designer
+
+
+
\ No newline at end of file
diff --git a/.svn/pristine/a2/a27e1d910830a9f9fa6276a7e6f6e385437ea169.svn-base b/.svn/pristine/a2/a27e1d910830a9f9fa6276a7e6f6e385437ea169.svn-base
new file mode 100644
index 0000000..448abd1
--- /dev/null
+++ b/.svn/pristine/a2/a27e1d910830a9f9fa6276a7e6f6e385437ea169.svn-base
@@ -0,0 +1,76 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+
+ //public class CountSession
+ //{
+ // public int[] QuantityDenomi { get; set; }
+ // public int[] SumDenomi { get; set; }
+
+ //}
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ private WelcomeUC _welcomeUC;
+ private DepositUC _depositUC;
+ private CollectionUC _collectionUC;
+ private InformationUC _informationUC;
+ private ErrorUC _errorUC;
+ public MainWindow()
+ {
+ InitializeComponent();
+ AppData.Init();
+ ShowWelcomeScreen();
+ }
+ public void ShowInformationScreen(string strInfor)
+ {
+ if (_informationUC == null) _informationUC = new InformationUC();
+ _informationUC.ShowInfor(strInfor);
+ MainContentControl.Content = _informationUC;
+ }
+ public void ShowErrorScreen(string strError)
+ {
+ if (_errorUC == null) _errorUC = new ErrorUC();
+ _errorUC.ShowInfor(strError);
+ MainContentControl.Content = _errorUC;
+ }
+ public void ShowWelcomeScreen()
+ {
+ if(_welcomeUC==null) _welcomeUC = new WelcomeUC();
+ MainContentControl.Content = _welcomeUC;
+ }
+ public void ShowDepositScreen()
+ {
+ if (_depositUC == null) _depositUC = new DepositUC();
+ MainContentControl.Content = _depositUC;
+ }
+ public void ShowCollectionScreen()
+ {
+ if (_collectionUC == null) _collectionUC = new CollectionUC();
+ MainContentControl.Content = _collectionUC;
+ }
+ }
+}
diff --git a/.svn/pristine/a4/a4964c9058ed2e4d14d7d6ec1e650197a2813027.svn-base b/.svn/pristine/a4/a4964c9058ed2e4d14d7d6ec1e650197a2813027.svn-base
new file mode 100644
index 0000000..f22488d
--- /dev/null
+++ b/.svn/pristine/a4/a4964c9058ed2e4d14d7d6ec1e650197a2813027.svn-base
@@ -0,0 +1,82 @@
+using DE70_CMDv2;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for CollectionUC.xaml
+ ///
+ public partial class CollectionUC : UserControl
+ {
+ public CollectionUC()
+ {
+ InitializeComponent();
+ }
+ public void Init()
+ {
+ lblStatus.Text = "TRẠNG THÁI: BỘ ĐẾM ĐẦY";
+ }
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ if(AppData.cCmdRsp!=null)
+ {
+ CCmdRsp cCmdRsp = AppData.cCmdRsp;
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ lblStatus.Text="TRẠNG THÁI: KHỞI TẠO BỘ ĐẾM THÀNH CÔNG";
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+
+ }
+ }
+
+ }
+
+ private void btnCancel_Click(object sender, RoutedEventArgs e)
+ {
+ if(AppData.cCmdRsp!=null)
+ AppData.cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+ }
+ }
+
+}
diff --git a/.svn/pristine/a5/a5d54292da01ac46c14be530d41aa98b4f6b6480.svn-base b/.svn/pristine/a5/a5d54292da01ac46c14be530d41aa98b4f6b6480.svn-base
new file mode 100644
index 0000000..56f3821
--- /dev/null
+++ b/.svn/pristine/a5/a5d54292da01ac46c14be530d41aa98b4f6b6480.svn-base
@@ -0,0 +1,129 @@
+using Custom.CuCustomWndAPI;
+using Microsoft.Extensions.Configuration;
+using Newtonsoft.Json;
+using SafeBagDE70.Admin;
+using SafeBagDE70.Model;
+using SafeBagDE70.StateMachine;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Configuration;
+using System.Data;
+using System.IO;
+using System.Linq;
+using System.Reflection;
+using System.Threading;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Forms;
+using VirtualKeyboard.Wpf;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for App.xaml
+ ///
+ public partial class App : System.Windows.Application
+ {
+ public static StateMachineConfig StateMachineConfig { get; private set; }
+ private static Mutex mutex;
+ public App()
+ {
+ }
+ protected override void OnStartup(StartupEventArgs e)
+ {
+ base.OnStartup(e);
+
+ CheckInstance();
+ LoadConfig();
+ LoadDualScreens();
+ }
+ private static void CheckInstance()
+ {
+ bool isNewInstance;
+ string mutexName = "9f5b55c9-c6eb-443a-8e28-027defa46fb5";
+
+ mutex = new Mutex(true, mutexName, out isNewInstance);
+
+ if (!isNewInstance)
+ {
+ // If an instance is already running, exit the application
+ System.Windows.MessageBox.Show("Ứng dụng đã khởi chạy");
+ System.Windows.Application.Current.Shutdown();
+ return;
+ }
+ }
+ private static void LoadConfig()
+ {
+ try
+ {
+ AppData.CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version;
+ VKeyboard.Listen(e => e.Text);
+ var configuration = new ConfigurationBuilder()
+ .AddJsonFile("appsettings.json")
+ .Build();
+ Log.Logger = new LoggerConfiguration()
+ .ReadFrom.Configuration(configuration)
+ .WriteTo.Sink(new RealTimeLogSink())
+ .CreateLogger();
+ AppData.CDMPort = configuration["SerialPort:CDMPort"];
+ AppData.SensorPort = configuration["SerialPort:SensorPort"];
+ StateMachineConfig = new StateMachineConfig();
+ configuration.GetSection("StateMachine").Bind(StateMachineConfig);
+ Log.Information("START APP");
+ }
+ catch (Exception ex)
+ {
+ System.Windows.MessageBox.Show(ex.Message);
+ }
+ }
+ private void LoadDualScreens()
+ {
+ try
+ {
+ // Create instances of the windows you want to open
+ var mainWindow = new MainWindow();
+
+ // Show both windows
+ mainWindow.Show();
+
+ // Get all available screens
+ var screens = Screen.AllScreens;
+
+ // Open the Main Window on the primary screen
+ var primaryScreen = screens.FirstOrDefault(s => s.Primary) ?? screens.First();
+ PositionWindowOnScreen(mainWindow, primaryScreen);
+ mainWindow.Show();
+
+ // Open the Secondary Window on the secondary screen, if available
+ if (screens.Length > 1)
+ {
+ var adminWindow = new AdminWindow(); // Replace this with your actual window class
+ adminWindow.Show();
+ var secondaryScreen = screens.First(s => !s.Primary);
+ PositionWindowOnScreen(adminWindow, secondaryScreen);
+ adminWindow.Show();
+ }
+ }catch (Exception ex)
+ {
+ Log.Fatal(ex,"START APP");
+ }
+
+ }
+
+ private void PositionWindowOnScreen(Window window, Screen screen)
+ {
+ // Convert screen bounds to WPF units (96 DPI)
+ var screenLeft = screen.WorkingArea.Left / (double)Screen.PrimaryScreen.WorkingArea.Width * SystemParameters.PrimaryScreenWidth;
+ var screenTop = screen.WorkingArea.Top / (double)Screen.PrimaryScreen.WorkingArea.Height * SystemParameters.PrimaryScreenHeight;
+
+ // Set window position and state
+ window.WindowStartupLocation = WindowStartupLocation.Manual;
+ window.Left = screenLeft;
+ window.Top = screenTop;
+ window.Width = screen.WorkingArea.Width;
+ window.Height = screen.WorkingArea.Height;
+ }
+ }
+}
diff --git a/.svn/pristine/a6/a6c338e54a17ad62ad5857cbadfb818bbd4dbdde.svn-base b/.svn/pristine/a6/a6c338e54a17ad62ad5857cbadfb818bbd4dbdde.svn-base
new file mode 100644
index 0000000..df3d8f7
--- /dev/null
+++ b/.svn/pristine/a6/a6c338e54a17ad62ad5857cbadfb818bbd4dbdde.svn-base
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70.StateMachine
+{
+ public class ActionWithFlag
+ {
+ public string Name { get; set; }
+ public bool IsRequired { get; set; }
+ }
+}
diff --git a/.svn/pristine/a8/a83ad665c9d1241c5d086006d22616adf996205d.svn-base b/.svn/pristine/a8/a83ad665c9d1241c5d086006d22616adf996205d.svn-base
new file mode 100644
index 0000000..84d8ef1
--- /dev/null
+++ b/.svn/pristine/a8/a83ad665c9d1241c5d086006d22616adf996205d.svn-base
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/a8/a8ec9706620f42e408a88f345a7c0215d20d6db1.svn-base b/.svn/pristine/a8/a8ec9706620f42e408a88f345a7c0215d20d6db1.svn-base
new file mode 100644
index 0000000..540e269
Binary files /dev/null and b/.svn/pristine/a8/a8ec9706620f42e408a88f345a7c0215d20d6db1.svn-base differ
diff --git a/.svn/pristine/a9/a9238a038b2c31d906823520723915267c2a0d32.svn-base b/.svn/pristine/a9/a9238a038b2c31d906823520723915267c2a0d32.svn-base
new file mode 100644
index 0000000..4728ef7
--- /dev/null
+++ b/.svn/pristine/a9/a9238a038b2c31d906823520723915267c2a0d32.svn-base
@@ -0,0 +1,40 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace SafeBagDE70.Services
+{
+ internal class WarningSoundManager2
+ {
+ private static bool _isWarningActive = false;
+ private static Thread _warningSoundThread;
+
+ public static void StartWarningSound()
+ {
+ if (!_isWarningActive)
+ {
+ _isWarningActive = true;
+ _warningSoundThread = new Thread(PlayWarningSound);
+ _warningSoundThread.IsBackground = true; // Ensure the thread stops when the application exits
+ _warningSoundThread.Start();
+ }
+ }
+
+ public static void StopWarningSound()
+ {
+ _isWarningActive = false;
+ }
+
+ private static void PlayWarningSound()
+ {
+ while (_isWarningActive)
+ {
+ Console.Beep(1200, 500); // Frequency: 1200 Hz, Duration: 500 ms
+ Thread.Sleep(500); // Pause for 500 ms before repeating for 100ms
+ }
+ }
+ }
+}
diff --git a/.svn/pristine/aa/aa1112bb0381e1ba1a67488992485cbd41e9a7b4.svn-base b/.svn/pristine/aa/aa1112bb0381e1ba1a67488992485cbd41e9a7b4.svn-base
new file mode 100644
index 0000000..b074cf1
--- /dev/null
+++ b/.svn/pristine/aa/aa1112bb0381e1ba1a67488992485cbd41e9a7b4.svn-base
@@ -0,0 +1,184 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using SafeBagDE70.Services;
+
+namespace SafeBagDE70
+{
+ ///
+ /// Interaction logic for MainWindow.xaml
+ ///
+ ///
+ public partial class MainWindow : HandyControl.Controls.Window
+ {
+ private WelcomeUC _welcomeUC;
+ private DepositSMUCv2 _depositUC;
+ private CollectionUC _collectionUC;
+ private InformationUC _informationUC;
+ private ErrorUC _errorUC;
+ private UserControl _currentUC;
+ private UserControl _prevUC;
+ private TimeoutUC _timeoutUC;
+ private MaintainanceUC _maintainanceUC;
+ private EndSessionUC _endSessionUC;
+ private object objLock = new object();
+ public MainWindow()
+ {
+ InitializeComponent();
+ Loaded += MainWindow_Loaded;
+ }
+
+ private void MainWindow_Loaded(object sender, RoutedEventArgs e)
+ {
+ AppData.Init();
+ if (_welcomeUC == null) _welcomeUC = new WelcomeUC();
+ if (_collectionUC == null) _collectionUC = new CollectionUC();
+ if (_informationUC == null) _informationUC = new InformationUC();
+ if (_errorUC == null) _errorUC = new ErrorUC();
+ if (_depositUC == null) _depositUC = new DepositSMUCv2();
+ if (_timeoutUC == null) _timeoutUC = new TimeoutUC();
+ if (_maintainanceUC == null) _maintainanceUC = new MaintainanceUC();
+ if (_endSessionUC == null) _endSessionUC = new EndSessionUC();
+
+
+ gridMain.Children.Add(_welcomeUC);
+ gridMain.Children.Add(_depositUC);
+ gridMain.Children.Add(_collectionUC);
+ gridMain.Children.Add(_informationUC);
+ gridMain.Children.Add(_errorUC);
+ gridMain.Children.Add(_timeoutUC);
+ gridMain.Children.Add(_maintainanceUC);
+ gridMain.Children.Add(_endSessionUC);
+
+ ShowWelcomeScreen();
+ //ShowDepositScreen();
+ }
+
+ public void HideAll()
+ {
+ lock(objLock)
+ {
+ foreach (var item in gridMain.Children)
+ {
+ if (item != null)
+ (item as UserControl).Visibility = Visibility.Hidden;
+ }
+ //_collectionUC.Visibility = Visibility.Hidden;
+ //_informationUC.Visibility = Visibility.Hidden;
+ //_errorUC.Visibility = Visibility.Hidden;
+ //_depositUC.Visibility = Visibility.Hidden;
+ //_welcomeUC.Visibility = Visibility.Hidden;
+ //_maintainanceUC.Visibility=Visibility.Hidden;
+ //_endSessionUC.Visibility = Visibility.Hidden;
+ SoundManager.StopWarningSound();
+ }
+
+ }
+ public void ShowEndSessionScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _endSessionUC.Visibility= Visibility.Visible;
+ }
+ public void ShowInformationScreen(string strInfor,bool bContinue=false,bool bPlaySound=true,List lstControls=null)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _informationUC;
+ HideAll();
+ _informationUC.Visibility = Visibility.Visible;
+ _informationUC.ShowInfor(strInfor, bContinue, bPlaySound,lstControls);
+ }
+ public void ShowErrorScreen(string strError)
+ {
+ _prevUC = _currentUC;
+ _currentUC = _errorUC;
+ HideAll();
+ _errorUC.Visibility = Visibility.Visible;
+ _errorUC.ShowInfor(strError);
+ }
+ public void ShowWelcomeScreen()
+ {
+ _depositUC.StopTimers();
+ _depositUC.StopWelcomeTimer();
+ _prevUC = _currentUC;
+ _currentUC = _welcomeUC;
+ HideAll();
+ _welcomeUC.Init();
+
+ _welcomeUC.Visibility = Visibility.Visible;
+ }
+ public void ShowDepositScreen(bool bInit=true)
+ {
+ _depositUC.ResetTimers();
+ _prevUC = _currentUC;
+ _currentUC = _depositUC;
+ HideAll();
+ _depositUC.Visibility = Visibility.Visible;
+ if(bInit)
+ {
+ _depositUC.EndTransaction();
+ _depositUC.InitTransaction();
+ }
+ }
+
+ public void ShowCollectionScreen()
+ {
+ _prevUC = _currentUC;
+ _currentUC = _collectionUC;
+ HideAll();
+ _collectionUC.Init();
+ _collectionUC.Visibility = Visibility.Visible;
+ }
+ public bool IsMaintainanceScreen()
+ {
+ return _currentUC == _maintainanceUC;
+ }
+ public DepositSMUCv2 GetDepositScreen()
+ {
+ return _depositUC;
+ }
+ public void ShowMaintainanceScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _maintainanceUC.Visibility = Visibility.Visible;
+ }
+ public void ShowTimeoutScreen()
+ {
+ _prevUC = _currentUC;
+ HideAll();
+ _timeoutUC.Visibility = Visibility.Visible;
+ }
+ public void StopTimers()
+ {
+ _depositUC.StopTimers();
+ }
+ public void ResetTimers()
+ {
+ _depositUC.ResetTimers();
+ }
+ public void BackScreen()
+ {
+ HideAll();
+ _prevUC.Visibility = Visibility.Visible;
+ _currentUC = _prevUC;
+ }
+ }
+}
diff --git a/.svn/pristine/ab/ab11c7a66808fd352a5daf62be17d7c12d00ba9e.svn-base b/.svn/pristine/ab/ab11c7a66808fd352a5daf62be17d7c12d00ba9e.svn-base
new file mode 100644
index 0000000..59b5ec9
--- /dev/null
+++ b/.svn/pristine/ab/ab11c7a66808fd352a5daf62be17d7c12d00ba9e.svn-base
@@ -0,0 +1,83 @@
+
+
+
+ WinExe
+ net8.0-windows7.0
+ enable
+ true
+ icon\logo.ico
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ tlbimp
+ 0
+ 1
+ db07b9fc-18b0-4b55-9a44-31d2c2f87875
+ 0
+ false
+ False
+
+
+
+
+
+ Always
+
+
+ PreserveNewest
+
+
+ PreserveNewest
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+ Code
+
+
+
+
diff --git a/.svn/pristine/ac/acc4a87e5248dd467029254d912f9c4c06673d23.svn-base b/.svn/pristine/ac/acc4a87e5248dd467029254d912f9c4c06673d23.svn-base
new file mode 100644
index 0000000..4b98cff
--- /dev/null
+++ b/.svn/pristine/ac/acc4a87e5248dd467029254d912f9c4c06673d23.svn-base
@@ -0,0 +1,863 @@
+using System;
+using System.Collections.Generic;
+using System.IO.Ports;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Channels;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Input;
+using System.Windows.Media;
+using System.Windows.Media.Imaging;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Xml.Serialization;
+using System.Windows.Threading;
+using System.Diagnostics;
+using System.Collections.ObjectModel;
+using SafeBagDE70.Model;
+using HandyControl.Tools;
+using System.Drawing.Printing;
+using System.Drawing;
+using static HandyControl.Tools.Interop.InteropValues;
+using SafeBagDE70.API;
+using Newtonsoft.Json;
+using System.IO;
+using System.Reflection;
+using DE70_CMDv2;
+using System.Configuration;
+
+
+namespace SafeBagDE70
+{ //Summary
+
+
+ public partial class DepositUC : UserControl
+ {
+ SerialPort serialPortDE70 = new SerialPort();
+ SerialPort serialPortSensor= new SerialPort();
+
+ List sessions = new List();
+ ObservableCollection lvCountItems = new ObservableCollection();
+ private DispatcherTimer timer;
+ private DispatcherTimer sensorTimer;
+
+ int countTimer = 0;
+ CCmdRsp cCmdRsp = null;
+ bool bInitialized = false;
+
+
+ public DepositUC()
+ {
+ InitializeComponent();
+
+ }
+
+ private void UserControl_Loaded(object sender, RoutedEventArgs e)
+ {
+ InitTransaction();
+
+ }
+ public void InitTransaction()
+ {
+ try
+ {
+ if (AppData.IsAuthenticated)
+ {
+ lblUser.Content = $"Xin chào khách hàng: {AppData.CurrentCustomerAccount.Name} (Gian hàng {AppData.CurrentCustomerAccount.CustomerId})";
+ }
+
+ // LoginUsingQRCode();
+ if (serialPortDE70.IsOpen) serialPortDE70.Close();
+ if (serialPortSensor.IsOpen) serialPortSensor.Close();
+
+ serialPortDE70.ReadBufferSize = 4096;
+ serialPortDE70.WriteBufferSize = 4096;
+ cCmdRsp = new CCmdRsp(serialPortDE70);
+ AppData.cCmdRsp = cCmdRsp;
+
+ serialPortDE70.PortName = "COM4";
+ serialPortDE70.BaudRate = 9600;
+ serialPortDE70.Parity = Parity.Even;
+ serialPortDE70.DataBits = 8;
+ serialPortDE70.StopBits = StopBits.One;
+ serialPortDE70.ReadTimeout = 5000;
+ serialPortDE70.WriteTimeout = 5000;
+
+ serialPortSensor.PortName = "COM3";
+ serialPortSensor.BaudRate = 9600;
+ serialPortSensor.Parity = Parity.None;
+ serialPortSensor.DataBits = 8;
+ serialPortSensor.StopBits = StopBits.One;
+ serialPortSensor.ReadTimeout = 5000;
+ serialPortSensor.WriteTimeout = 5000;
+
+
+ //Subscrible to the DataReveied event
+ if (!serialPortDE70.IsOpen)
+ serialPortDE70.Open();
+
+ if (!serialPortSensor.IsOpen)
+ serialPortSensor.Open();
+
+ bInitialized = InitSession();
+
+ timer = new DispatcherTimer();
+ timer.Interval = new TimeSpan(0, 0, 10); //10 seconds
+ timer.Tick += Timer_Tick;
+ timer.Start();
+
+ sensorTimer = new DispatcherTimer();
+ sensorTimer.Interval = new TimeSpan(0, 0, 1); //1 seconds
+ sensorTimer.Tick += SensorTimer_Tick;
+ sensorTimer.Start();
+
+ }
+ catch (Exception ex)
+ {
+ ShowError("LỖI CỔNG KẾT NỐI, VUI LÒNG KIỂM TRA LẠI CỔNG KẾT NỐI");
+ }
+
+ }
+
+ public void EndTransaction()
+ {
+ try
+ {
+ AppData.IsInTransaction = false;
+ if (timer != null)
+ {
+ timer.Tick -= Timer_Tick;
+ timer.Stop();
+ }
+ if (sensorTimer != null)
+ {
+ sensorTimer.Tick -= SensorTimer_Tick;
+ sensorTimer.Stop();
+ }
+ }
+ catch (Exception ex)
+ {
+ }
+ }
+ public void SetStep(int step)
+ {
+ switch(step)
+ {
+ case 0:
+ btnStart.IsEnabled = true;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = false;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled = false;
+ break;
+ case 1:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = false;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = false;
+ btnEnd.IsEnabled =false;
+ break;
+ case 2:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = false;
+ break;
+ case 3:
+ btnStart.IsEnabled = false;
+ btnCheck.IsEnabled = true;
+ btnCountStart.IsEnabled = true;
+ btnStoreStart.IsEnabled = true;
+ btnEnd.IsEnabled = true;
+ break;
+ }
+ }
+
+ public void InitSessionCount()
+ {
+ if (lvCount.Items.Count == 11) {
+ foreach(var item in lvCountItems)
+ {
+ item.Quantity = "0";
+ }
+ }
+ else
+ {
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "1000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "2000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "5000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "10000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "20000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "50000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "100000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "200000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "500000",
+ Quantity = "0"
+ });
+ lvCountItems.Add(new LvCountItem
+ {
+ Name = "Tổng",
+ Quantity = "0"
+ });
+ lvCountItems[10].Quantity = "0";
+ lvCountItems[10].Value = "0";
+ }
+
+
+ lvCount.ItemsSource = lvCountItems;
+
+ //lvCountItems[0].Quantity = "10";
+ }
+ public long maxQuantitySheet = 10000;
+ public int quantityStored = 0;
+ public int totalAllDenominations = 0;
+ public int posDenomi;
+ public bool printerFlag = false;
+ public static string? recvDataString;
+ public int[] TempQuantity = new int[10] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ public int[] TempNote = new int[5] { 0, 0, 0, 0, 0 };
+ public int[] Notes = new int[5] { 0, 0, 0, 0, 0 };
+
+ private void SensorTimer_Tick(object? sender, EventArgs e)
+ {
+ try
+ {
+ timer.IsEnabled = false;
+ GetSensorValue();
+ if (AppData.IsInTransaction)
+ {
+ if (AppData.WDTCount == 15)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowTimeoutScreen();
+ }
+ else if (AppData.WDTCount == 30)
+ {
+ //Nhận tiền và Kết thúc
+ StoreStart();
+ EndSession();
+
+ ((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ }
+ AppData.WDTCount++;
+ }
+ else
+ {
+ AppData.WDTCount = 0;
+ }
+ timer.IsEnabled = true;
+ }
+ catch (Exception)
+ {
+
+ }
+
+
+ }
+
+ private void GetSensorValue()
+ {
+ try
+ {
+
+ int state = 0;
+ if (serialPortSensor.IsOpen == true)
+ {
+ serialPortSensor.Write(new byte[] { (byte)'S', 13, 10 }, 0, 3);
+ var buffer = new byte[16];
+
+ int n = serialPortSensor.Read(buffer, 0, buffer.Length);
+
+ for (int i = 1; i < n - 1; i++)
+ {
+ if ((buffer[i] == 13) && (buffer[i + 1] == 10))
+ {
+ state = buffer[i - 1] - 48;
+ if (bInitialized)
+ {
+ if (state != 0)
+ gridMain.IsEnabled = false;
+ else
+ gridMain.IsEnabled = true;
+ }
+ switch (state)
+ {
+ case 0:
+ lblStatus.Content = "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Ở";
+ break;
+ case 2:
+ lblStatus.Content = "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Ở";
+ break;
+ }
+ break;
+ }
+ }
+
+ }
+ }
+ catch (Exception ex)
+ {
+ serialPortDE70.Close();
+ serialPortDE70.Open();
+ }
+ }
+
+ private void Timer_Tick(object? sender, EventArgs e)
+ {
+ timer.IsEnabled = false;
+
+ APIModels.SendHealthCheck();
+
+ timer.IsEnabled = true;
+ }
+ public int UpdateTotalQuantity()
+ {
+ int total = 0;
+ foreach (var item in lvCountItems)
+ {
+ if (item.Name != "Tổng")
+ {
+ int quantity = 0;
+ if (int.TryParse(item.Quantity, out quantity))
+ {
+ total += quantity;
+ }
+ }
+ }
+ return total;
+ }
+
+ public int AutoSerialGet(SerialPort serialPort)
+ {
+ int ret;
+ ushort seri_num = 0;
+ ushort get_num = 0;
+ bool endflg = false;
+
+ while (true)
+ {
+ ret = cCmdRsp.SendSerialSense();
+ if (ret == Constants.E_OK)
+ {
+ ret = cCmdRsp.GetSerialNum(out seri_num);
+ if (ret == Constants.E_OK)
+ {
+ // Serial number acquisition
+
+ if (cCmdRsp.ChkCntEnd())
+ {
+ endflg = true;
+ Debug.WriteLine("END FLAG: "+cCmdRsp.recv_dat.dat[1]);
+ }
+ Debug.WriteLine("START");
+ Debug.WriteLine($"Num Serial: {seri_num}");
+
+ while (get_num < seri_num)
+ {
+ get_num++;
+ ret = cCmdRsp.SendGetSerial(get_num);
+
+
+ switch (cCmdRsp.recv_dat.dat[18])
+ {
+ case 0x00: TempNote[0] ++; Notes[0] += TempNote[0]; break;
+ case 0x02:
+ //TempNote[1] ++;
+ switch (cCmdRsp.recv_dat.dat[17])
+ {
+ case 0x00: TempQuantity[0]++; break;
+ case 0x01: TempQuantity[1]++; break;
+ case 0x02: TempQuantity[2]++; break;
+ case 0x03: TempQuantity[3]++; break;
+ case 0x04: TempQuantity[4]++; break;
+ case 0x05: TempQuantity[5]++; break;
+ case 0x06: TempQuantity[6]++; break;
+ case 0x07: TempQuantity[7]++; break;
+ case 0x08: TempQuantity[8]++; break;
+ case 0x09: TempQuantity[9]++; break;
+
+ }
+ break;
+ case 0x03: TempNote[2] ++; Notes[2] += TempNote[2]; break;
+ case 0x0b: TempNote[3] ++; Notes[3] += TempNote[3]; break;
+ case 0x0c: TempNote[4] ++; Notes[4] += TempNote[4]; break;
+ }
+ }
+
+ Debug.WriteLine("END");
+ //Debug.WriteLine("Ellapsed Time: " + timeSpan.TotalSeconds);
+ if (endflg)
+ {
+
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END GET SERIAL: "+ret);
+ break;
+ }
+ }
+ else
+ {
+ Debug.WriteLine("END SEND SERIAL: "+ret);
+ break;
+ }
+ }
+ return 0;
+ }
+
+ public void btnCountStart_Click(object sender, RoutedEventArgs e)
+ {
+ CountStart();
+ AppData.WDTCount = 0;
+ }
+
+ private void CountStart()
+ {
+ printerFlag = false;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ try
+ {
+
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CNTSTART);
+ //var recvData = DE70_CMD.SendxxCmd((byte)CMD_BYTE.CMD_DE_CNTSTART, serialPort);
+
+ //Thread.Sleep(20000);
+ if (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[2] != 43) { }
+ do
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ cCmdRsp.SendXXCmd((byte)Command.CMD_SENSE);
+ }
+ while (cCmdRsp.recv_dat != null && cCmdRsp.recv_dat.dat[1] == 0x09); //SR2 = 0x09 : Counting Status
+
+ //SR3 = 0x43 : Stacker full
+
+ AutoSerialGet(serialPortDE70);
+
+ if (sessions == null || sessions.Count == 0)
+ {
+ double tempSum = 0;
+ for (int i = 0; i < 10; i++)
+ {
+ lvCountItems[i].Quantity = TempQuantity[9 - i].ToString();
+ tempSum += lvCountItems[i].getValue();
+ }
+
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = tempSum.ToString();
+
+ }
+ else
+ {
+ InitSessionCount();
+ double sum = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+
+ }
+
+ a += TempQuantity[9 - i];
+
+ lvCountItems[i].Quantity = a.ToString();
+ sum += lvCountItems[i].getValue();
+
+ }
+ //Update amount of money
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sum.ToString();
+
+ }
+ SetStep(2);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnCheck_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_CANCEL);
+
+ double sumStored;
+
+ //TempNote[1] = 0;
+
+ if (sessions != null)
+ {
+ sumStored = 0;
+
+ for (int i = 0; i < 10; i++)
+ {
+ int a = 0;
+ for (int j = 0; j < sessions.Count; j++)
+ {
+
+ a += sessions[j].QuantityDenomi[9 - i];
+ //quantityStored += lvCountItems[i].getQuantity();
+ }
+ lvCountItems[i].Quantity = a.ToString();
+ sumStored += lvCountItems[i].getValue();
+ }
+ lvCountItems[10].Quantity = UpdateTotalQuantity().ToString();
+ lvCountItems[10].Value = sumStored.ToString();
+ }
+ else
+ {
+ InitSessionCount();
+ }
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ AppData.WDTCount = 0;
+ }
+ private void btnStoreStart_Click(object sender, RoutedEventArgs e)
+ {
+ StoreStart();
+ AppData.WDTCount = 0;
+ }
+
+ private void StoreStart()
+ {
+ printerFlag = true;
+
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+ LogAction(currentMethod, null);
+ sessions.Add(new CountSession());
+
+ sessions[sessions.Count - 1].QuantityDenomi = (int[])TempQuantity.Clone();
+ quantityStored = UpdateTotalQuantity();
+
+ Debug.WriteLine(quantityStored);
+
+ Array.Clear(TempQuantity, 0, TempQuantity.Length);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_STORESTART);
+ SetStep(3);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ }
+
+ private void btnStart_Click(object sender, RoutedEventArgs e)
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ InitSession();
+ AppData.IsInTransaction= true;
+ try
+ {
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ LogAction(currentMethod, null);
+
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_SENSE);
+
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+ SetStep(1);
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+ AppData.WDTCount = 0;
+ }
+
+ private void btnEnd_Click(object sender, RoutedEventArgs e)
+ {
+ AppData.IsInTransaction = false;
+ AppData.WDTCount = 0;
+ EndSession();
+ }
+
+ private void EndSession()
+ {
+ string currentMethod = MethodBase.GetCurrentMethod().Name;
+ var totalQuantity = lvCountItems[10].Quantity;
+ var totalValue = lvCountItems[10].Value;
+ try
+ {
+ LogAction(currentMethod, null);
+ serialPortDE70.DiscardInBuffer();
+ serialPortDE70.DiscardOutBuffer();
+
+ //SendData2Server
+ var data2Send = new CountingData2Send
+ {
+ Sessions = sessions,
+ MachineId = null,
+ UserId = AppData.CurrentCustomerAccount.CustomerId,
+ MachineTime = DateTime.Now.ToString("yyyyMMddHHmmss"),
+ RejectNotes = Notes[0],
+ GenuineNotes = quantityStored,
+ UnfitNotes = Notes[2],
+ CounterfeitNotes = Notes[3],
+ SuspendNotes = Notes[4]
+
+ };
+ var str = JsonConvert.SerializeObject(data2Send);
+
+ APIModels.SendCountingData(data2Send);
+ //Reset all and ready to next session
+
+ if (printerFlag == true)
+ {
+ PrintReceipt();
+ printerFlag = false;
+
+ }
+ InitSession();
+ //Debug.WriteLine("Reject Note: " + Notes[0] );
+ //Debug.WriteLine("Genuine note stored: " + quantityStored);
+ //Debug.WriteLine("Unfit note: " + Notes[2]);
+ //Debug.WriteLine("Counterfeit: " + Notes[3]);
+ //Debug.WriteLine("Suspend: " + Notes[4]);
+
+ }
+ catch (Exception ex)
+ {
+ LogException(currentMethod, ex.ToString());
+ }
+
+
+ String strNotify = $"BẠN VỪA THỰC HIỆN TIỀN VÀO MÁY CDM:\r\n"
+ + $"SỐ LƯỢNG TỜ: {totalQuantity}\r\n"
+ + $"SỐ TIỀN: {totalValue} VND\r\n";
+
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen(strNotify);
+ }
+
+ private void ShowError(string strError)
+ {
+ //gridMain.IsEnabled = false;
+ //btnCollect2.Visibility=Visibility.Collapsed;
+ //panelError.Visibility = Visibility.Visible;
+ //lblError.Text = strError;
+ //((MainWindow)Application.Current.MainWindow).ShowWelcomeScreen();
+ ((MainWindow)Application.Current.MainWindow).ShowErrorScreen(strError);
+ }
+
+ private bool InitSession()
+ {
+ try
+ {
+ //Check status
+ cCmdRsp.SendDeSense();
+ var data = cCmdRsp.recv_dat.dat;
+ int IsCassetteFull = 0;
+ int IsNotesInEscrow = 0;
+ IsCassetteFull = data[17] & 0x08;
+ IsNotesInEscrow = data[4] & 0x01;
+
+ if (IsCassetteFull != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowCollectionScreen();
+ return false;
+ }
+ else if (IsNotesInEscrow != 0)
+ {
+ ((MainWindow)Application.Current.MainWindow).ShowInformationScreen("ĐỀ NGHỊ BỎ TIỀN TRONG NGĂN PHỤ ĐỂ TIẾP TỤC");
+ }
+ else
+ {
+ InitSessionCount();
+ sessions.Clear();
+ Array.Clear(TempNote, 0, TempNote.Length);
+ Array.Clear(Notes, 0, Notes.Length);
+ quantityStored = 0;
+ maxQuantitySheet = 0;
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ SetStep(0);
+ return true;
+ }
+
+ }
+ catch(Exception ex)
+ {
+ LogException("InitSession", ex.ToString());
+ }
+ return false;
+ }
+
+ private void PrintReceipt()
+ {
+ var shopName = AppData.CurrentCustomerAccount.Name;
+ var shopCode = AppData.CurrentCustomerAccount.CustomerId;
+ var tradingCode = "TRA04052024CDM";
+ var storeAccountNumber = 686868686688;
+ var currentTime = DateTime.Now;
+ var printDocument = new PrintDocument();
+ printDocument.PrinterSettings.PrinterName = "CUSTOM K80";
+ printDocument.PrintPage += (sender, e) =>
+ {
+ e.Graphics.DrawString("Biên nhận nộp tiền", new Font("Arial", 15), System.Drawing.Brushes.Black, new PointF(80, 10));
+ e.Graphics.DrawString("Mã máy CDM: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 60));
+ e.Graphics.DrawString("Batch no: ", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 90));
+ e.Graphics.DrawString("Thời gian GD: " + currentTime.ToString("dd/MM/yyyy HH:mm:ss"), new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 120));
+ e.Graphics.DrawString("Mã GD: " + tradingCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 150));
+ e.Graphics.DrawString("Mã gian hàng: " + shopCode, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 180));
+ e.Graphics.DrawString("Tên gian hàng: " + shopName, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 210));
+ e.Graphics.DrawString("STK gian hàng: " + storeAccountNumber, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 240));
+ e.Graphics.DrawString("Số tiền nộp: " + lvCountItems[10].Value, new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(50, 270));
+ e.Graphics.DrawString("*****Xin cám ơn******", new Font("Arial", 9), System.Drawing.Brushes.Black, new PointF(100, 300));
+ // To send raw ESC/POS commands, you'd typically use e.Graphics.DrawString() with the command string,
+ // or for more complex scenarios, directly manipulate the byte stream sent to the printer.
+ };
+ printDocument.Print();
+
+
+ }
+
+ public void LogAction(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("log.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ public void LogException(string strAction, string? strData)
+ {
+ if (strData != null) strData = "Data: " + strData;
+ File.AppendAllText("logException.txt", "\r\n" + DateTime.Now.ToString("yyyyMMddHHmmss: ") +
+ "Action: " + strAction + " " + strData);
+ }
+
+ private void btnCollect_Click(object sender, RoutedEventArgs e)
+ {
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ cCmdRsp.SendXXCmd((byte)Command.CMD_DE_UNLOCK);
+ Thread.Sleep(1000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ //Event fix
+ var recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] == recvData.dat[16])
+ {
+ cCmdRsp.SendLock();
+ }
+ else
+ {
+ cCmdRsp.SendEventFix(recvData.dat[16]);
+ cCmdRsp.SendLock();
+ }
+
+ var currentMode = cCmdRsp.GetLockParam().mode;
+ cCmdRsp.GetLockParam().mode = Mode.MODE_COLLECTION;
+ cCmdRsp.SendLock();
+ Thread.Sleep(10000);
+ cCmdRsp.SendDeSense();
+ Thread.Sleep(1000);
+ recvData = cCmdRsp.recv_dat;
+
+ if (recvData.dat[14] != recvData.dat[16])
+ {
+ ShowError("Khởi tạo bộ đếm thành công");
+ // ShutdownApp();
+ // InitApp();
+ }
+ AppData.WDTCount = 0;
+ }
+
+ private void UserControl_Unloaded(object sender, RoutedEventArgs e)
+ {
+ EndTransaction();
+ }
+ }
+}
+
diff --git a/.svn/pristine/ad/ad166b929fdc31a199436311032c622e3798fe9e.svn-base b/.svn/pristine/ad/ad166b929fdc31a199436311032c622e3798fe9e.svn-base
new file mode 100644
index 0000000..9340d16
--- /dev/null
+++ b/.svn/pristine/ad/ad166b929fdc31a199436311032c622e3798fe9e.svn-base
@@ -0,0 +1,20 @@
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/ae/ae3ba57016fea395a59f282eba16178acc394034.svn-base b/.svn/pristine/ae/ae3ba57016fea395a59f282eba16178acc394034.svn-base
new file mode 100644
index 0000000..0df715e
--- /dev/null
+++ b/.svn/pristine/ae/ae3ba57016fea395a59f282eba16178acc394034.svn-base
@@ -0,0 +1,124 @@
+using DE70_CMDv2;
+using SafeBagDE70.Model;
+using Serilog;
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Controls;
+
+namespace SafeBagDE70
+{
+ public static class AppData
+ {
+ public static string CDMPort = "COM4";
+ public static string SensorPort = "COM3";
+ public static Version? CurrentVersion = null;
+ public static List? customerAccounts = null;
+ public static CustomerAccount? CurrentCustomerAccount{get;set;}
+ public static CCmdRsp? cCmdRsp=null;
+ public static bool IsAuthenticated = false;
+ public static bool IsInTransaction = false;
+ public static int WDTCount = 0;
+ public static ObservableCollection logCollection = new ObservableCollection();
+ public static ListView logListView = null;
+ public static int MaxLogCount = 500;
+ public static void Init()
+ {
+
+ customerAccounts = new List{
+ new CustomerAccount{Name="NGUYỄN ĐÌNH THUẬN",CustomerId="HUE_0000000001",QRCode="HUE_0000000001",PINCode="H0001" },
+ new CustomerAccount{Name="HOÀNG VĂN HIỆP",CustomerId="HUE_0000000002",QRCode="HUE_0000000002",PINCode="H0002" },
+ new CustomerAccount{Name="PHẠM NGỌC HƯNG",CustomerId="HUE_0000000003",QRCode="HUE_0000000003",PINCode="H0003" },
+ new CustomerAccount{Name="AMHUE-ESTELLETEST",CustomerId="00DZAMHUE0004",QRCode="00DZAMHUE0004",PINCode="H0004" },
+ new CustomerAccount{Name="AMHUE-ECCOTEST",CustomerId="00DZAMHUE0005",QRCode="00DZAMHUE0005",PINCode="H0005" },
+ new CustomerAccount{Name="AMHUE-ALDOTEST",CustomerId="00DZAMHUE0006",QRCode="00DZAMHUE0006",PINCode="H0006" },
+ new CustomerAccount{Name="AMHUE-MLBTEST",CustomerId="00DZAMHUE0007",QRCode="00DZAMHUE0007",PINCode="H0007" },
+ new CustomerAccount{Name="AMHUE-PEDROTEST",CustomerId="00DZAMHUE0008",QRCode="00DZAMHUE0008",PINCode="H0008" }
+ };
+ CurrentCustomerAccount = customerAccounts[0];
+ }
+ private static DateTime CutOffTime = new DateTime(1, 1, 1, 12, 0, 0); // 12:00 noon as cut-off time
+
+ public static void GetNewTransactionCode()
+ {
+ DateTime transactionDateTime = DateTime.Now;
+ string merchantCode = CurrentCustomerAccount.CustomerId;
+
+ // Adjust transaction date if it's past cut-off time (12:00 noon)
+ DateTime prevadjustedDate = CurrentCustomerAccount.TransactionTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+
+ DateTime adjustedDate = transactionDateTime.Hour >= CutOffTime.Hour ? transactionDateTime.Date : transactionDateTime.Date.AddDays(-1);
+ if ((adjustedDate - prevadjustedDate).Days > 0)
+ {
+ CurrentCustomerAccount.TransactionCount =1;
+ }
+ else
+ {
+ CurrentCustomerAccount.TransactionCount++;
+ }
+ var transactionCount = CurrentCustomerAccount.TransactionCount;
+ string datePart = adjustedDate.ToString("yyyyMMdd");
+ string timePart = transactionDateTime.ToString("HHmmss");
+ string transactionCountPart = transactionCount.ToString("D2"); // Ensure 2 digits
+
+ // Combine all parts to form the transaction ID
+ string transactionId = $"{datePart}{timePart}{merchantCode}{transactionCountPart}";
+
+ CurrentCustomerAccount.TransactionCode = transactionId;
+ CurrentCustomerAccount.TransactionTime = transactionDateTime;
+ }
+
+ }
+ public class CustomerAccount
+ {
+ public string? Name { get; set; }
+ public string? CustomerId { get; set; }
+ public string? QRCode { get; set; }
+ public string? PINCode { get; set; }
+ public int TransactionCount { get; set; } = 1;
+ public DateTime TransactionTime { get; set; }
+ public string TransactionCode { get; set; }
+ }
+ public class CountSession
+ {
+ public CountSession()
+ {
+ for (int i = 0; i < QuantityDenomi.Count(); i++)
+ {
+ QuantityDenomi[i] = 0;
+ }
+ for (int i = 0; i < SumDenomi.Count(); i++)
+ {
+ SumDenomi[i] = 0;
+ }
+ for (int i = 0; i < TempNotes.Count(); i++)
+ {
+ TempNotes[i] = 0;
+ }
+ }
+
+ public int[] QuantityDenomi { get; set; } = new int[10];
+ public int[] SumDenomi { get; set; } = new int[10];
+ public bool IsStored = false;
+ public int[] TempNotes { get; set; } = new int[5];
+
+ }
+
+ public class CountingData2Send
+ {
+ public string? TransactionCode { get; set; }
+ public List? Sessions { get; set; }
+ public string? UserId { get; set; }
+ public string? MachineId { get; set; }
+ public string? MachineTime { get; set; }
+ public int RejectNotes { get; set; }
+ public int GenuineNotes { get; set; }
+ public int UnfitNotes { get; set; }
+ public int CounterfeitNotes { get; set; }
+ public int SuspendNotes { get; set; }
+ }
+}
diff --git a/.svn/pristine/af/afdd9a4dcc0b472cc0f55570683e707962e4ad43.svn-base b/.svn/pristine/af/afdd9a4dcc0b472cc0f55570683e707962e4ad43.svn-base
new file mode 100644
index 0000000..d6bbc54
--- /dev/null
+++ b/.svn/pristine/af/afdd9a4dcc0b472cc0f55570683e707962e4ad43.svn-base
@@ -0,0 +1,76 @@
+#pragma checksum "..\..\..\MainWindow.xaml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "7A83FBF0207447A23EB5D2C4E987D84562091419"
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+using System;
+using System.Diagnostics;
+using System.Windows;
+using System.Windows.Automation;
+using System.Windows.Controls;
+using System.Windows.Controls.Primitives;
+using System.Windows.Controls.Ribbon;
+using System.Windows.Data;
+using System.Windows.Documents;
+using System.Windows.Ink;
+using System.Windows.Input;
+using System.Windows.Markup;
+using System.Windows.Media;
+using System.Windows.Media.Animation;
+using System.Windows.Media.Effects;
+using System.Windows.Media.Imaging;
+using System.Windows.Media.Media3D;
+using System.Windows.Media.TextFormatting;
+using System.Windows.Navigation;
+using System.Windows.Shapes;
+using System.Windows.Shell;
+using VirtualKeyboard;
+
+
+namespace VirtualKeyboard {
+
+
+ ///
+ /// MainWindow
+ ///
+ public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {
+
+ private bool _contentLoaded;
+
+ ///
+ /// InitializeComponent
+ ///
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.2.0")]
+ public void InitializeComponent() {
+ if (_contentLoaded) {
+ return;
+ }
+ _contentLoaded = true;
+ System.Uri resourceLocater = new System.Uri("/VirtualKeyboard;V1.0.0.0;component/mainwindow.xaml", System.UriKind.Relative);
+
+ #line 1 "..\..\..\MainWindow.xaml"
+ System.Windows.Application.LoadComponent(this, resourceLocater);
+
+ #line default
+ #line hidden
+ }
+
+ [System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "8.0.2.0")]
+ [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
+ void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
+ this._contentLoaded = true;
+ }
+ }
+}
+
diff --git a/.svn/pristine/b0/b057dfdddaea20260a7c4ee678727e7dc7f8ccc6.svn-base b/.svn/pristine/b0/b057dfdddaea20260a7c4ee678727e7dc7f8ccc6.svn-base
new file mode 100644
index 0000000..ad2debf
--- /dev/null
+++ b/.svn/pristine/b0/b057dfdddaea20260a7c4ee678727e7dc7f8ccc6.svn-base
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/.svn/pristine/b1/b164e36553153fb26b6c310a5509ac034cdd9207.svn-base b/.svn/pristine/b1/b164e36553153fb26b6c310a5509ac034cdd9207.svn-base
new file mode 100644
index 0000000..679251d
--- /dev/null
+++ b/.svn/pristine/b1/b164e36553153fb26b6c310a5509ac034cdd9207.svn-base
@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Documents;
+
+namespace VirtualKeyboard.Wpf.Converters
+{
+ class UppercaseTypographyConverter : IValueConverter
+ {
+ public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ bool uppercase = (bool)value;
+ if (uppercase) return FontCapitals.AllSmallCaps;
+ else return FontCapitals.Normal;
+ }
+
+ public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
+ {
+ throw new NotImplementedException();
+ }
+ }
+}
diff --git a/.svn/pristine/b1/b16940df6482c1ba96c1c69731c586570d61b308.svn-base b/.svn/pristine/b1/b16940df6482c1ba96c1c69731c586570d61b308.svn-base
new file mode 100644
index 0000000..cffce40
--- /dev/null
+++ b/.svn/pristine/b1/b16940df6482c1ba96c1c69731c586570d61b308.svn-base
@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Input;
+
+namespace VirtualKeyboard.Wpf
+{
+ class Command : ICommand
+ {
+ public event EventHandler CanExecuteChanged;
+
+ private bool _canExecuteCommand = true;
+ public bool CanExecuteCommand
+ {
+ get => _canExecuteCommand;
+ set
+ {
+ _canExecuteCommand = value;
+ CanExecuteChanged?.Invoke(this, new EventArgs());
+ }
+ }
+
+ private readonly Action