Compare commits

...

9 Commits

8 changed files with 130 additions and 64 deletions

View File

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

View File

@ -4,24 +4,27 @@ 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, int numberOfRetry = 5) public ApiController(string serverIPAddress, Logger appLogger, int numberOfRetry = 3)
{ {
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()
@ -71,12 +74,14 @@ 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()
@ -84,7 +89,6 @@ 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);
@ -92,7 +96,7 @@ namespace AIParkingApplication
requestCounter += 1; requestCounter += 1;
await Task.Delay(100); await Task.Delay(100);
} }
while (response.StatusCode != HttpStatusCode.OK && requestCounter < MAX_REQUEST); while (response.StatusCode != HttpStatusCode.OK && requestCounter < numberOfRetry);
var cardValication = await response.Content.ReadAsAsync<CardInformation>(); var cardValication = await response.Content.ReadAsAsync<CardInformation>();
return cardValication; return cardValication;
@ -100,6 +104,7 @@ 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;
} }
} }
@ -111,6 +116,8 @@ 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
@ -128,21 +135,22 @@ 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 < MAX_REQUEST); } while (response.StatusCode != HttpStatusCode.OK && requestCounter < numberOfRetry);
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}");
return new SaveLogRespone(); 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 null;
} }
} }

View File

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

View File

@ -3,6 +3,7 @@ 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;
@ -21,6 +22,7 @@ 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,
@ -29,12 +31,14 @@ 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;
@ -59,23 +63,27 @@ 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);
@ -88,6 +96,13 @@ 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)
@ -95,11 +110,13 @@ 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
{ {
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: LƯU BẢN GHI LỖI");
lblStatusInfo.UpdateLabel("LƯU BẢN GHI LỖI", Color.Red);
} }
} }
@ -159,6 +176,12 @@ 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,6 +3,7 @@ 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,6 +23,7 @@ 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,
@ -30,12 +32,14 @@ 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;
@ -46,7 +50,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(); printer = new Printer(appLogger);
plateProcessor = new PlateProcessor(engineApiController, this.isSupportSquarePlate, this.isSupportLongPlate); plateProcessor = new PlateProcessor(engineApiController, this.isSupportSquarePlate, this.isSupportLongPlate);
} }
@ -62,17 +66,20 @@ 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;
} }
@ -85,6 +92,7 @@ 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);
@ -97,6 +105,13 @@ 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)
@ -104,6 +119,7 @@ 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
{ {
@ -116,7 +132,8 @@ namespace AIParkingApplication
} }
else else
{ {
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: LƯU BẢN GHI LỖI");
lblStatusInfo.UpdateLabel("LƯU BẢN GHI LỖI", Color.Red);
} }
} }
@ -182,6 +199,12 @@ 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 OpenCvSharp; using NLog;
using System; using System;
using System.Configuration; using System.Configuration;
using System.Drawing; using System.Drawing;
@ -10,10 +10,13 @@ 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);
@ -31,6 +34,7 @@ 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;
} }
@ -40,17 +44,19 @@ 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); apiController = new ApiController(serverUrl, applicationLogger);
} }
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;
} }
@ -59,8 +65,9 @@ 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;
} }
@ -72,23 +79,27 @@ 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).Show(); new AIParkingApplicationForm(apiController, ipAddress, loginResult.LoginData, applicationLogger).Show();
Hide(); Hide();
applicationLogger.Log(LogLevel.Info, $"Đăng nhập thành công với tài khoản: {txtUsername.Text}");
} }
} }
@ -101,6 +112,7 @@ 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();
} }
} }
@ -114,9 +126,12 @@ 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,24 +6,16 @@
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="${uppercase:${level}} ${message} ${exception}" layout="${logLayout}" maxArchiveFiles="30" encoding="Unicode" writeBom="true"/>
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="${uppercase:${level}} ${message} ${exception}" layout="${logLayout}" maxArchiveFiles="30" encoding="Unicode" writeBom="true"/>
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="${uppercase:${level}} ${message} ${exception}" layout="${logLayout}" maxArchiveFiles="30" encoding="Unicode" writeBom="true"/>
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,4 +1,5 @@
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;
@ -7,8 +8,11 @@ namespace AIParkingApplication
{ {
public class Printer public class Printer
{ {
public Printer() private Logger appLogger;
public Printer(Logger appLogger)
{ {
this.appLogger = appLogger;
SetupPrinterPageSetting(); SetupPrinterPageSetting();
} }
@ -43,6 +47,7 @@ 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;
} }
} }