Compare commits

..

No commits in common. "646449b4ba338a672768989e308c6ce123c83107" and "8778a976db20732190065a31a456c94e2447a042" have entirely different histories.

8 changed files with 64 additions and 130 deletions

View File

@ -22,24 +22,25 @@ namespace AIParkingApplication
private Config configOnWeb; private Config configOnWeb;
private EngineApiController engineApiController; private EngineApiController engineApiController;
private string doorAccessControlDeviceIP; private string doorAccessControlDeviceIP;
private Logger appLogger;
public AIParkingApplicationForm(ApiController apiController, string serverIPAddress, Config configOnWeb, Logger appLogger) private Logger applicationLogger;
public AIParkingApplicationForm(ApiController apiController, string serverIPAddress, Config configOnWeb)
{ {
InitializeComponent(); InitializeComponent();
this.apiController = apiController; this.apiController = apiController;
this.configOnWeb = configOnWeb; this.configOnWeb = configOnWeb;
this.appLogger = appLogger; applicationLogger = LogManager.GetLogger(AppConstant.APPLICATION_LOGGER_NAME);
ReadAccessControlDeviceIPConfigurationFile(); ReadAccessControlDeviceIPConfigurationFile();
if (string.IsNullOrEmpty(doorAccessControlDeviceIP) || !Util.IsValidIPAddress(doorAccessControlDeviceIP)) if (string.IsNullOrEmpty(doorAccessControlDeviceIP) || !Util.IsValidIPAddress(doorAccessControlDeviceIP))
{ {
appLogger.Log(LogLevel.Error, "Kiểm tra lại cấu hình IP thiết bị mở cửa!"); applicationLogger.Log(LogLevel.Error, "Kiểm tra lại cấu hình IP thiết bị mở cửa!");
MessageBox.Show("Kiểm tra lại cấu hình IP thiết bị mở cửa! (C3200)", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Kiểm tra lại cấu hình IP thiết bị mở cửa! (C3200)", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit(); Application.Exit();
} }
c3Device = new C3DeviceController(appLogger, doorAccessControlDeviceIP); c3Device = new C3DeviceController(doorAccessControlDeviceIP);
sidebar = new Sidebar(apiController) sidebar = new Sidebar(apiController)
{ {
Location = new Point(0, 0) Location = new Point(0, 0)
@ -57,9 +58,9 @@ namespace AIParkingApplication
{ {
engineApiController = new EngineApiController($"http://{this.configOnWeb.APIPath.ApiPlateRecognize.IP}:{this.configOnWeb.APIPath.ApiPlateRecognize.Port}"); engineApiController = new EngineApiController($"http://{this.configOnWeb.APIPath.ApiPlateRecognize.IP}:{this.configOnWeb.APIPath.ApiPlateRecognize.Port}");
} }
catch (Exception ex) catch (Exception)
{ {
appLogger.Log(LogLevel.Error, $"Cấu hình URL của Engine nhận diện biển số lỗi. exMessage: {ex.Message}"); applicationLogger.Log(LogLevel.Error, "Cấu hình URL của Engine nhận diện biển số lỗi!");
MessageBox.Show("Cấu hình API Plate Recognize lỗi!", "Cấu hình API Engine lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show("Cấu hình API Plate Recognize lỗi!", "Cấu hình API Engine lỗi!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return; return;
} }
@ -67,22 +68,22 @@ namespace AIParkingApplication
private void InitAllLanes() private void InitAllLanes()
{ {
laneIn12 = new LaneIn(10, configOnWeb.CameraData1.Id.ToString(), configOnWeb.CameraData1.StreamUrl, configOnWeb.CameraData2.StreamUrl, c3Device, apiController, engineApiController, appLogger, true, false, true); laneIn12 = new LaneIn(10, configOnWeb.CameraData1.Id.ToString(), configOnWeb.CameraData1.StreamUrl, configOnWeb.CameraData2.StreamUrl, c3Device, apiController, engineApiController, true, false, true);
laneIn12.BorderStyle = BorderStyle.FixedSingle; laneIn12.BorderStyle = BorderStyle.FixedSingle;
laneIn12.Hide(); laneIn12.Hide();
Controls.Add(laneIn12); Controls.Add(laneIn12);
laneOut34 = new LaneOut(20, configOnWeb.CameraData3.Id.ToString(), configOnWeb.CameraData3.StreamUrl, configOnWeb.CameraData4.StreamUrl, c3Device, apiController, engineApiController, appLogger, true, false, true); laneOut34 = new LaneOut(20, configOnWeb.CameraData3.Id.ToString(), configOnWeb.CameraData3.StreamUrl, configOnWeb.CameraData4.StreamUrl, c3Device, apiController, engineApiController, true, false, true);
laneOut34.BorderStyle = BorderStyle.FixedSingle; laneOut34.BorderStyle = BorderStyle.FixedSingle;
laneOut34.Hide(); laneOut34.Hide();
Controls.Add(laneOut34); Controls.Add(laneOut34);
laneIn56 = new LaneIn(10, configOnWeb.CameraData5.Id.ToString(), configOnWeb.CameraData5.StreamUrl, configOnWeb.CameraData6.StreamUrl, c3Device, apiController, engineApiController, appLogger, true, false, true); laneIn56 = new LaneIn(10, configOnWeb.CameraData5.Id.ToString(), configOnWeb.CameraData5.StreamUrl, configOnWeb.CameraData6.StreamUrl, c3Device, apiController, engineApiController, true, false, true);
laneIn56.BorderStyle = BorderStyle.FixedSingle; laneIn56.BorderStyle = BorderStyle.FixedSingle;
laneIn56.Hide(); laneIn56.Hide();
Controls.Add(laneIn56); Controls.Add(laneIn56);
laneOut78 = new LaneOut(20, configOnWeb.CameraData7.Id.ToString(), configOnWeb.CameraData7.StreamUrl, configOnWeb.CameraData8.StreamUrl, c3Device, apiController, engineApiController, appLogger, true, false, true); laneOut78 = new LaneOut(20, configOnWeb.CameraData7.Id.ToString(), configOnWeb.CameraData7.StreamUrl, configOnWeb.CameraData8.StreamUrl, c3Device, apiController, engineApiController, true, false, true);
laneOut78.BorderStyle = BorderStyle.FixedSingle; laneOut78.BorderStyle = BorderStyle.FixedSingle;
laneOut78.Hide(); laneOut78.Hide();
Controls.Add(laneOut78); Controls.Add(laneOut78);
@ -99,6 +100,8 @@ namespace AIParkingApplication
laneOut34.Location = new Point(laneIn12.Location.X + laneIn12.Width + 20, menuStrip.Height); laneOut34.Location = new Point(laneIn12.Location.X + laneIn12.Width + 20, menuStrip.Height);
laneOut34.Show(); laneOut34.Show();
laneOut34.Start(); laneOut34.Start();
toolStripMenuItemSwitchLaneInOut.DisableSelected();
} }
private void UpdateLaneInIn() private void UpdateLaneInIn()
@ -112,6 +115,8 @@ namespace AIParkingApplication
laneIn56.Location = new Point(laneIn12.Location.X + laneIn12.Width + 20, menuStrip.Height); laneIn56.Location = new Point(laneIn12.Location.X + laneIn12.Width + 20, menuStrip.Height);
laneIn56.Show(); laneIn56.Show();
laneIn56.Start(); laneIn56.Start();
toolStripMenuItemSwitchLaneInIn.DisableSelected();
} }
private void UpdateLaneOutIn() private void UpdateLaneOutIn()
@ -125,6 +130,8 @@ namespace AIParkingApplication
laneIn56.Location = new Point(laneOut78.Location.X + laneOut78.Width + 20, menuStrip.Height); laneIn56.Location = new Point(laneOut78.Location.X + laneOut78.Width + 20, menuStrip.Height);
laneIn56.Show(); laneIn56.Show();
laneIn56.Start(); laneIn56.Start();
toolStripMenuItemSwitchLaneOutIn.DisableSelected();
} }
private void UpdateLaneOutOut() private void UpdateLaneOutOut()
@ -138,6 +145,8 @@ namespace AIParkingApplication
laneOut34.Location = new Point(laneOut78.Location.X + laneOut78.Width + 20, menuStrip.Height); laneOut34.Location = new Point(laneOut78.Location.X + laneOut78.Width + 20, menuStrip.Height);
laneOut34.Show(); laneOut34.Show();
laneOut34.Start(); laneOut34.Start();
toolStripMenuItemSwitchLaneOutOut.DisableSelected();
} }
private void toolStripMenuItemSwitchLaneInIn_Click(object sender, EventArgs e) private void toolStripMenuItemSwitchLaneInIn_Click(object sender, EventArgs e)
@ -146,7 +155,7 @@ namespace AIParkingApplication
UpdateMenuStripItemStatus(sender as ToolStripMenuItem); UpdateMenuStripItemStatus(sender as ToolStripMenuItem);
StopAllLanes(); StopAllLanes();
UpdateLaneInIn(); UpdateLaneInIn();
appLogger.Log(LogLevel.Info, "Chuyển làn: IN-IN"); applicationLogger.Log(LogLevel.Info, "Chuyển làn: IN-IN");
} }
private void toolStripMenuItemSwitchLaneInOut_Click(object sender, EventArgs e) private void toolStripMenuItemSwitchLaneInOut_Click(object sender, EventArgs e)
@ -155,7 +164,7 @@ namespace AIParkingApplication
UpdateMenuStripItemStatus(sender as ToolStripMenuItem); UpdateMenuStripItemStatus(sender as ToolStripMenuItem);
StopAllLanes(); StopAllLanes();
UpdateLaneInOut(); UpdateLaneInOut();
appLogger.Log(LogLevel.Info, "Chuyển làn: IN-OUT"); applicationLogger.Log(LogLevel.Info, "Chuyển làn: IN-OUT");
} }
private void toolStripMenuItemSwitchLaneOutIn_Click(object sender, EventArgs e) private void toolStripMenuItemSwitchLaneOutIn_Click(object sender, EventArgs e)
@ -164,7 +173,7 @@ namespace AIParkingApplication
UpdateMenuStripItemStatus(sender as ToolStripMenuItem); UpdateMenuStripItemStatus(sender as ToolStripMenuItem);
StopAllLanes(); StopAllLanes();
UpdateLaneOutIn(); UpdateLaneOutIn();
appLogger.Log(LogLevel.Info, "Chuyển làn: OUT-IN"); applicationLogger.Log(LogLevel.Info, "Chuyển làn: OUT-IN");
} }
private void toolStripMenuItemSwitchLaneOutOut_Click(object sender, EventArgs e) private void toolStripMenuItemSwitchLaneOutOut_Click(object sender, EventArgs e)
@ -173,7 +182,7 @@ namespace AIParkingApplication
UpdateMenuStripItemStatus(sender as ToolStripMenuItem); UpdateMenuStripItemStatus(sender as ToolStripMenuItem);
StopAllLanes(); StopAllLanes();
UpdateLaneOutOut(); UpdateLaneOutOut();
appLogger.Log(LogLevel.Info, "Chuyển làn: OUT-OUT"); applicationLogger.Log(LogLevel.Info, "Chuyển làn: OUT-OUT");
} }
private void UpdateMenuStripItemStatus(ToolStripMenuItem selectedToolStripMenuItem) private void UpdateMenuStripItemStatus(ToolStripMenuItem selectedToolStripMenuItem)
@ -226,34 +235,29 @@ namespace AIParkingApplication
if (lane0 == "in" && lane1 == "in") if (lane0 == "in" && lane1 == "in")
{ {
UpdateLaneInIn(); UpdateLaneInIn();
toolStripMenuItemSwitchLaneInIn.DisableSelected(); applicationLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: IN-IN");
appLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: IN-IN");
} }
if (lane0 == "in" && lane1 == "out") if (lane0 == "in" && lane1 == "out")
{ {
UpdateLaneInOut(); UpdateLaneInOut();
toolStripMenuItemSwitchLaneInOut.DisableSelected(); applicationLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: IN-OUT");
appLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: IN-OUT");
} }
if (lane0 == "out" && lane1 == "in") if (lane0 == "out" && lane1 == "in")
{ {
UpdateLaneOutIn(); UpdateLaneOutIn();
toolStripMenuItemSwitchLaneOutIn.DisableSelected(); applicationLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: OUT-IN");
appLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: OUT-IN");
} }
if (lane0 == "out" && lane1 == "out") if (lane0 == "out" && lane1 == "out")
{ {
UpdateLaneOutOut(); UpdateLaneOutOut();
toolStripMenuItemSwitchLaneOutOut.DisableSelected(); applicationLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: OUT-OUT");
appLogger.Log(LogLevel.Info, $"Khởi động App sử dụng lane: OUT-OUT");
} }
} }
else else
{ {
Util.AddOrUpdateAppSettings(CURRENT_LANE_SETTING_KEY, "IN-OUT"); Util.AddOrUpdateAppSettings(CURRENT_LANE_SETTING_KEY, "IN-OUT");
UpdateLaneInOut(); UpdateLaneInOut();
toolStripMenuItemSwitchLaneInOut.DisableSelected(); applicationLogger.Log(LogLevel.Info, $"Khởi động App đọc config không đủ 2 param: IN-OUT");
appLogger.Log(LogLevel.Info, $"Khởi động App đọc config không đủ 2 param: IN-OUT");
} }
} }
} }
@ -261,9 +265,8 @@ namespace AIParkingApplication
{ {
Util.AddOrUpdateAppSettings(CURRENT_LANE_SETTING_KEY, "IN-OUT"); Util.AddOrUpdateAppSettings(CURRENT_LANE_SETTING_KEY, "IN-OUT");
UpdateLaneInOut(); UpdateLaneInOut();
toolStripMenuItemSwitchLaneInOut.DisableSelected();
Console.WriteLine($"{DateTime.Now.GetTimeFormatted()}\tReadLaneSettingFromConfigurationFile\t{ex.Message}"); Console.WriteLine($"{DateTime.Now.GetTimeFormatted()}\tReadLaneSettingFromConfigurationFile\t{ex.Message}");
appLogger.Log(LogLevel.Error, $"Đọc config làn lỗi khi khởi động app!\texMessage: {ex.Message}"); applicationLogger.Log(LogLevel.Error, $"Đọc config làn lỗi khi khởi động app!\texMessage: {ex.Message}");
} }
} }
@ -277,7 +280,7 @@ namespace AIParkingApplication
{ {
doorAccessControlDeviceIP = string.Empty; doorAccessControlDeviceIP = string.Empty;
Console.WriteLine($"{DateTime.Now.GetTimeFormatted()}\tReadAccessControlDeviceIPConfiguration\t{ex.Message}"); Console.WriteLine($"{DateTime.Now.GetTimeFormatted()}\tReadAccessControlDeviceIPConfiguration\t{ex.Message}");
appLogger.Log(LogLevel.Error, $"Cấu hình IP thiết bị mở cửa lỗi(DOOR_ACCESS_DEVICE_CONTROL_IP)!\texMessage: {ex.Message}"); applicationLogger.Log(LogLevel.Error, $"Cấu hình IP thiết bị mở cửa lỗi(DOOR_ACCESS_DEVICE_CONTROL_IP)!\texMessage: {ex.Message}");
} }
} }
@ -289,7 +292,7 @@ namespace AIParkingApplication
private void AIParkingApplicationForm_FormClosing(object sender, FormClosingEventArgs e) private void AIParkingApplicationForm_FormClosing(object sender, FormClosingEventArgs e)
{ {
appLogger.Log(LogLevel.Info, $"Đóng ứng dụng"); applicationLogger.Log(LogLevel.Error, $"Đóng ứng dụng");
Application.Exit(); Application.Exit();
} }
} }

