Now the SQLITE database is operationnal and is fed with driver infos

This commit is contained in:
2023-05-17 15:23:19 +02:00
parent ac65c7b4f3
commit e727dc9301
5 changed files with 230 additions and 71 deletions

View File

@@ -30,8 +30,9 @@
{
this.btnSettings = new System.Windows.Forms.Button();
this.tbxResult = new System.Windows.Forms.TextBox();
this.btnUpdate = new System.Windows.Forms.Button();
this.btnStartDecoding = new System.Windows.Forms.Button();
this.pbxResult = new System.Windows.Forms.PictureBox();
this.btnStopUpdating = new System.Windows.Forms.Button();
((System.ComponentModel.ISupportInitialize)(this.pbxResult)).BeginInit();
this.SuspendLayout();
//
@@ -54,15 +55,15 @@
this.tbxResult.Size = new System.Drawing.Size(310, 249);
this.tbxResult.TabIndex = 1;
//
// btnUpdate
// btnStartDecoding
//
this.btnUpdate.Location = new System.Drawing.Point(120, 12);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Size = new System.Drawing.Size(102, 53);
this.btnUpdate.TabIndex = 2;
this.btnUpdate.Text = "Update";
this.btnUpdate.UseVisualStyleBackColor = true;
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
this.btnStartDecoding.Location = new System.Drawing.Point(120, 12);
this.btnStartDecoding.Name = "btnStartDecoding";
this.btnStartDecoding.Size = new System.Drawing.Size(102, 53);
this.btnStartDecoding.TabIndex = 2;
this.btnStartDecoding.Text = "Start";
this.btnStartDecoding.UseVisualStyleBackColor = true;
this.btnStartDecoding.Click += new System.EventHandler(this.btnUpdate_Click);
//
// pbxResult
//
@@ -73,13 +74,24 @@
this.pbxResult.TabIndex = 3;
this.pbxResult.TabStop = false;
//
// btnStopUpdating
//
this.btnStopUpdating.Location = new System.Drawing.Point(228, 12);
this.btnStopUpdating.Name = "btnStopUpdating";
this.btnStopUpdating.Size = new System.Drawing.Size(102, 53);
this.btnStopUpdating.TabIndex = 4;
this.btnStopUpdating.Text = "Stop";
this.btnStopUpdating.UseVisualStyleBackColor = true;
this.btnStopUpdating.Click += new System.EventHandler(this.btnStopUpdating_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 335);
this.Controls.Add(this.btnStopUpdating);
this.Controls.Add(this.pbxResult);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnStartDecoding);
this.Controls.Add(this.tbxResult);
this.Controls.Add(this.btnSettings);
this.Name = "Form1";
@@ -96,8 +108,9 @@
private System.Windows.Forms.Button btnSettings;
private System.Windows.Forms.TextBox tbxResult;
private System.Windows.Forms.Button btnUpdate;
private System.Windows.Forms.Button btnStartDecoding;
private System.Windows.Forms.PictureBox pbxResult;
private System.Windows.Forms.Button btnStopUpdating;
}
}

View File

