Compare commits

..

9 Commits

14 changed files with 314 additions and 142 deletions

41
AiQ_GUI.Designer.cs generated
View File

@@ -144,6 +144,8 @@ namespace AiQ_GUI
BtnZoom8000 = new Button();
BtnZoomWide = new Button();
TabSettings = new TabPage();
BtnUploadWonwooSetIR = new Button();
BtnUploadWonwooSetOV = new Button();
BtnAdminStart = new Button();
BtnFirewall = new Button();
TabImages = new TabPage();
@@ -587,6 +589,7 @@ namespace AiQ_GUI
BtnTest.TabIndex = 189;
BtnTest.Text = "Test";
BtnTest.UseVisualStyleBackColor = false;
BtnTest.Visible = false;
BtnTest.Click += BtnTest_Click;
//
// PicBxIRF2
@@ -1835,6 +1838,8 @@ namespace AiQ_GUI
// TabSettings
//
TabSettings.BackColor = Color.FromArgb(39, 37, 55);
TabSettings.Controls.Add(BtnUploadWonwooSetIR);
TabSettings.Controls.Add(BtnUploadWonwooSetOV);
TabSettings.Controls.Add(BtnAdminStart);
TabSettings.Controls.Add(BtnFirewall);
TabSettings.Controls.Add(PanelSettings);
@@ -1845,6 +1850,40 @@ namespace AiQ_GUI
TabSettings.TabIndex = 3;
TabSettings.Text = "Settings";
//
// BtnUploadWonwooSetIR
//
BtnUploadWonwooSetIR.BackColor = Color.FromArgb(70, 65, 80);
BtnUploadWonwooSetIR.FlatAppearance.BorderColor = Color.FromArgb(70, 65, 80);
BtnUploadWonwooSetIR.FlatAppearance.BorderSize = 0;
BtnUploadWonwooSetIR.FlatStyle = FlatStyle.Flat;
BtnUploadWonwooSetIR.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold);
BtnUploadWonwooSetIR.ForeColor = SystemColors.Control;
BtnUploadWonwooSetIR.Location = new Point(210, 304);
BtnUploadWonwooSetIR.Margin = new Padding(4, 3, 4, 3);
BtnUploadWonwooSetIR.Name = "BtnUploadWonwooSetIR";
BtnUploadWonwooSetIR.Size = new Size(180, 49);
BtnUploadWonwooSetIR.TabIndex = 244;
BtnUploadWonwooSetIR.Text = "Upload Wonwoo Settings IR";
BtnUploadWonwooSetIR.UseVisualStyleBackColor = false;
BtnUploadWonwooSetIR.Click += UploadWonwooSetIR_Click;
//
// BtnUploadWonwooSetOV
//
BtnUploadWonwooSetOV.BackColor = Color.FromArgb(70, 65, 80);
BtnUploadWonwooSetOV.FlatAppearance.BorderColor = Color.FromArgb(70, 65, 80);
BtnUploadWonwooSetOV.FlatAppearance.BorderSize = 0;
BtnUploadWonwooSetOV.FlatStyle = FlatStyle.Flat;
BtnUploadWonwooSetOV.Font = new Font("Segoe UI Semibold", 10F, FontStyle.Bold);
BtnUploadWonwooSetOV.ForeColor = SystemColors.Control;
BtnUploadWonwooSetOV.Location = new Point(19, 304);
BtnUploadWonwooSetOV.Margin = new Padding(4, 3, 4, 3);
BtnUploadWonwooSetOV.Name = "BtnUploadWonwooSetOV";
BtnUploadWonwooSetOV.Size = new Size(181, 49);
BtnUploadWonwooSetOV.TabIndex = 243;
BtnUploadWonwooSetOV.Text = "Upload Wonwoo Settings OV";
BtnUploadWonwooSetOV.UseVisualStyleBackColor = false;
BtnUploadWonwooSetOV.Click += UploadWonwooSetOV_Click;
//
// BtnAdminStart
//
BtnAdminStart.BackColor = Color.FromArgb(70, 65, 80);
@@ -2210,5 +2249,7 @@ namespace AiQ_GUI
private Button BtnAdminStart;
private Button SetGodModeAll;
private Button BtnFactoryDefault;
private Button BtnUploadWonwooSetOV;
private Button BtnUploadWonwooSetIR;
}
}

View File