View File

@ -4,27 +4,24 @@ using System.Threading.Tasks;
using OpenCvSharp; using OpenCvSharp;
using Newtonsoft.Json; using Newtonsoft.Json;
using System.Net; using System.Net;
using NLog;
namespace AIParkingApplication namespace AIParkingApplication
{ {
public class ApiController : IDisposable public class ApiController : IDisposable
{ {
private const int MAX_REQUEST = 3;
private HttpClient httpClient; private HttpClient httpClient;
private bool isHttpClientDisposabled; private bool isHttpClientDisposabled;
private int numberOfRetry;
private Logger appLogger;
public ApiController(string serverIPAddress, Logger appLogger, int numberOfRetry = 3) public ApiController(string serverIPAddress, int numberOfRetry = 5)
{ {
this.appLogger = appLogger;
httpClient = new HttpClient httpClient = new HttpClient
{ {
BaseAddress = new Uri($"http://{serverIPAddress}"), BaseAddress = new Uri($"http://{serverIPAddress}"),
Timeout = TimeSpan.FromSeconds(5) Timeout = TimeSpan.FromSeconds(5)
}; };
isHttpClientDisposabled = false; isHttpClientDisposabled = false;
this.numberOfRetry = numberOfRetry;
} }
~ApiController() ~ApiController()
@ -74,14 +71,12 @@ namespace AIParkingApplication
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"GetStatisticInfo Exception:\t{DateTime.Now.GetTimeFormatted()} \t {ex.Message}"); Console.WriteLine($"GetStatisticInfo Exception:\t{DateTime.Now.GetTimeFormatted()} \t {ex.Message}");
appLogger.Log(LogLevel.Info, $"Query dữ liệu thống kê bãi xe lỗi. exMessage: {ex.Message}");
return null; return null;
} }
} }
public async Task<CardInformation> GetCardInformation(string cardNumber) public async Task<CardInformation> GetCardInformation(string cardNumber)
{ {
int requestCounter = 1;
try try
{ {
var request = new CardModel() var request = new CardModel()
@ -89,6 +84,7 @@ namespace AIParkingApplication
CardNumber = cardNumber CardNumber = cardNumber
}; };
HttpResponseMessage response; HttpResponseMessage response;
int requestCounter = 1;
do do
{ {
response = await httpClient.PostAsJsonAsync("/api/check-card", request); response = await httpClient.PostAsJsonAsync("/api/check-card", request);
@ -96,7 +92,7 @@ namespace AIParkingApplication
requestCounter += 1; requestCounter += 1;
await Task.Delay(100); await Task.Delay(100);
} }
while (response.StatusCode != HttpStatusCode.OK && requestCounter < numberOfRetry); while (response.StatusCode != HttpStatusCode.OK && requestCounter < MAX_REQUEST);
var cardValication = await response.Content.ReadAsAsync<CardInformation>(); var cardValication = await response.Content.ReadAsAsync<CardInformation>();
return cardValication; return cardValication;
@ -104,7 +100,6 @@ namespace AIParkingApplication
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"CheckCard Exception:\t{DateTime.Now.GetTimeFormatted()} \t {ex.Message}"); Console.WriteLine($"CheckCard Exception:\t{DateTime.Now.GetTimeFormatted()} \t {ex.Message}");
appLogger.Log(LogLevel.Info, $"Query thông tin thẻ lỗi. Thẻ số: {cardNumber} | số lần thử lại: {requestCounter} | exMessage: {ex.Message}");
return null; return null;
} }
} }
@ -116,8 +111,6 @@ namespace AIParkingApplication
string plateImageResultBase64 = Convert.ToBase64String(plateImageResult.ToBytes()); string plateImageResultBase64 = Convert.ToBase64String(plateImageResult.ToBytes());
string plateFrameImageBase64 = Convert.ToBase64String(plateFrameImage.ToBytes()); string plateFrameImageBase64 = Convert.ToBase64String(plateFrameImage.ToBytes());
string frameImageBase64 = Convert.ToBase64String(frameImage.ToBytes()); string frameImageBase64 = Convert.ToBase64String(frameImage.ToBytes());
int requestCounter = 1;
try try
{ {
var request = new SaveLogModel var request = new SaveLogModel
@ -135,22 +128,21 @@ namespace AIParkingApplication
FrameImage = frameImageBase64 FrameImage = frameImageBase64
}; };
HttpResponseMessage response; HttpResponseMessage response;
int requestCounter = 1;
do do
{ {
response = await httpClient.PostAsJsonAsync("/api/save-logs", request); response = await httpClient.PostAsJsonAsync("/api/save-logs", request);
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
requestCounter += 1; requestCounter += 1;
await Task.Delay(100); await Task.Delay(100);
} while (response.StatusCode != HttpStatusCode.OK && requestCounter < numberOfRetry); } while (response.StatusCode != HttpStatusCode.OK && requestCounter < MAX_REQUEST);
SaveLogRespone saveLogRespone = await response.Content.ReadAsAsync<SaveLogRespone>(); SaveLogRespone saveLogRespone = await response.Content.ReadAsAsync<SaveLogRespone>();
return saveLogRespone; return saveLogRespone;
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"SaveLog Exception:\t{DateTime.Now.GetTimeFormatted()} \t {ex.Message}"); Console.WriteLine($"SaveLog Exception:\t{DateTime.Now.GetTimeFormatted()} \t {ex.Message}");
appLogger.Log(LogLevel.Info, string.Format("Không thể lưu log gửi xe. Làn: {0} | Mã thẻ: {1} | cameraID: {2} | Thời gian: {3} | Biển số: {4} | LogID: {5} | exMessage: ", direction == LaneDirection.In ? "IN" : "OUT", cardID, cameraID, timestamp, plateString, logID, ex.Message)); return new SaveLogRespone();
return null;
} }
} }