@@ -15,35 +15,15 @@ namespace Test_Merge
{
Reader Reader = null;
F1TVEmulator Emulator = null;
private bool cancelRequested = false;
public Form1()
{
InitializeComponent();
}
public async void RefreshUI()
{
if (Emulator != null && Reader != null)
{
btnSettings.Enabled = false;
btnUpdate.Enabled = false;
Stopwatch sw = new Stopwatch();
sw.Start();
Bitmap screen = Emulator.Screenshot();
screen.Save("SCREEEEEEEEN.png");
Reader.ChangeImage(screen);
string result = await Reader.Decode(Reader.MainZones, Reader.Drivers);
sw.Stop();
tbxResult.Text = "";
tbxResult.Text = "Decoding done in :" + sw.ElapsedMilliseconds + "ms"+Environment.NewLine;
tbxResult.Text += result;
pbxResult.Image = screen;
btnSettings.Enabled = true;
btnUpdate.Enabled = true;
}
}
private async void btnSettings_Click(object sender, EventArgs e)
{
@@ -74,13 +54,42 @@ namespace Test_Merge
Reader = new Reader(configFile, Emulator.Screenshot(), true);
}
private void btnUpdate_Click(object sender, EventArgs e)
private async void btnUpdate_Click(object sender, EventArgs e)
{
btnUpdate.Enabled = false;
RefreshUI();
btnUpdate.Enabled = true;
}
cancelRequested = false;
if (Emulator != null && Reader != null)
{
// Disable UI controls to prevent re-entrancy
btnStartDecoding.Enabled = false;
btnStopUpdating.Enabled = true;
btnSettings.Enabled = false;
while (!cancelRequested)
{
// Start the time-consuming task on a separate thread
await Task.Run(async () =>
{
Stopwatch sw = new Stopwatch();
sw.Start();
Bitmap screen = Emulator.Screenshot();
screen.Save("SCREEEEEEEEN.png");
Reader.ChangeImage(screen);
string result = await Reader.Decode(Reader.MainZones, Reader.Drivers);
sw.Stop();
// Task completed
Invoke((MethodInvoker)delegate
{
DisplayResults(result, sw, screen);
});
});
}
// Re-enable UI controls
btnStartDecoding.Enabled = true;
btnStopUpdating.Enabled = false;
btnSettings.Enabled = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (Emulator != null)
@@ -88,5 +97,18 @@ namespace Test_Merge
Emulator.Stop();
}
}
private void DisplayResults(string result,Stopwatch sw,Bitmap screen)
{
tbxResult.Text = "";
tbxResult.Text = "Decoding done in :" + sw.ElapsedMilliseconds + "ms" + Environment.NewLine;
tbxResult.Text += result;
pbxResult.Image = screen;
}
private void btnStopUpdating_Click(object sender, EventArgs e)
{
// Set the cancellation flag
cancelRequested = true;
}
}
}

View File

@@ -388,7 +388,7 @@ namespace Test_Merge
}
inputBitmap.UnlockBits(bmpData);
return Color.FromArgb(255, Convert.ToInt32((float)totR / (float)totPixels), Convert.ToInt32((float)totG / (float)totPixels), Convert.ToInt32((float)totB / (float)totPixels));
return Color.FromArgb(255,Math.Min(Convert.ToInt32((float)totR / (float)totPixels),255), Math.Min(Convert.ToInt32((float)totG / (float)totPixels),255), Math.Min(Convert.ToInt32((float)totB / (float)totPixels),255));
}
/// <summary>
/// This method simply inverts all the colors in a Bitmap

View File

