This Commit contains all the changes for the new feature for S.L in regards to ExcelStats of the GUI

This commit is contained in:
2025-10-17 12:06:36 +01:00
parent 0c463ad929
commit f4081515be
10 changed files with 511 additions and 93 deletions

View File

@@ -1,6 +1,9 @@
using Newtonsoft.Json;
using AiQ_GUI.Microsoft;
using Newtonsoft.Json;
using System.ComponentModel;
using System.Data.OleDb;
using System.Diagnostics;
using System.Numerics;
using System.Reflection;
namespace AiQ_GUI
@@ -25,6 +28,8 @@ namespace AiQ_GUI
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public static MainForm? Instance { get; private set; }
// For Access Stats
const string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Final_Test.accdb;Persist Security Info=False;OLE DB Services=-1;";
public MainForm()
{
@@ -37,7 +42,7 @@ namespace AiQ_GUI
Stopwatch stopwatch = Stopwatch.StartNew();
Task? closeProcessesTask = Windows.CloseProcesses(); // Fire and forget closing other apps
Windows.UpdateFirewall();
//Windows.UpdateFirewall();
Task UniDataTask = Task.Run(() => Access.ReadUniData()); // Get universal data
Task<LocalDataStore> LDSWAIT = Task.Run(() => LDS.GetLDS()); // Get and deserialise LDS.json
Task<string> guiVerTask = Task.Run(() => GUIUpdate.FindGUIVersion()); // Get GUI Version
@@ -138,12 +143,15 @@ namespace AiQ_GUI
AddToActionsList($"LED level could not be set: {LEDreply}");
}
else if (!await TestTube.CheckInTestTube(CamOnTest.IP)) // Sets LED's to medium power after checking it is in the test tube
{
await TestFailed(BtnStartTest, "Camera not in test tube");
}
Task VisCheck = Helper.VisualCheck(BtnStartTest);
if (!await FlexiAPI.ZoomModules("1F40", CamOnTest.IP)) // Zoom to 8000 (1F40h) at the same time.
await TestFailed(BtnStartTest, "Could not zoom modules to 8000");
if (!await FlexiAPI.SetZoomLockOn(CamOnTest.IP))
Helper.RestartApp();
@@ -186,7 +194,9 @@ namespace AiQ_GUI
await FlexiAPI.SetTrim(CamOnTest.IP, LblTestTubePing.Text); // Auto trims the cameras, some plates should have been captured in the meantime
if (!await FlexiAPI.ZoomModules("0000", CamOnTest.IP)) // Zoom to full wide
{
await TestFailed(BtnStartTest, "Could not zoom modules to full wide");
}
await Task.Delay(1000); // Wait to be sure cameras are zoomed out.
@@ -214,15 +224,86 @@ namespace AiQ_GUI
LED.CheckLEDs(DiagsAPI.LedCurrent, LblLEDI, "mA", CameraAccessInfo.LED_I); // Current
this.Refresh(); // Make sure all labels are updated before checking them
// If there are any actions identified then fail the test.
// If any labels are red then fail. Only labels in panel so can foreach on labels not controls
if (RhTxBxActions.Text.Length > 2 || PnlLbls.Controls.OfType<Label>().Any(c => c.ForeColor == Color.Red) == true)
await TestFailed(BtnStartTest);// If approved then pass otherwise GUI would have restarted before getting to TestPassed.
{
await TestFailed(BtnStartTest, "Diagnostic Failure");// If approved then pass otherwise GUI would have restarted before getting to TestPassed.
}
await TestPassed(PCTime);
}
public void Stats(string TypeOfTest)
{
Stats([TypeOfTest]);
}
public void Stats(string[] TypeOfTest)
{
using OleDbConnection conn = new(connString); // Opens connection to Access database
try
{
conn.Open(); // Opens DB
string modelNumber = CbBxCameraType.Text.Substring(0, 6); // Get model number from combobox and make sure it is only 6 characters.
foreach (string type in TypeOfTest)
{
string query = $"UPDATE AiQ SET [{type}] = [{type}] + 1 WHERE [ModelNumber] = ?"; // Add one for every test ran of this type for this model number
using OleDbCommand cmd = new(query, conn); // Create command
cmd.Parameters.AddWithValue("?", modelNumber); // Add model number to prevent injection
int rowsAffected = cmd.ExecuteNonQuery();
// Execute the command and get the number of rows affected
//if (rowsAffected > 0) // If one or more rows were updated
// AddToActionsList($"Updated {TypeOfTest} for {modelNumber}");
//else
// AddToActionsList($"No rows found for {modelNumber}");
}
}
catch
{
AddToActionsList("Could not access Access in Google Drive. Is it running?");
return;
}
}
public void StatsDiags(string redDiagLabels, string RhTxBxActionsText)
{
using OleDbConnection conn = new(connString);
conn.Open();
// Null checks
string redVal = string.IsNullOrWhiteSpace(redDiagLabels) ? "-" : redDiagLabels;
string actVal = string.IsNullOrWhiteSpace(RhTxBxActionsText) ? "-" : RhTxBxActionsText;
string model = string.IsNullOrWhiteSpace(CamOnTest?.Model) ? "-" : CamOnTest.Model;
string sql = @"
INSERT INTO DiagsStats ([Date], [Model], [Red Diags Labels], [RhTxBxActions Contents])
VALUES (?, ?, ?, ?)";
using OleDbCommand cmd = new(sql, conn);
cmd.Parameters.Add(new OleDbParameter
{
OleDbType = OleDbType.Date,
Value = DateTime.Now
});
cmd.Parameters.AddWithValue("?", model);
cmd.Parameters.AddWithValue("?", redVal);
cmd.Parameters.AddWithValue("?", actVal);
int rows = cmd.ExecuteNonQuery();
//if (rows > 0)
// AddToActionsList($"DiagsStats inserted ({rows} row) for model '{model}' on {DateTime.Now:yyyy-MM-dd}");
//else
// AddToActionsList("No rows inserted into DiagsStats (unexpected).");
}
private async void BtnPreTest_Click(object sender, EventArgs e)
{
// Show user test has started
@@ -278,7 +359,11 @@ namespace AiQ_GUI
await PreTestPassed();
}
else
await PreTestFailed();
{
await PreTestFailed("Diagnostic Failure");
}
}
// ***** Pass/Fails *****
@@ -293,7 +378,7 @@ namespace AiQ_GUI
// Purge camera of all reads
await FlexiAPI.APIHTTPRequest("/api/purge-all", CamOnTest.IP);
if (await DisplayQuestion("Do you want to set this camera to 211 and God mode?"))
if (await DisplayQuestion("Do you want to set this camera to 211 and God mode off?"))
{
// Turn off God mode
string[,] GOD_JSON = { { "propGodMode", "false" } };
@@ -322,25 +407,45 @@ namespace AiQ_GUI
// TODO make sure serial number is in CamOnTest before making PDF
// Serial number is either what came out of the camera under RMA or updated above as new serial number from next empty row in spreadsheet
PDF.CreateFinalTestReport(CamOnTest, CbBxUserName.Text, fulltestvalues, PCTime);
// Indicators to the user the test has passed
BtnStartTest.BackColor = Color.ForestGreen;
BtnStartTest.Text = "Test Passed";
PnlQuestion.Visible = false; // just in case this came from an override
Logging.LogMessage("Final Test Passed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{
Stats("Final Tests Passed");
}
else
{
Stats("RMA Final Tests Passed");
}
}
public async Task TestFailed(Button Btn, string ErrMssg)
{
AddToActionsList(ErrMssg);
await TestFailed(Btn);
}
private async Task TestFailed(Button Btn)
{
// Indicators to the user the test has failed
Btn.BackColor = Color.Maroon;
Btn.Text = "Test Failed";
if (!(CamOnTest.RMANum != 0)) // Yap to check if it is not a RMA
{
Stats( ["Final Tests Failed", ErrMssg]);
}
else
{
Stats("RMA Final Tests Failed");
}
AddToActionsList(ErrMssg);
string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls
.OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
StatsDiags(RedLbls, RhTxBxActions.Text); // Log to Access database
if (await DisplayQuestion("Test failed, appeal?" + Environment.NewLine + "See Actions textbox for details."))
{
@@ -356,14 +461,10 @@ namespace AiQ_GUI
this.Refresh(); // To make sure all labels are up to date before reading them
// Joins the actions box to any red labels to use as a full failed text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine +
string.Join(Environment.NewLine, PnlLbls.Controls
.OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text
Logging.LogErrorMessage(FullFailureValues);
IList<IList<object>> values = GoogleAPI.service.Spreadsheets.Values.Get(GoogleAPI.spreadsheetId_ModelInfo, "'Approval'!A1:A").Execute().Values;
if (values?.Count > 0)
@@ -416,12 +517,20 @@ namespace AiQ_GUI
PnlQuestion.Visible = true;
BtnNo.Visible = false;
Logging.LogMessage("Pre Test Passed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{
Stats("Pre Tests Passed");
}
else
{
Stats("RMA Pre Tests Passed");
}
if (await DisplayQuestion("Test passed, restart?"))
Helper.RestartApp();
}
private async Task PreTestFailed()
private async Task PreTestFailed(string ErrMssg)
{
BtnPreTest.BackColor = Color.Maroon; // Indicators to the user the test has failed
BtnPreTest.Text = "Test Failed";
@@ -429,6 +538,23 @@ namespace AiQ_GUI
BtnNo.Visible = false;
Logging.LogMessage("Pre Test Failed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{
Stats(["Pre Tests Failed", ErrMssg]);
}
else
{
Stats("RMA Pre Tests Failed");
}
string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls
.OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
StatsDiags(RedLbls, RhTxBxActions.Text); // Log to Access database
if (await DisplayQuestion("Test failed, restart?" + Environment.NewLine + "See Actions textbox for details."))
Helper.RestartApp();
}
@@ -549,7 +675,9 @@ namespace AiQ_GUI
CamOnTest.RMANum = Convert.ToInt32(await DisplayInput("What is the RMA number?"));
if (CamOnTest.RMANum == -1) // Means they chose the 'I don't know' option
{
await TestFailed(BtnStartTest, "Please get RMA number from operations team before continuing");
}
}
// Found RMA num and want to verify it with user
else if (!await DisplayQuestion($"Is {CamOnTest.RMANum} the RMA Number?")) // '!' because if its not the right RMA number let the user to it manually
@@ -557,7 +685,9 @@ namespace AiQ_GUI
CamOnTest.RMANum = Convert.ToInt32(await DisplayInput("What is the RMA number?"));
if (CamOnTest.RMANum == -1) // Means they chose the 'I don't know' option
{
await TestFailed(BtnStartTest, "Please get RMA number from operations team before continuing");
}
}
}
}
@@ -622,7 +752,11 @@ namespace AiQ_GUI
string ProdcutKeyID = await DisplayInput("What is the Key ID?", false);
if (RegexCache.VaxtorRegex().IsMatch(ProdcutKeyID)) // Means they chose the 'I don't know' option or isn't valid Key ID
{
Stats("Please Get A Valid Vaxtor Product Key Before Continuing");
await TestFailed(BtnStartTest, "Please get a valid Vaxtor Product Key before continuing");
}
DiagsAPI.licenses.raptorKeyID = TxBxProductKey.Text;
lblVaxtor.Text += DiagsAPI.licenses.raptorKeyID;
@@ -671,7 +805,7 @@ namespace AiQ_GUI
if (!JSONResponse.Contains(NewSerial) || !JSONResponse.Contains(CamOnTest.Model))
{
AddToActionsList("Could not set model or serial numbers into camera.");
await PreTestFailed();
await PreTestFailed("Failed To Set Model Or Serial Number");
}
DiagsAPI.modelNumber = CamOnTest.Model; // Update Diags and labels
@@ -1659,8 +1793,8 @@ namespace AiQ_GUI
// Constants
const double RealPlateWidthMeters = 0.52; // UK standard plate width
const double FocalLengthPixels = (50 * 1280) / 14.111224; // focal mm * pixel width / sensor width for IQ
// const double FocalLengthPixels = (50 * 1920) / 6.95; // focal mm * pixel width / sensor width for AiQ
// const double FocalLengthPixels = (50 * 1280) / 14.111224; // focal mm * pixel width / sensor width for IQ
const double FocalLengthPixels = (35 * 1920) / 6.95; // focal mm * pixel width / sensor width for AiQ
const double FrameRate = 25.0; // Frames per second
public class FrameData
@@ -1689,38 +1823,72 @@ namespace AiQ_GUI
return speedMph;
}
// ***** Test & Debug *****
private void BtnTest_Click(object sender, EventArgs e)
private async void BtnTest_Click(object sender, EventArgs e)
{
Stopwatch stopWatchTest = Stopwatch.StartNew();
//string[,] GOD_JSON = { { "propURI", "rtsp://ADMIN:1234@192.168.0.49:554/live/main" } };
//string str = FlexiAPI.BuildJsonUpdate(GOD_JSON, "CameraA");
//AddToActionsList(str);
List<FrameData> frames = new List<FrameData>
{
new FrameData { FrameID = 60192555, PlatePosX = 1172, PlatePosY = 393, PlateWidthPixels = 108 },
new FrameData { FrameID = 60192556, PlatePosX = 1103, PlatePosY = 361, PlateWidthPixels = 105 },
new FrameData { FrameID = 60192558, PlatePosX = 983, PlatePosY = 331, PlateWidthPixels = 99 },
new FrameData { FrameID = 60192559, PlatePosX = 930, PlatePosY = 301, PlateWidthPixels = 95 },
new FrameData { FrameID = 60192560, PlatePosX = 880, PlatePosY = 304, PlateWidthPixels = 93 },
new FrameData { FrameID = 60192561, PlatePosX = 834, PlatePosY = 278, PlateWidthPixels = 89 },
new FrameData { FrameID = 60192562, PlatePosX = 792, PlatePosY = 229, PlateWidthPixels = 87 },
new FrameData { FrameID = 60192563, PlatePosX = 752, PlatePosY = 208, PlateWidthPixels = 85 },
new FrameData { FrameID = 60192565, PlatePosX = 680, PlatePosY = 187, PlateWidthPixels = 81 },
new FrameData { FrameID = 60192566, PlatePosX = 648, PlatePosY = 167, PlateWidthPixels = 78 },
new FrameData { FrameID = 60192567, PlatePosX = 617, PlatePosY = 149, PlateWidthPixels = 76 },
new FrameData { FrameID = 60192568, PlatePosX = 588, PlatePosY = 132, PlateWidthPixels = 75 },
new FrameData { FrameID = 60192569, PlatePosX = 561, PlatePosY = 100, PlateWidthPixels = 70 },
new FrameData { FrameID = 60192570, PlatePosX = 535, PlatePosY = 85, PlateWidthPixels = 72 },
new FrameData { FrameID = 60192572, PlatePosX = 488, PlatePosY = 70, PlateWidthPixels = 69 },
new FrameData { FrameID = 60192573, PlatePosX = 466, PlatePosY = 55, PlateWidthPixels = 67 }
};
// To estimate speed
//List<FrameData> frames = new List<FrameData>
//{
// new FrameData { FrameID = 60192555, PlatePosX = 1172, PlatePosY = 393, PlateWidthPixels = 108 },
// new FrameData { FrameID = 60192556, PlatePosX = 1103, PlatePosY = 361, PlateWidthPixels = 105 },
// new FrameData { FrameID = 60192558, PlatePosX = 983, PlatePosY = 331, PlateWidthPixels = 99 },
// new FrameData { FrameID = 60192559, PlatePosX = 930, PlatePosY = 301, PlateWidthPixels = 95 },
// new FrameData { FrameID = 60192560, PlatePosX = 880, PlatePosY = 304, PlateWidthPixels = 93 },
// new FrameData { FrameID = 60192561, PlatePosX = 834, PlatePosY = 278, PlateWidthPixels = 89 },
// new FrameData { FrameID = 60192562, PlatePosX = 792, PlatePosY = 229, PlateWidthPixels = 87 },
// new FrameData { FrameID = 60192563, PlatePosX = 752, PlatePosY = 208, PlateWidthPixels = 85 },
// new FrameData { FrameID = 60192565, PlatePosX = 680, PlatePosY = 187, PlateWidthPixels = 81 },
// new FrameData { FrameID = 60192566, PlatePosX = 648, PlatePosY = 167, PlateWidthPixels = 78 },
// new FrameData { FrameID = 60192567, PlatePosX = 617, PlatePosY = 149, PlateWidthPixels = 76 },
// new FrameData { FrameID = 60192568, PlatePosX = 588, PlatePosY = 132, PlateWidthPixels = 75 },
// new FrameData { FrameID = 60192569, PlatePosX = 561, PlatePosY = 100, PlateWidthPixels = 70 },
// new FrameData { FrameID = 60192570, PlatePosX = 535, PlatePosY = 85, PlateWidthPixels = 72 },
// new FrameData { FrameID = 60192572, PlatePosX = 488, PlatePosY = 70, PlateWidthPixels = 69 },
// new FrameData { FrameID = 60192573, PlatePosX = 466, PlatePosY = 55, PlateWidthPixels = 67 }
//};
//double Spd = EstimateSpeed(frames);
//AddToActionsList("Estimated Speed: " + Spd.ToString("F2") + " MPH");
StatsExcel excelExporter = new();
excelExporter.ExportDatabaseToExcel();
// FakeCamera fakeCamera = new FakeCamera(80); // Create an instance of FakeCamera
// //CamOnTest.IP = CbBxFoundCams.Text;
// _ = fakeCamera.StartAsync(CAMTYPE.BAD).ContinueWith(task =>
// {
// //Network.Initialize("developer", "Pass123");
// if (task.IsFaulted)
// {
// AddToActionsList("Error starting FakeCamera: " + task.Exception?.Message);
// }
// else
// {
// AddToActionsList($"FakeCamera started successfully. IP: {fakeCamera}", false);
// }
// });
// await Task.Delay(3000); // Wait for server to start
// CbBxFoundCams.Text = "localhost"; // Should force update in creds an network reinit
// CmBoFoundCams_TextChanged(sender, e);
// CbBxCameraType.SelectedIndex = CbBxCameraType.Items.Count - 1; // Selects AB12CD as model number
// await Task.Delay(3000); // Wait for server to start
//BtnPreTest_Click(sender, e);
double Spd = EstimateSpeed(frames);
AddToActionsList("Estimated Speed: " + Spd.ToString("F2") + " MPH");
stopWatchTest.Stop();
AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff"));
//AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff"));
}
}
}