View File

@ -1,5 +1,4 @@
using NLog; using System;
using System;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
@ -16,11 +15,10 @@ namespace AIParkingApplication
private string connectionString; private string connectionString;
private bool isReconnected; private bool isReconnected;
private int reconnectCounter; private int reconnectCounter;
private Logger appLogger;
public event C3DeviceEvent OnNewCardReceived; public event C3DeviceEvent OnNewCardReceived;
public C3DeviceController(Logger appLogger, string ipAddress, int port = C3Constant.DEFAULT_C3_PORT) public C3DeviceController(string ipAddress, int port = C3Constant.DEFAULT_C3_PORT)
{ {
this.ipAddress = ipAddress; this.ipAddress = ipAddress;
this.port = port; this.port = port;
@ -28,7 +26,6 @@ namespace AIParkingApplication
oneTimeConnectedParamHandler = IntPtr.Zero; oneTimeConnectedParamHandler = IntPtr.Zero;
isReconnected = true; isReconnected = true;
reconnectCounter = 0; reconnectCounter = 0;
this.appLogger = appLogger;
} }
~C3DeviceController() ~C3DeviceController()

View File

@ -3,7 +3,6 @@ using System.Drawing;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using OpenCvSharp; using OpenCvSharp;
using OpenCvSharp.Extensions; using OpenCvSharp.Extensions;
@ -22,7 +21,6 @@ namespace AIParkingApplication
private bool isRetryMode; private bool isRetryMode;
private IDoorControlAccess doorControlAccess; private IDoorControlAccess doorControlAccess;
private ApiController apiController; private ApiController apiController;
private Logger appLogger;
public LaneIn(int doorId, public LaneIn(int doorId,
string cameraId, string cameraId,
@ -31,14 +29,12 @@ namespace AIParkingApplication
IDoorControlAccess doorControlAccess, IDoorControlAccess doorControlAccess,
ApiController apiController, ApiController apiController,
EngineApiController engineApiController, EngineApiController engineApiController,
Logger appLogger,
bool isSupportSquarePlate = true, bool isSupportSquarePlate = true,
bool isSupportLongPlate = false, bool isSupportLongPlate = false,
bool isAutoOpenDoor = true, bool isAutoOpenDoor = true,
bool isRetryMode = false) bool isRetryMode = false)
{ {
InitializeComponent(); InitializeComponent();
this.appLogger = appLogger;
DoorId = doorId; DoorId = doorId;
this.cameraId = cameraId; this.cameraId = cameraId;
this.isSupportSquarePlate = isSupportSquarePlate; this.isSupportSquarePlate = isSupportSquarePlate;
@ -63,27 +59,23 @@ namespace AIParkingApplication
if (cardInfoResult == null) if (cardInfoResult == null)
{ {
lblStatusInfo.UpdateLabel("KHÔNG THỂ KẾT NỐI SERVER", Color.Purple); lblStatusInfo.UpdateLabel("KHÔNG THỂ KẾT NỐI SERVER", Color.Purple);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: KHÔNG THỂ KẾT NỐI TỚI SERVER");
return; return;
} }
if (!cardInfoResult.IsValid) if (!cardInfoResult.IsValid)
{ {
lblStatusInfo.UpdateLabel("THẺ KHÔNG HỢP LỆ", Color.Purple); lblStatusInfo.UpdateLabel("THẺ KHÔNG HỢP LỆ", Color.Purple);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: THẺ KHÔNG HỢP LỆ");
return; return;
} }
if (cardInfoResult.Direction != "in") if (cardInfoResult.Direction != "in")
{ {
lblStatusInfo.UpdateLabel("XE ĐÃ Ở TRONG BÃI", Color.Red); lblStatusInfo.UpdateLabel("XE ĐÃ Ở TRONG BÃI", Color.Red);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: XE ĐÃ Ở TRONG BÃI");
return; return;
} }
plateCamera.RequestCaptureOneFrame(); plateCamera.RequestCaptureOneFrame();
overviewCamera.RequestCaptureOneFrame(); overviewCamera.RequestCaptureOneFrame();
await Task.Delay(200); await Task.Delay(200);
appLogger.Log(LogLevel.Info, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | Chụp ảnh camera");
var plateVideoFrame = plateCamera.CurrentFrame; var plateVideoFrame = plateCamera.CurrentFrame;
FinalPlateResult result = await ProcessFrameImage(plateProcessor, plateVideoFrame, isRetryMode); FinalPlateResult result = await ProcessFrameImage(plateProcessor, plateVideoFrame, isRetryMode);
@ -96,13 +88,6 @@ namespace AIParkingApplication
var saveLogResult = await apiController.SaveLog(LaneDirection.In, cardInformation.CardRealID.ToString(), cameraId, result.PlateType, DateTime.Now.GetTimeFormatted(), result.PlateString, result.PlateImage, result.PlateImage, result.PlateImage, overviewVideoFrame); var saveLogResult = await apiController.SaveLog(LaneDirection.In, cardInformation.CardRealID.ToString(), cameraId, result.PlateType, DateTime.Now.GetTimeFormatted(), result.PlateString, result.PlateImage, result.PlateImage, result.PlateImage, overviewVideoFrame);
if (saveLogResult == null)
{
lblStatusInfo.UpdateLabel("KHÔNG CÓ KẾT NỐI ĐẾN MÁY CHỦ", Color.Red);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: KHÔNG CÓ KẾT NỐI ĐẾN MÁY CHỦ - KHÔNG LƯU ĐƯỢC LOG");
return;
}
ShowCardInfoOnUI(cardNumber, result.PlateString, cardInformation.CardType, DateTime.Now.GetTimeFormatted()); ShowCardInfoOnUI(cardNumber, result.PlateString, cardInformation.CardType, DateTime.Now.GetTimeFormatted());
if (saveLogResult.Status) if (saveLogResult.Status)
@ -110,13 +95,11 @@ namespace AIParkingApplication
if (isAutoOpenDoor && DoorId == doorId) if (isAutoOpenDoor && DoorId == doorId)
{ {
OpenDoor(doorId); OpenDoor(doorId);
appLogger.Log(LogLevel.Info, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | biển số: {result.PlateString} | Đã mở cửa");
} }
} }
else else
{ {
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: LƯU BẢN GHI LỖI"); lblStatusInfo.UpdateLabel("KHÔNG CÓ KẾT NỐI ĐẾN MÁY CHỦ", Color.Red);
lblStatusInfo.UpdateLabel("LƯU BẢN GHI LỖI", Color.Red);
} }
} }
@ -176,12 +159,6 @@ namespace AIParkingApplication
{ {
plateCamera.Stop(); plateCamera.Stop();
overviewCamera.Stop(); overviewCamera.Stop();
pictureBoxPlateImage.UpdateImage(null);
pictureBoxPlateVideo.UpdateImage(null);
pictureBoxOverviewImage.UpdateImage(null);
pictureBoxOverviewVideo.UpdateImage(null);
} }
public void Start() public void Start()