@@ -23,23 +23,32 @@ namespace Test_Merge
public List<Zone> MainZones;
private SqliteStorage _storage;
private List<DriverData>[] DriverDataLogs = new List<DriverData>[NUMBER_OF_DRIVERS];
private int[] DriverLaps = new int[NUMBER_OF_DRIVERS];
public SqliteStorage Storage { get => _storage; private set => _storage = value; }
public Reader(string configFile, Bitmap image, bool loadOCR = true)
{
Storage = new SqliteStorage();
MainZones = Load(image, configFile, ref Drivers, loadOCR);
}
/// <summary>
/// Method that reads the JSON config file and create all the Zones and Windows
/// </summary>
/// <param name="imageNumber">The image #id on wich you want to create the zones on</param>
public static List<Zone> Load(Bitmap image, string configFilePath, ref List<string> driverListToFill, bool LoadOCR)
public List<Zone> Load(Bitmap image, string configFilePath, ref List<string> driverListToFill, bool LoadOCR)
{
List<Zone> mainZones = new List<Zone>();
Bitmap fullImage = image;
Zone mainZone;
for (int i = 0; i < NUMBER_OF_DRIVERS; i++)
{
DriverDataLogs[i] = new List<DriverData>();
DriverLaps[i] = 0;
}
try
{
string jsonString = File.ReadAllText(configFilePath);
@@ -149,7 +158,7 @@ namespace Test_Merge
sec1El.GetProperty("y").GetInt32(),
sec1El.GetProperty("width").GetInt32(),
sec1El.GetProperty("height").GetInt32()),
1,LoadOCR);
1, LoadOCR);
//Sector2
JsonElement sec2El = windowElement.GetProperty("Sector2");
@@ -187,7 +196,9 @@ namespace Test_Merge
JsonElement driversElement = main.GetProperty("Drivers");
foreach (JsonElement driverElement in driversElement.EnumerateArray())
{
driverListToFill.Add(driverElement.GetString());
string driverName = driverElement.GetString();
driverListToFill.Add(driverName);
Storage.AddDriver(driverName);
}
mainZones.Add(mainZone);
@@ -204,7 +215,7 @@ namespace Test_Merge
foreach (Zone z in mainZones[0].Zones)
{
driverID++;
z.ZoneImage.Save("LoadedDriver"+driverID+".png");
z.ZoneImage.Save("LoadedDriver" + driverID + ".png");
}
return mainZones;
}
@@ -218,8 +229,6 @@ namespace Test_Merge
string result = "";
List<DriverData> mainResults = new List<DriverData>();
Storage = new SqliteStorage();
//Decode
for (int mainZoneId = 0; mainZoneId < mainZones.Count; mainZoneId++)
{
@@ -227,12 +236,40 @@ namespace Test_Merge
{
case 0:
//Main Zone
//Parallel.ForEach(mainZones[mainZoneId].Zones,async (z) =>
foreach (Zone z in mainZones[mainZoneId].Zones)
for (int i = 0; i < mainZones[mainZoneId].Zones.Count; i++)
{
mainResults.Add(await z.Decode(new List<string>(drivers)));
}//);
//MessageBox.Show("Finished");
DriverData data = await mainZones[mainZoneId].Zones[i].Decode(new List<string>(drivers));
mainResults.Add(data);
DriverDataLogs[i].Add(data);
if (data.Position != -1 && DriverDataLogs[i].Count > 1)
{
//Checking if its a new lap
//If the third sector is filled but it was'nt the last time, then it means that a new Lap has been started
if (
DriverDataLogs[i][DriverDataLogs[i].Count - 1].Sector3 != 0
&& DriverDataLogs[i][DriverDataLogs[i].Count - 2].Sector3 == 0)
{
DriverData stats = DriverDataLogs[i][DriverDataLogs[i].Count - 2];
DriverLaps[i]++;
Storage.AddDriverStat(stats, DriverLaps[i]);
}
//Checking if its a pitstop
//If the tyre is a different counpound or if the tyre is much fresher than the older one then it must be because the driver had a pitstop
//BE CAREFULL the last if is here because the OCR is quite weak with the number 4
//if (data.CurrentTyre.Coumpound != DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.Coumpound
//|| data.CurrentTyre.NumberOfLaps != DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps
//&& data.CurrentTyre.NumberOfLaps < DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps
//&& DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps != 3)
//Forget this the best way to know if a tyre has been changed is if the number of laps is zero
if(data.CurrentTyre.Coumpound != Tyre.Type.Undefined && data.CurrentTyre.NumberOfLaps == 0 && DriverDataLogs[i][DriverDataLogs[i].Count - 2].CurrentTyre.NumberOfLaps != 0)
{
Storage.AddPitstop(data.Name, DriverLaps[i] - 1, data.CurrentTyre.Coumpound.ToString());
//Driver laps -1 because it would take AT LEAST one lap for this program to detect a pitstop
}
}
DriverDataLogs[i].Add(data);
}
break;
//Next there could be a Title Zone and TrackInfoZone
}

View File