@@ -1,6 +1,5 @@
using Newtonsoft.Json;
using System.ComponentModel;
using System.Data.OleDb;
using System.Diagnostics;
using System.Reflection;
@@ -20,6 +19,8 @@ namespace AiQ_GUI
private List<CancellationTokenSource> soakCtsList = [];
private List<Task> soakTasks = [];
public const string GoogleDrivePath = @"G:\Shared drives\MAV Production GUI's\AiQ\GUI's\";
// Colours
public static readonly Color BtnColour = Color.FromArgb(70, 65, 80);
public static readonly Color TxBxColour = Color.FromArgb(53, 51, 64);
@@ -220,73 +221,10 @@ namespace AiQ_GUI
// 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, "Failed due to action box text and/or red label");// 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(Access.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, string IsRMA, int RMA)
{
using OleDbConnection conn = new(Access.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],[IsRMA],[RMA])
VALUES (?, ?, ?, ?, ?, ?)";
using OleDbCommand cmd = new(sql, conn);
// OleDb uses positional parameters — order must match the VALUES list above
cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = DateTime.Now });
cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar, Value = model });
cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar, Value = redVal });
cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar, Value = actVal });
cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Boolean, Value = IsRMA });
cmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar, Value = RMA });
cmd.ExecuteNonQuery();
}
private async void BtnPreTest_Click(object sender, EventArgs e)
{
@@ -335,8 +273,8 @@ namespace AiQ_GUI
await AllocateSerial();
else if (GoogleAPI.UpdateSpreadSheetRePreTest(CameraAccessInfo.SpreadsheetID, Vers) != "OK") // If rerun might be different values so update SS
AddToActionsList("Failed to write to spreadsheet, please check manually");
// else if (Excel.UpdateSpreadSheetPreTest(CameraAccessInfo.SpreadsheetID, Vers, CamOnTest.GetCamDesc(), CamOnTest.Model) != "OK")
// AddToActionsList("Failed to write to spreadsheet, please check manually");
// else if (Excel.UpdateSpreadSheetPreTest(CameraAccessInfo.SpreadsheetID, Vers, CamOnTest.GetCamDesc(), CamOnTest.Model) != "OK")
// AddToActionsList("Failed to write to spreadsheet, please check manually");
}
else // No serial or model so allocate one
await AllocateSerial();
@@ -368,7 +306,7 @@ namespace AiQ_GUI
{
// Turn off God mode
string[,] GOD_JSON = { { "propGodMode", "false" } };
string IntConf = await FlexiAPI.HTTP_Update("Internal Config", CamOnTest.IP, GOD_JSON);
string IntConf = await FlexiAPI.HTTP_Update("GLOBAL--FlexiApplication", CamOnTest.IP, GOD_JSON);
if (!IntConf.Contains("\"propGodMode\": {\"value\": \"false\", \"datatype\": \"boolean\"},"))
AddToActionsList("Could not turn off God mode");
@@ -461,15 +399,14 @@ namespace AiQ_GUI
List<object> oblistCD = [CamOnTest.Model, FullFailureValues];
GoogleAPI.WriteToSS(oblistCD, "'Approval'!C" + nextRow + ":D" + nextRow, GoogleAPI.spreadsheetId_ModelInfo);
//await Teams.SendMssg(Convert.ToString(nextRow), CbBxUserName.Text);
GoogleAPI.EmailApproval(Convert.ToString(nextRow), CbBxUserName.Text);
await Teams.SendMssg(Convert.ToString(nextRow), CbBxUserName.Text);
//GoogleAPI.EmailApproval(Convert.ToString(nextRow), CbBxUserName.Text);
string Approved = "";
while (Approved != "TRUE")
{
await Task.Delay(1000);
values = GoogleAPI.service.Spreadsheets.Values.Get(GoogleAPI.spreadsheetId_ModelInfo, "'Approval'!B" + nextRow).Execute().Values;
if (values?.Count > 0)
@@ -501,14 +438,11 @@ 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
{
Access.Stats("Pre Tests Passed", CamOnTest.Model);
}
else
{
Access.Stats("RMA Pre Tests Passed", CamOnTest.Model);
}
if (await DisplayQuestion("Test passed, restart?"))
Helper.RestartApp();
@@ -523,13 +457,9 @@ namespace AiQ_GUI
Logging.LogMessage("Pre Test Failed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{
Access.Stats(["Pre Tests Failed", ErrMssg], CamOnTest.Model);
}
else
{
Access.Stats("RMA Pre Tests Failed", CamOnTest.Model);
}
string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls
.OfType<Label>()
@@ -539,17 +469,6 @@ namespace AiQ_GUI
Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{
Stats(["Pre Tests Failed", ErrMssg]);
StatsDiags(RedLbls, RhTxBxActions.Text, "FALSE", CamOnTest.RMANum);
}
else
{
Stats("RMA Pre Tests Failed");
StatsDiags(RedLbls, RhTxBxActions.Text, "TRUE", CamOnTest.RMANum);
}
if (await DisplayQuestion("Test failed, restart?" + Environment.NewLine + "See Actions textbox for details."))
Helper.RestartApp();
}
@@ -852,7 +771,7 @@ namespace AiQ_GUI
private async void BtnFindCams_Click(object sender, EventArgs e)
{
CbBxFoundCams.Text = "Searching";
BtnFindCams.Enabled = BtnSetAll211.Enabled = BtnSoak.Enabled = BtnSet211.Enabled = BtnSetGodMode.Enabled = BtnUploadBlob.Enabled = SetGodModeAll.Enabled = BtnFactoryDefault.Enabled = false;
BtnFindCams.Enabled = BtnSetAll211.Enabled = BtnSoak.Enabled = BtnSet211.Enabled = BtnSetGodMode.Enabled = BtnUploadBlob.Enabled = SetGodModeAll.Enabled = BtnFactoryDefault.Enabled = BtnUploadWonwooSetIR.Enabled = BtnUploadWonwooSetOV.Enabled = false;
BtnSetGodMode.BackColor = BtnUploadBlob.BackColor = BtnFactoryDefault.BackColor = BtnSetAll211.BackColor = BtnColour;
CbBxFoundCams.Items.Clear();
soakCameraList.Clear();
@@ -968,7 +887,7 @@ namespace AiQ_GUI
else
{
CbBxFoundCams.BackColor = Color.Red;
BtnSecret.Enabled = BtnOpenWebpage.Enabled = BtnSet211.Enabled = BtnSetGodMode.Enabled = false;
BtnSecret.Enabled = BtnOpenWebpage.Enabled = BtnSet211.Enabled = BtnSetGodMode.Enabled = BtnUploadWonwooSetIR.Enabled = BtnUploadWonwooSetOV.Enabled = false;
}
TestStartConditions();
@@ -1007,7 +926,7 @@ namespace AiQ_GUI
try
{
await FlexiAPI.HTTP_Update("Internal Config", CamOnTest.IP, GOD_JSON);
await FlexiAPI.HTTP_Update("GLOBAL--FlexiApplication", CamOnTest.IP, GOD_JSON);
BtnSetGodMode.Text = newGodModeValue == "true" ? "Set God Mode Off" : "Set God Mode On";
BtnSetGodMode.BackColor = Color.Green;
}
@@ -1053,7 +972,7 @@ namespace AiQ_GUI
if (CbBxFoundCams.BackColor != BtnColour || CbBxFoundCams.Text.Contains("Found"))
TSC = SetInvalid("Select camera IP address.");
else
BtnOpenWebpage.Enabled = BtnSet211.Enabled = BtnSetGodMode.Enabled = BtnZoom8000.Enabled = BtnZoomWide.Enabled = true; // Allow user to go to camera webpage & change DHCP/211
BtnOpenWebpage.Enabled = BtnSet211.Enabled = BtnSetGodMode.Enabled = BtnZoom8000.Enabled = BtnZoomWide.Enabled = BtnUploadWonwooSetIR.Enabled = BtnUploadWonwooSetOV.Enabled = true; // Allow user to go to camera webpage & change DHCP/211
// Name chosen
if (CbBxUserName.Text == "Select Operator to Begin Test" || CbBxUserName.Text.Length < 2)
@@ -1253,7 +1172,7 @@ namespace AiQ_GUI
try
{
Network.Initialize("developer", SCL.DevPass); // Ensure network is initialized to the right camera
string RESP = await FlexiAPI.HTTP_Update("Internal Config", SCL.IP, GOD_JSON);
string RESP = await FlexiAPI.HTTP_Update("GLOBAL--FlexiApplication", SCL.IP, GOD_JSON);
Instance.AddToActionsList($"Setting God mode for camera {SCL.IP} to {newGodModeValue}", false);
}
catch (Exception ex)
@@ -1570,6 +1489,16 @@ namespace AiQ_GUI
Process.Start(psi);
}
private async void UploadWonwooSetOV_Click(object sender, EventArgs e)
{
await FlexiAPI.UploadWonwooSet(CbBxFoundCams.Text, false); // false = Colour
}
private async void UploadWonwooSetIR_Click(object sender, EventArgs e)
{
await FlexiAPI.UploadWonwooSet(CbBxFoundCams.Text, true); // true = Infrared
}
private void TxBxSerialPrint_Click(object sender, EventArgs e)
{
if (TxBxSerialPrint.Text == "K ") // If at default then remove the dashes ready for user to put in number
@@ -1646,7 +1575,7 @@ namespace AiQ_GUI
CancellationTokenSource cts = new();
soakCtsList.Add(cts);
soakTasks.Add(SoakTest.StartSoak(SCL, cts.Token));
await Task.Delay(5000);
await Task.Delay(10000);
}
}
else
@@ -1657,14 +1586,44 @@ namespace AiQ_GUI
cts.Cancel();
soakCtsList.Clear();
soakTasks.Clear();
int i = soakCameraList.Count + 1; // Add 1 for 211 itself staying in the list
foreach (Camera SCL in soakCameraList) // Reset all cameras that were being soaked to default module settings
string[,] Network_JSON = { { "propDHCP", "false" }, { "propHost", "192.168.1.211" }, { "propNetmask", "255.255.255.0" }, { "propGateway", "192.168.1.1" } };
string[,] GOD_JSON = { { "propGodMode", "false" } };
foreach (Camera SCL in soakCameraList.Where(c => c.IsChecked)) // only checked cameras
{
if (!SCL.IsChecked)
continue;
try
{
AddToActionsList($"Setting 211 & God Mode off for camera {SCL.IP}", false);
Network.Initialize("developer", SCL.DevPass); // Ensure network is initialized to the right camera
await CameraModules.FactoryResetModules(SCL.IP); // Reset camera modules
Network.Initialize("developer", SCL.DevPass); // Ensure network is initialized to the right camera, cannot be done in soak test finally becuase of this.
await CameraModules.FactoryResetModules(SCL.IP);
string GOD = await FlexiAPI.HTTP_Update("GLOBAL--FlexiApplication", SCL.IP, GOD_JSON);
if (GOD.Contains("Error"))
throw new Exception("Could not set God mode off");
// Update GLOBAL--NetworkConfig with fixed IP and turn off DHCP
await FlexiAPI.HTTP_Update("GLOBAL--NetworkConfig", SCL.IP, Network_JSON);
i--; // Decriment count becuase they will stack into 211
}
catch (Exception ex)
{
AddToActionsList("Failed to set all cameras to 211 and god mode off. Reason: " + ex.Message); // In case non AiQ's get caught up
}
}
await Task.Delay(5000); // Wait for 5 seconds to allow the camera to restart
IList<string> FoundCams = await Network.SearchForCams(); // Have to check via broadcast becuase Ping sometimes fails across subnets
if ((FoundCams.Count == i && FoundCams.Contains("192.168.1.211")) || FoundCams.Count == 1)
{
AddToActionsList("All cameras successfully changed to 211.", false);
}
else
{
AddToActionsList($"Some cameras failed: Found {FoundCams.Count}, expected {i}.", true);
}
}
}
@@ -1750,7 +1709,7 @@ namespace AiQ_GUI
{
string apiUrl = $"http://{cam.IP}/upload/software-update/2";
Network.Initialize("developer", cam.DevPass);
await Task.Delay(1000); // Gives extra time to allow for Network to initialize
AddToActionsList($"Uploading to {cam.IP}...", false);
string result = await FlexiAPI.SendBlobFileUpload(apiUrl, fileToUpload, fileName);
@@ -1788,8 +1747,12 @@ namespace AiQ_GUI
{
Stopwatch stopWatchTest = Stopwatch.StartNew();
StatsExcel excelExporter = new();
excelExporter.ExportDatabaseToExcel();
//StatsExcel excelExporter = new();
//excelExporter.ExportDatabaseToExcel();
string ans = await FlexiAPI.HTTP_Fetch("GLOBAL--Device", "192.168.0.71");
AddToActionsList(ans);
// /api/config-ids - For getting all available config IDs
stopWatchTest.Stop();
AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff"));

View File

@@ -123,6 +123,9 @@
<metadata name="ToolTipClipboard.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>159, 17</value>
</metadata>
<metadata name="ToolTipAvailable.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="TimerDDC.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>690, 19</value>
</metadata>

View File

@@ -16,7 +16,7 @@
<Product>AiQ GUI</Product>
<Authors>MAV Systems Ltd</Authors>
<PackageId>AiQ GUI</PackageId>
<Version>4.0.0</Version>
<Version>4.4.0</Version>
<Description>A GUI to control and test the AiQ</Description>
<Copyright>MAV Systems Ltd 2025</Copyright>
<PackageIcon>MAV - Plain - Blue.png</PackageIcon>
@@ -30,10 +30,20 @@
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<Optimize>True</Optimize>
<DefineConstants>$(DefineConstants);_PUBLISH_CHROMEDRIVER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x86'">
<Optimize>True</Optimize>
<DefineConstants>$(DefineConstants);_PUBLISH_CHROMEDRIVER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DefineConstants>$(DefineConstants);_PUBLISH_CHROMEDRIVER</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'">
<DefineConstants>$(DefineConstants);_PUBLISH_CHROMEDRIVER</DefineConstants>
</PropertyGroup>
<ItemGroup>
@@ -51,9 +61,9 @@
<PackageReference Include="PDFsharp-MigraDoc-gdi" Version="6.2.2" />
<PackageReference Include="Selenium.Support" Version="4.38.0" />
<PackageReference Include="Selenium.WebDriver" Version="4.38.0" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="141.0.7390.12200" />
<PackageReference Include="SSH.NET" Version="2025.0.0" />
<PackageReference Include="System.Data.OleDb" Version="9.0.10" />
<PackageReference Include="Selenium.WebDriver.ChromeDriver" Version="142.0.7444.6100" />
<PackageReference Include="SSH.NET" Version="2025.1.0" />
<PackageReference Include="System.Data.OleDb" Version="10.0.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -36,9 +36,9 @@ namespace AiQ_GUI
{
string JSONdata = BuildJsonUpdate(jsonArrayData, ID);
JSONdata = JSONdata.Replace("\"14\"", "14").Replace("\"30\"", "30"); // Fixes & encoding issue
MainForm.Instance.AddToActionsList(JSONdata);
string url = $"http://{IPAddress}/api/update-config";
return await Network.SendHttpRequest(url, HttpMethod.Post, 2, JSONdata);
}
catch (Exception ex)
{
@@ -81,7 +81,7 @@ namespace AiQ_GUI
// Always Infrared as LED's are controlled from infrared page
// Level can be word eg. SAFE or hex eg. 0x0E
string suffix = $"/Infrared/led-controls?power={LEVEL}";
return await APIHTTPRequest(suffix, IPAddress);
return await APIHTTPRequest(suffix, IPAddress, 5);
}
public static async Task<string> SendBlobFileUpload(string url, string filePath, string fileName)
@@ -161,12 +161,13 @@ namespace AiQ_GUI
return null; // If it fails to parse the JSON
}
}
public static async Task<bool> SetVaxtorMinMaxPlate(string IP)
{
try
{
// Build JSON array for Vaxtor min/max plate configuration
string[,] Vaxtor_JSON = { { "propMinCharHeight", "18" }, { "propMinGlobalConfidence", "30" } };
string[,] Vaxtor_JSON = { { "propMinCharHeight", "14" }, { "propMaxCharHeight", "40" }, { "propMinGlobalConfidence", "30" } };
string response = await HTTP_Update("RaptorOCR".Trim(), IP, Vaxtor_JSON);
// Treat "operation was canceled" as a successful apply
@@ -191,8 +192,6 @@ namespace AiQ_GUI
}
}
public static async Task<bool> SetZoomLockOn(string IP)
{
// Set Zoomlock on and if it fails ask user to set it manually
@@ -238,8 +237,7 @@ namespace AiQ_GUI
}
// Check no value is -1 (no plate found) or if the positions are identical (one plate found). If it is then try again 3 times
if (new[] { trim.infraredX, trim.infraredY, trim.colourX, trim.colourY }.Any(value => value == -1)
|| (trim.infraredX == trim.colourX && trim.infraredY == trim.colourY))
if (new[] { trim.infraredX, trim.infraredY, trim.colourX, trim.colourY }.Any(value => value == -1) || (trim.infraredX == trim.colourX && trim.infraredY == trim.colourY))
{
if (RetryCount >= 3)
{
@@ -248,7 +246,7 @@ namespace AiQ_GUI
}
await Task.Delay(5000); // Give 5 second delay for it to see a plate
await SetTrim(IPAddress, LblTxt, RetryCount++);
await SetTrim(IPAddress, LblTxt, RetryCount + 1);
}
int offset = 105;
@@ -279,7 +277,7 @@ namespace AiQ_GUI
return;
}
await Task.Delay(5000); // Give 5 second delay for it to see a plate
await SetTrim(IPAddress, LblTxt, RetryCount++);
await SetTrim(IPAddress, LblTxt, RetryCount + 1);
}
}
@@ -356,11 +354,86 @@ namespace AiQ_GUI
}
// Change network settings to DHCP and restart camera for it to take effect
public async static Task ChangeNetworkToDHCP(string IPAddress)
public async static Task<bool> ChangeNetworkToDHCP(string IPAddress)
{
string[,] TEST_JSON = { { "propDHCP", "true" } }; // Update GLOBAL--NetworkConfig with fixed IP and turn off DHCP
await HTTP_Update("GLOBAL--NetworkConfig", IPAddress, TEST_JSON);
// TODO - Check if this worked, if not return false
string[,] TEST_JSON = { { "propDHCP", "true" } };
await HTTP_Update("GLOBAL--NetworkConfig", IPAddress, TEST_JSON); // Don't care about response because it will fail as it has changed IP.
await Task.Delay(5000); // Wait for 5 seconds to allow the camera to restart
IList<string> FoundCams = await Network.SearchForCams();
if (FoundCams.Contains("192.168.1.211"))
{
MainForm.Instance.AddToActionsList("Could not set camera to DHCP please check camera.");
return false;
}
MainForm.Instance.AddToActionsList("Camera successfully set to DHCP.");
return true;
}
public static async Task UploadWonwooSet(string ipAddress, bool isIR)
{
string fileToUpload = null;
using OpenFileDialog openFileDialog1 = new()
{
InitialDirectory = MainForm.GoogleDrivePath,
Filter = "CSV files (*.csv)|*.csv",
FilterIndex = 0
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
fileToUpload = openFileDialog1.FileName;
else
{
MainForm.Instance.AddToActionsList("File selection cancelled.", false);
return;
}
//Filename validation
string filename = Path.GetFileName(fileToUpload).ToUpper();
if ((isIR && !filename.Contains("IR")) || (!isIR && !filename.Contains("OV")))
{
MainForm.Instance.AddToActionsList($"Incorrect file selected. Expected {(isIR ? "IR" : "OV")} file", false);
return;
}
string[] lines = File.ReadAllLines(fileToUpload);
for (int i = 1; i < lines.Length; i++)
{
string[] parts = lines[i].Split(',').Select(p => p.Trim()).ToArray();
if (parts.Length < 3)
{
MainForm.Instance.AddToActionsList($"Invalid row format at line {i + 1}", false);
continue;
}
string name = parts[0];
string command = parts[1];
string expectedResponse = parts[2];
// VISCA format check
if (!RegexCache.VISCAAPIRegex().IsMatch(command))
{
MainForm.Instance.AddToActionsList($"{name}: Invalid VISCA command ({command})", false);
continue; // do not send it if bad
}
string result = await APIHTTPVISCA(ipAddress, command, isIR);
if (result.Contains(expectedResponse))
MainForm.Instance.AddToActionsList($"{name}: Success ({(isIR ? "IR" : "Colour")})", true);
else
MainForm.Instance.AddToActionsList($"{name}: Unexpected response ({result})", false);
await Task.Delay(150);
}
MainForm.Instance.AddToActionsList($"Upload complete ({(isIR ? "IR" : "Colour")}).", true);
}
}