View File

@ -3,7 +3,6 @@ using System.Drawing;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using NLog;
using OpenCvSharp; using OpenCvSharp;
using OpenCvSharp.Extensions; using OpenCvSharp.Extensions;
@ -23,7 +22,6 @@ namespace AIParkingApplication
private IDoorControlAccess doorControlAccess; private IDoorControlAccess doorControlAccess;
private ApiController apiController; private ApiController apiController;
private Printer printer; private Printer printer;
private Logger appLogger;
public LaneOut(int doorId, public LaneOut(int doorId,
string cameraId, string cameraId,
@ -32,14 +30,12 @@ namespace AIParkingApplication
IDoorControlAccess doorControlAccess, IDoorControlAccess doorControlAccess,
ApiController apiController, ApiController apiController,
EngineApiController engineApiController, EngineApiController engineApiController,
Logger appLogger,
bool isSupportSquarePlate = true, bool isSupportSquarePlate = true,
bool isSupportLongPlate = false, bool isSupportLongPlate = false,
bool isAutoOpenDoor = true, bool isAutoOpenDoor = true,
bool isRetryMode = false) bool isRetryMode = false)
{ {
InitializeComponent(); InitializeComponent();
this.appLogger = appLogger;
DoorId = doorId; DoorId = doorId;
this.cameraId = cameraId; this.cameraId = cameraId;
this.isSupportSquarePlate = isSupportSquarePlate; this.isSupportSquarePlate = isSupportSquarePlate;
@ -50,7 +46,7 @@ namespace AIParkingApplication
plateCamera = new Camera(plateStream); plateCamera = new Camera(plateStream);
this.apiController = apiController; this.apiController = apiController;
this.doorControlAccess = doorControlAccess; this.doorControlAccess = doorControlAccess;
printer = new Printer(appLogger); printer = new Printer();
plateProcessor = new PlateProcessor(engineApiController, this.isSupportSquarePlate, this.isSupportLongPlate); plateProcessor = new PlateProcessor(engineApiController, this.isSupportSquarePlate, this.isSupportLongPlate);
} }
@ -66,20 +62,17 @@ namespace AIParkingApplication
if (cardInfoResult == null) if (cardInfoResult == null)
{ {
lblStatusInfo.UpdateLabel("KHÔNG THỂ KẾT NỐI SERVER", Color.Purple); lblStatusInfo.UpdateLabel("KHÔNG THỂ KẾT NỐI SERVER", Color.Purple);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: KHÔNG THỂ KẾT NỐI TỚI SERVER");
return; return;
} }
if (!cardInfoResult.IsValid) if (!cardInfoResult.IsValid)
{ {
lblStatusInfo.UpdateLabel("THẺ KHÔNG HỢP LỆ", Color.Purple); lblStatusInfo.UpdateLabel("THẺ KHÔNG HỢP LỆ", Color.Purple);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: THẺ KHÔNG HỢP LỆ");
return; return;
} }
if (cardInfoResult.Direction != "out") if (cardInfoResult.Direction != "out")
{ {
lblStatusInfo.UpdateLabel("CHƯA NHẬN THẺ VÀO", Color.Red); lblStatusInfo.UpdateLabel("CHƯA NHẬN THẺ VÀO", Color.Red);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: XE ĐÃ Ở TRONG BÃI");
return; return;
} }
@ -92,7 +85,6 @@ namespace AIParkingApplication
plateCamera.RequestCaptureOneFrame(); plateCamera.RequestCaptureOneFrame();
overviewCamera.RequestCaptureOneFrame(); overviewCamera.RequestCaptureOneFrame();
await Task.Delay(200); await Task.Delay(200);
appLogger.Log(LogLevel.Info, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | Chụp ảnh camera");
var plateVideoFrame = plateCamera.CurrentFrame; var plateVideoFrame = plateCamera.CurrentFrame;
FinalPlateResult result = await ProcessFrameImage(plateProcessor, plateVideoFrame, isRetryMode); FinalPlateResult result = await ProcessFrameImage(plateProcessor, plateVideoFrame, isRetryMode);
@ -105,13 +97,6 @@ namespace AIParkingApplication
var saveLogResult = await apiController.SaveLog(LaneDirection.Out, cardInformation.CardRealID.ToString(), cameraId, result.PlateType, DateTime.Now.GetTimeFormatted(), result.PlateString, result.PlateImage, result.PlateImage, result.PlateImage, overviewVideoFrame, cardInformation.LogID.ToString()); var saveLogResult = await apiController.SaveLog(LaneDirection.Out, cardInformation.CardRealID.ToString(), cameraId, result.PlateType, DateTime.Now.GetTimeFormatted(), result.PlateString, result.PlateImage, result.PlateImage, result.PlateImage, overviewVideoFrame, cardInformation.LogID.ToString());
if (saveLogResult == null)
{
lblStatusInfo.UpdateLabel("KHÔNG CÓ KẾT NỐI ĐẾN MÁY CHỦ", Color.Red);
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: KHÔNG CÓ KẾT NỐI ĐẾN MÁY CHỦ - KHÔNG LƯU ĐƯỢC LOG");
return;
}
ShowCardInfoOnUI(cardNumber, result.PlateString, cardInformation.PlateString, cardInformation.CardType, cardInformation.TimeIn, DateTime.Now.GetTimeFormatted(), saveLogResult.Cost); ShowCardInfoOnUI(cardNumber, result.PlateString, cardInformation.PlateString, cardInformation.CardType, cardInformation.TimeIn, DateTime.Now.GetTimeFormatted(), saveLogResult.Cost);
if (saveLogResult.Status) if (saveLogResult.Status)
@ -119,7 +104,6 @@ namespace AIParkingApplication
if (isAutoOpenDoor) if (isAutoOpenDoor)
{ {
OpenDoor(doorId); OpenDoor(doorId);
appLogger.Log(LogLevel.Info, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | biển số: {result.PlateString} | Đã mở cửa");
} }
PrinterData printerData = new PrinterData PrinterData printerData = new PrinterData
{ {
@ -132,8 +116,7 @@ namespace AIParkingApplication
} }
else else
{ {
appLogger.Log(LogLevel.Error, $"Request thẻ cổng {doorId} vào | số thẻ : {cardNumber} | lỗi: LƯU BẢN GHI LỖI"); lblStatusInfo.UpdateLabel("KHÔNG CÓ KẾT NỐI ĐẾN MÁY CHỦ", Color.Red);
lblStatusInfo.UpdateLabel("LƯU BẢN GHI LỖI", Color.Red);
} }
} }
@ -199,12 +182,6 @@ namespace AIParkingApplication
{ {
plateCamera.Stop(); plateCamera.Stop();
overviewCamera.Stop(); overviewCamera.Stop();
pictureBoxPlateImage.UpdateImage(null);
pictureBoxPlateVideo.UpdateImage(null);
pictureBoxOverviewImage.UpdateImage(null);
pictureBoxOverviewVideo.UpdateImage(null);
} }
public void Start() public void Start()