@@ -5,6 +5,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
using System.IO;
using System.Windows.Forms;
namespace Test_Merge
{
@@ -13,6 +14,8 @@ namespace Test_Merge
private const string DATABASE_FOLDER = "./Data";
private const string DATABASE_FILE = "/database.sqlite";
private const string CONNECTION_STRING = "Data Source=" + DATABASE_FOLDER + DATABASE_FILE + ";Version=3;";
private SQLiteConnection Connection;
public SqliteStorage()
{
Load();
@@ -29,36 +32,34 @@ namespace Test_Merge
else
{
//We are not using the existing DataBase
File.Delete(DATABASE_FOLDER+DATABASE_FILE);
File.Delete(DATABASE_FOLDER + DATABASE_FILE);
}
using (var connection = new SQLiteConnection(CONNECTION_STRING))
{
connection.Open();
Connection = new SQLiteConnection(CONNECTION_STRING);
Connection.Open();
//Create the drivers table
string createDriversTableQuery = @"CREATE TABLE IF NOT EXISTS Drivers
//Create the drivers table
string createDriversTableQuery = @"CREATE TABLE IF NOT EXISTS Drivers
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
Name VARCHAR NOT NULL);";
using (var command = new SQLiteCommand(createDriversTableQuery, connection))
{
command.ExecuteNonQuery();
}
using (var command = new SQLiteCommand(createDriversTableQuery, Connection))
{
command.ExecuteNonQuery();
}
//Create the drivers table
string createPitstopTableQuery = @"CREATE TABLE Pitstops
//Create the drivers table
string createPitstopTableQuery = @"CREATE TABLE Pitstops
(Lap INTEGER NOT NULL,
DriverID INTEGER NOT NULL,
Tyre VARCHAR,
PRIMARY KEY (Lap,DriverID));";
using (var command = new SQLiteCommand(createPitstopTableQuery, connection))
{
command.ExecuteNonQuery();
}
using (var command = new SQLiteCommand(createPitstopTableQuery, Connection))
{
command.ExecuteNonQuery();
}
//Create the stats
string createStatsTableQuery = @"CREATE TABLE IF NOT EXISTS Stats
//Create the stats
string createStatsTableQuery = @"CREATE TABLE IF NOT EXISTS Stats
(Lap INTEGER NOT NULL,
DriverID INTEGER NOT NULL,
Tyre VARCHAR NOT NULL,
@@ -69,10 +70,96 @@ namespace Test_Merge
GapToLeader INTEGER NOT NULL,
Position INTEGER NOT NULL,
PRIMARY KEY (Lap, DriverID));";
using (var command = new SQLiteCommand(createStatsTableQuery, connection))
using (var command = new SQLiteCommand(createStatsTableQuery, Connection))
{
command.ExecuteNonQuery();
}
}
public void AddDriver(string name)
{
string insertQuery = "INSERT INTO Drivers (Name) VALUES (@name);";
using (var command = new SQLiteCommand(insertQuery,Connection))
{
command.Parameters.AddWithValue("@Name",name);
try
{
command.ExecuteNonQuery();
}
catch
{
//MessageBox.Show("An error has occured while trying to insert a new driver into de Database");
}
}
}
private int GetDriverID(string name)
{
string selectQuery = "SELECT ID FROM Drivers where Name LIKE @driverName";
int result = 0;
using (var command = new SQLiteCommand(selectQuery,Connection))
{
command.Parameters.AddWithValue("@driverName",name);
try
{
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
result = reader.GetInt32(0);
}
}
}
catch
{
//MessageBox.Show("There has been an error while trying to retrieve the ID of a Driver from the database");
}
}
return result;
}
public void AddPitstop(string driverName,int lap,string tyre)
{
string insertQuery = "INSERT INTO Pitstops (Lap,DriverID,Tyre) VALUES (@Lap,@DriverID,@Tyre)";
using (var command = new SQLiteCommand(insertQuery,Connection))
{
command.Parameters.AddWithValue("@Lap",lap);
command.Parameters.AddWithValue("@DriverID",GetDriverID(driverName));
command.Parameters.AddWithValue("@Tyre",tyre);
try
{
command.ExecuteNonQuery();
}
catch
{
//MessageBox.Show("An error has occured while trying to insert a new pitstop into the DB" + Environment.NewLine + "Request :"+ command.ToString());
}
}
}
public void AddDriverStat(DriverData data,int lap)
{
string insertQuery = "INSERT INTO Stats (Lap,DriverID,Tyre,LapTime,Sector1,Sector2,Sector3,GapToLeader,Position) VALUES (@Lap,@DriverID,@Tyre,@LapTime,@Sector1,@Sector2,@Sector3,@GapToLeader,@Position);";
using (var command = new SQLiteCommand(insertQuery,Connection))
{
command.Parameters.AddWithValue("@Lap",lap);
command.Parameters.AddWithValue("@DriverID",GetDriverID(data.Name));
command.Parameters.AddWithValue("@Tyre",data.CurrentTyre.Coumpound.ToString());
command.Parameters.AddWithValue("@LapTime",data.LapTime);
command.Parameters.AddWithValue("@Sector1",data.Sector1);
command.Parameters.AddWithValue("@Sector2", data.Sector2);
command.Parameters.AddWithValue("@Sector3", data.Sector3);
command.Parameters.AddWithValue("@GapToLeader", data.GapToLeader);
command.Parameters.AddWithValue("@Position", data.Position);
try
{
command.ExecuteNonQuery();
}
catch
{
//MessageBox.Show("An error has occured while trying to insert infos about a driver");
}
}
}
}