View File

@@ -1,7 +1,7 @@
{
"cameraName": "AiQ-ANPR-Camera",
"version": "1.6.4",
"revision": "bf16134",
"version": "1.7.1",
"revision": "4b63df5",
"serialNumber": "K1005001",
"modelNumber": "AB12CD",
"MAC": "3C:6D:66:0A:BA:18",

View File

@@ -116,7 +116,7 @@ namespace AiQ_GUI
if (requiresAuth)
{
string authHeader = context.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Basic "))
{
context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"FakeCamera\"");
@@ -293,7 +293,7 @@ namespace AiQ_GUI
{
await HTTPReplySetup(context, "Update successful.", 200, "text/plain");
}
else if (fo.Id == "Internal Config")
else if (fo.Id == "GLOBAL--FlexiApplication")
{
string SerialNumber = "";
string ModelNumber = "";

View File

@@ -297,7 +297,7 @@ namespace AiQ_GUI
}
// Build the MIME message with attachment
using MailMessage mail = new MailMessage();
using MailMessage mail = new();
mail.From = new MailAddress("me");
mail.To.Add("richard.porter@mav-systems.com");
mail.To.Add("bradley.relyea@mav-systems.com");

View File

@@ -23,7 +23,7 @@ namespace AiQ_GUI
DateTime? lastStatsRun = null;
try
{
using (var cmdPeriod = new OleDbCommand("SELECT LastStatsRun FROM UniversalData", conn))
using (OleDbCommand cmdPeriod = new OleDbCommand("SELECT LastStatsRun FROM UniversalData", conn))
{
object res = cmdPeriod.ExecuteScalar();
if (res != null && res != DBNull.Value)
@@ -136,12 +136,12 @@ namespace AiQ_GUI
FROM DiagsStats
WHERE [Date] >= ? AND [Date] < ?";
using (var diagsCmd = new OleDbCommand(diagsQuery, conn))
using (OleDbCommand diagsCmd = new OleDbCommand(diagsQuery, conn))
{
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = monthStart });
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = nextMonth });
using (var diagsAdapter = new OleDbDataAdapter(diagsCmd))
using (OleDbDataAdapter diagsAdapter = new OleDbDataAdapter(diagsCmd))
{
DataTable diagsTable = new();
diagsAdapter.Fill(diagsTable);
@@ -195,7 +195,7 @@ namespace AiQ_GUI
return;
}
using (var tx = conn.BeginTransaction())
using (OleDbTransaction tx = conn.BeginTransaction())
{
try
{

View File

@@ -7,9 +7,9 @@ namespace AiQ_GUI
{
const string webhookUrl = "https://default71bd136a1c65418fb59e927135629c.ac.environment.api.powerplatform.com:443/powerautomate/automations/direct/workflows/b27c5192e83f4f48b20c1b115985b0b3/triggers/manual/paths/invoke/?api-version=1&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=1-eCbYXms6xInRKHwz3tgAcdQ9x7CSjl3Yzw2V_1MlA";
public static async Task SendMssg(string ApprovalRow, string User) // Sometimes You will need to reauthenticate the workflow
public static async Task SendMssg(string ApprovalRow, string User) // Sometimes You will need to reauthenticate the workflow
{
using HttpClient client = new HttpClient();
using HttpClient client = new();
string link = $"https://docs.google.com/spreadsheets/d/1bCcCr4OYqfjmydt6UqtmN4FQETezXmZRSStJdCCcqZM/edit#gid=1931079354&range=A{ApprovalRow}"; // Has to be parsed like this as teams doesnt hyperlink otherwise
@@ -21,7 +21,7 @@ namespace AiQ_GUI
};
string json = JsonConvert.SerializeObject(payload);
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
StringContent content = new(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(webhookUrl, content);
}

View File

@@ -10,7 +10,7 @@ namespace AiQ_GUI
public static HttpClient? SingleHTTPClient;
public static HttpClient Client => SingleHTTPClient ?? throw new InvalidOperationException("Client not initialized.");
public static void Initialize(string username, string password)
public async static void Initialize(string username, string password)
{
HttpClientHandler handler = new()
{
@@ -23,6 +23,21 @@ namespace AiQ_GUI
{
Timeout = TimeSpan.FromSeconds(20)
};
bool UP = false;
int i = 0;
while (!UP)
{
UP = await PingIP("10.10.10.137");
await Task.Delay(500);
if (i >= 5)
{
//MainForm.Instance.AddToActionsList($"Could not initialise new network with USER: {username} & PSWD: {password}");
return; // Try 5 times max
}
i++;
}
}
// Handles get and post to the camera API
@@ -74,6 +89,7 @@ namespace AiQ_GUI
{
const int sendPort = 6666;
const int receivePort = 6667;
const int discoveryTimeoutMs = 1000;
IList<string> FoundCams = [];
byte[] discoveryPacket = [0x50, 0x4f, 0x4c, 0x4c, 0xaf, 0xb0, 0xb3, 0xb3, 0xb6, 0x01, 0xa8, 0xc0, 0x0b, 0x1a, 0x00, 0x00];
@@ -88,9 +104,9 @@ namespace AiQ_GUI
}
using UdpClient receiver = new(receivePort); // Listen for replies on fixed port
receiver.Client.ReceiveTimeout = 750;
receiver.Client.ReceiveTimeout = discoveryTimeoutMs;
DateTime timeout = DateTime.Now.AddMilliseconds(750);
DateTime timeout = DateTime.Now.AddMilliseconds(discoveryTimeoutMs);
try
{
while (DateTime.Now < timeout)

View File

@@ -39,6 +39,47 @@ namespace AiQ_GUI
return elementID;
}
public static void SwitchUser(ChromeDriver driver)
{
try
{
WebDriverWait wait = new(driver, TimeSpan.FromSeconds(10));
// Click "Switch User"
IWebElement switchBtn = wait.Until(d =>
d.FindElement(By.XPath("//*[contains(text(),'Switch User')]"))
);
switchBtn.Click();
// Username
IWebElement userBox = wait.Until(d => d.FindElement(By.Id("username")));
userBox.Clear();
userBox.SendKeys("admin");
// Password
IWebElement passBox = wait.Until(d => d.FindElement(By.Id("password")));
passBox.Clear();
passBox.SendKeys("admin");
// Login button
IWebElement loginBtn = wait.Until(d =>
d.FindElement(By.XPath("//button[contains(normalize-space(text()), 'Login')]"))
);
// Wait until it's clickable manually (no SeleniumExtras)
wait.Until(d => loginBtn.Displayed && loginBtn.Enabled);
loginBtn.Click();
MainForm.Instance.AddToActionsList("Switched user and logged in.");
}
catch (Exception ex)
{
MainForm.Instance.AddToActionsList("SwitchUser failed: " + ex.Message);
}
}
// Attempts to click the web element with the specified ID; refreshes the page and retries once if the initial attempt fails
public static void ClickElementByID(string elementID, ChromeDriver driver, bool tryagain = true)
{
@@ -65,16 +106,39 @@ namespace AiQ_GUI
// Initialises and opens a ChromeDriver with specific options
public static ChromeDriver OpenDriver()
{
ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
chromeDriverService.HideCommandPromptWindow = true;
ChromeOptions options = new();
options.AddArguments("--app=data:,", "--window-size=960,1040", "--window-position=0,0");
options.AddExcludedArgument("enable-automation");
options.AddAdditionalChromeOption("useAutomationExtension", false);
string tempProfile = null;
ChromeDriver driver = new(chromeDriverService, options);
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(5);
return driver;
try
{
ChromeOptions options = new();
options.AddArguments("--app=data:,",
"--window-size=960,1040",
"--window-position=0,0",
"--no-sandbox",
"--incognito",
"--no-first-run",
"--no-default-browser-check",
"--disable-features=BrowserAddPersonFeature,InterestFeedContentSuggestions");
// Use a unique temporary profile to avoid conflicts
tempProfile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
options.AddArguments($"--user-data-dir={tempProfile}");
// manual driver path
string driverPath = @"C:\ProgramData\MAV\AiQ_GUI";
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverPath);
service.HideCommandPromptWindow = true;
ChromeDriver driver = new(service, options);
driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(5);
return driver;
}
catch (Exception ex)
{
MainForm.Instance.AddToActionsList("Failed to create ChromeDriver: " + ex.Message);
throw;
}
}
// Changes the value of a dropdown element by ID, logs the action, and verifies the result using flashline feedback

View File

@@ -18,6 +18,7 @@ namespace AiQ_GUI
try
{
driver = Selenium.OpenDriver();
await Task.Delay(1000); // Small delay to ensure driver is ready
// Keep retrying until connected or cancelled
bool connected = false;
@@ -27,6 +28,7 @@ namespace AiQ_GUI
{
// Attempt initial connection and navigation to setup tab
Selenium.GoToUrl($"http://{CamInfo.IP}", driver);
Selenium.SwitchUser(driver);
Selenium.ClickElementByID("tabSetup", driver);
connected = true;
}