View File

@ -1,4 +1,4 @@
using NLog; using OpenCvSharp;
using System; using System;
using System.Configuration; using System.Configuration;
using System.Drawing; using System.Drawing;
@ -10,13 +10,10 @@ namespace AIParkingApplication
public partial class LoginForm : Form public partial class LoginForm : Form
{ {
private ApiController apiController; private ApiController apiController;
private Logger applicationLogger;
public LoginForm() public LoginForm()
{ {
InitializeComponent(); InitializeComponent();
applicationLogger = LogManager.GetLogger(AppConstant.APPLICATION_LOGGER_NAME);
applicationLogger.Log(LogLevel.Info, new string('-', 20));
if (File.Exists(AppConstant.DEFAULT_LOGO_IMAGE)) if (File.Exists(AppConstant.DEFAULT_LOGO_IMAGE))
{ {
pictureBoxImageLogo.Image = new Bitmap(AppConstant.DEFAULT_LOGO_IMAGE); pictureBoxImageLogo.Image = new Bitmap(AppConstant.DEFAULT_LOGO_IMAGE);
@ -34,7 +31,6 @@ namespace AIParkingApplication
{ {
lblLoginStatus.Text = "Địa chỉ server không được để trống! \r\n ví dụ: 192.168.1.2:80"; lblLoginStatus.Text = "Địa chỉ server không được để trống! \r\n ví dụ: 192.168.1.2:80";
btnLogin.Enabled = true; btnLogin.Enabled = true;
applicationLogger.Log(LogLevel.Error, "Địa chỉ server không được để trống");
return; return;
} }
@ -44,19 +40,17 @@ namespace AIParkingApplication
{ {
lblLoginStatus.Text = "Địa chỉ server không đúng định dạng: \r\n ví dụ: 192.168.1.122:80"; lblLoginStatus.Text = "Địa chỉ server không đúng định dạng: \r\n ví dụ: 192.168.1.122:80";
btnLogin.Enabled = true; btnLogin.Enabled = true;
applicationLogger.Log(LogLevel.Error, "Địa chỉ server không đúng định dạng");
return; return;
} }
try try
{ {
apiController = new ApiController(serverUrl, applicationLogger); apiController = new ApiController(serverUrl);
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show($"Cấu máy chủ lỗi - Kiểm tra lại tên máy chủ, kết nối máy chủ! \r\n {ex.Message}", "Lỗi khởi tạo API!", MessageBoxButtons.OK, MessageBoxIcon.Error); MessageBox.Show($"Cấu máy chủ lỗi - Kiểm tra lại tên máy chủ, kết nối máy chủ! \r\n {ex.Message}", "Lỗi khởi tạo API!", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnLogin.Enabled = true; btnLogin.Enabled = true;
applicationLogger.Log(LogLevel.Error, "Cấu máy chủ lỗi - Kiểm tra lại tên máy chủ, kết nối máy chủ! Không thể khởi tạo API Webserver");
return; return;
} }
@ -65,9 +59,8 @@ namespace AIParkingApplication
string password = txtPassword.Text; string password = txtPassword.Text;
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
{ {
lblLoginStatus.Text = "Tên tài khoản hoặc mật khẩu không được để trống"; lblLoginStatus.Text = "Tên tài khoản hoặc mật khẩu không được để trống!";
btnLogin.Enabled = true; btnLogin.Enabled = true;
applicationLogger.Log(LogLevel.Error, "Tên tài khoản hoặc mật khẩu không được để trống");
return; return;
} }
@ -79,27 +72,23 @@ namespace AIParkingApplication
if (execeptioMessage.Contains("Error converting value")) if (execeptioMessage.Contains("Error converting value"))
{ {
lblLoginStatus.UpdateLabel("Sai tên tài khoản hoặc mật khẩu!", Color.Red); lblLoginStatus.UpdateLabel("Sai tên tài khoản hoặc mật khẩu!", Color.Red);
applicationLogger.Log(LogLevel.Error, "Sai tên tài khoản hoặc mật khẩu");
return; return;
} }
if (execeptioMessage.Contains("An error occurred while sending the request")) if (execeptioMessage.Contains("An error occurred while sending the request"))
{ {
lblLoginStatus.UpdateLabel("Không có kết nối tới server!\r\nKiểm tra lại kết nối tới server!", Color.Red, Color.White); lblLoginStatus.UpdateLabel("Không có kết nối tới server!\r\nKiểm tra lại kết nối tới server!", Color.Red, Color.White);
applicationLogger.Log(LogLevel.Error, "Không có kết nối tới server!");
return; return;
} }
lblLoginStatus.UpdateLabel("Không có kết nối tới server!\r\nKiểm tra lại kết nối tới server!", Color.Red, Color.White); lblLoginStatus.UpdateLabel("Không có kết nối tới server!\r\nKiểm tra lại kết nối tới server!", Color.Red, Color.White);
applicationLogger.Log(LogLevel.Error, "Không có kết nối tới server!");
} }
if (loginResult.IsLoginSuccess) if (loginResult.IsLoginSuccess)
{ {
Util.AddOrUpdateAppSettings("DEFAULT_USERNAME", txtUsername.Text); Util.AddOrUpdateAppSettings("DEFAULT_USERNAME", txtUsername.Text);
Util.AddOrUpdateAppSettings("DEFAULT_PASSWORD", txtPassword.Text); Util.AddOrUpdateAppSettings("DEFAULT_PASSWORD", txtPassword.Text);
new AIParkingApplicationForm(apiController, ipAddress, loginResult.LoginData, applicationLogger).Show(); new AIParkingApplicationForm(apiController, ipAddress, loginResult.LoginData).Show();
Hide(); Hide();
applicationLogger.Log(LogLevel.Info, $"Đăng nhập thành công với tài khoản: {txtUsername.Text}");
} }
} }
@ -112,7 +101,6 @@ namespace AIParkingApplication
{ {
if (DialogResult.OK == MessageBox.Show("AIParking - Bạn muốn thoát ứng dụng?", "Cảnh báo!", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)) if (DialogResult.OK == MessageBox.Show("AIParking - Bạn muốn thoát ứng dụng?", "Cảnh báo!", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
{ {
applicationLogger.Log(LogLevel.Info, "Login - Thoát ứng dụng");
Application.Exit(); Application.Exit();
} }
} }
@ -126,12 +114,9 @@ namespace AIParkingApplication
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"{DateTime.Now.GetTimeFormatted()}\tReadAccessControlDeviceIPConfiguration\t{ex.Message}");
txtUsername.Text = string.Empty; txtUsername.Text = string.Empty;
txtPassword.Text = string.Empty; txtPassword.Text = string.Empty;
Util.AddOrUpdateAppSettings("DEFAULT_USERNAME", string.Empty);
Util.AddOrUpdateAppSettings("DEFAULT_PASSWORD", string.Empty);
Console.WriteLine($"{DateTime.Now.GetTimeFormatted()}\tReadAccessControlDeviceIPConfiguration\t{ex.Message}");
applicationLogger.Log(LogLevel.Error, "Không thể đọc cấu hình tài khoản mặc định: DEFAULT_USERNAME, DEFAULT_PASSWORD");
} }
} }

View File

@ -6,16 +6,24 @@
throwExceptions="false" throwExceptions="false"
internalLogLevel="Off" internalLogFile="D:\nlog-internal.log"> internalLogLevel="Off" internalLogFile="D:\nlog-internal.log">
<variable name="logDirectory" value="${basedir}/logs"/> <variable name="logDirectory" value="${basedir}/logs"/>
<variable name="logLayout" value="${date:format=HH\:mm\:ss dd-MM-yyyy} ${uppercase:${level}} ${message} ${exception}"/>
<targets> <targets>
<target xsi:type="File" name="applicationLogger" fileName="${logDirectory}/${shortdate}_App.log" <target xsi:type="File" name="applicationLogger" fileName="${logDirectory}/${shortdate}_App.log"
layout="${logLayout}" maxArchiveFiles="30" encoding="Unicode" writeBom="true"/> layout="${uppercase:${level}} ${message} ${exception}"
maxArchiveFiles="30"
encoding="Unicode"
writeBom="true"/>
<target xsi:type="File" name="pingServerLoggingFile" fileName="${logDirectory}/${shortdate}_PingServer.log" <target xsi:type="File" name="pingServerLoggingFile" fileName="${logDirectory}/${shortdate}_PingServer.log"
layout="${logLayout}" maxArchiveFiles="30" encoding="Unicode" writeBom="true"/> layout="${uppercase:${level}} ${message} ${exception}"
maxArchiveFiles="30"
encoding="Unicode"
writeBom="true"/>
<target xsi:type="File" name="pingDoorDeviceControlAccessLoggingFile" fileName="${logDirectory}/${shortdate}_PingDoorDeviceControlAccess.log" <target xsi:type="File" name="pingDoorDeviceControlAccessLoggingFile" fileName="${logDirectory}/${shortdate}_PingDoorDeviceControlAccess.log"
layout="${logLayout}" maxArchiveFiles="30" encoding="Unicode" writeBom="true"/> layout="${uppercase:${level}} ${message} ${exception}"
maxArchiveFiles="30"
encoding="Unicode"
writeBom="true"/>
</targets> </targets>
<rules> <rules>
<logger name="ApplicationLogger" minlevel="Trace" writeTo="applicationLogger" /> <logger name="ApplicationLogger" minlevel="Trace" writeTo="applicationLogger" />

View File

@ -1,5 +1,4 @@
using Microsoft.Win32; using Microsoft.Win32;
using NLog;
using System; using System;
using System.IO; using System.IO;
using System.Windows.Forms; using System.Windows.Forms;
@ -8,11 +7,8 @@ namespace AIParkingApplication
{ {
public class Printer public class Printer
{ {
private Logger appLogger; public Printer()
public Printer(Logger appLogger)
{ {
this.appLogger = appLogger;
SetupPrinterPageSetting(); SetupPrinterPageSetting();
} }
@ -47,7 +43,6 @@ namespace AIParkingApplication
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"ProcessingString\texMessage:{ex.Message}"); Console.WriteLine($"ProcessingString\texMessage:{ex.Message}");
appLogger.Log(LogLevel.Info, $"Lỗi khi In hóa đơn: {ex.Message}");
return string.Empty; return string.Empty;
} }
} }