Compare commits

..

26 Commits

Author SHA1 Message Date
e0af20b46d Удаление лишнего 2025-04-04 13:14:41 +03:00
099ec402cf Merge branch 'main' into devVlad 2025-04-04 13:13:16 +03:00
bf037b0870 Исправления 2025-04-04 02:53:00 +03:00
46e296b7c2 Дофига исправлений 2025-04-04 02:12:55 +03:00
b8ff486e5a hi 2025-04-03 20:49:36 +00:00
8dc1e17080 Клининг 2025-04-03 23:45:33 +03:00
71e772a440 Merge pull request 'main' (#5) from main into Sergey
Reviewed-on: #5
2025-04-03 20:41:38 +00:00
e6cb5430ef revert 0ae998f0fbbf7bdd74b7f1dc9649198f0840f426
revert Merge branch 'Sergey' into main
2025-04-03 20:38:44 +00:00
114522ad0a игнор 2025-04-03 20:38:44 +00:00
a74b5d1ab9 игнор 2025-04-03 20:38:44 +00:00
3975f5c6ed Перенос в общую репу 2025-04-03 20:38:44 +00:00
2c08331bbe ненуна тут 2025-04-03 20:38:44 +00:00
215236fa15 Починин Socket 2025-04-03 20:38:44 +00:00
d5e4c08527 игнор 2025-04-03 20:38:44 +00:00
b19fb44822 убивать 2025-04-03 20:38:44 +00:00
e1eb3bd73f игнор 2025-04-03 20:38:44 +00:00
38be80788b игнор 2025-04-03 20:38:44 +00:00
d8deec303a мусор 2025-04-03 20:38:44 +00:00
01023a458e add 2025-04-03 23:32:16 +03:00
6f3c102ad8 revert 0ae998f0fbbf7bdd74b7f1dc9649198f0840f426
revert Merge branch 'Sergey' into main
2025-04-03 20:27:01 +00:00
0ae998f0fb Merge branch 'Sergey' into main 2025-04-03 20:23:35 +00:00
b611a915b6 ццц 2025-04-03 23:18:45 +03:00
b2599c94f8 игнор 2025-04-03 22:59:03 +03:00
ed2719f2b8 игнор 2025-04-03 22:57:46 +03:00
f1921083bb Перенос в общую репу 2025-04-03 22:33:04 +03:00
e1b7f7b8e3 ненуна тут 2025-03-31 20:36:04 +03:00
16 changed files with 963 additions and 1032 deletions

59
.gitignore vendored
View File

@ -1,58 +1,3 @@
# Файлы и папки Visual Studio
*.obj
*.exe
*.pdb
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.cache
*.ilk
*.log
*.sbr
*.scc
*.idb
*.tlog
*.ipch
*.db
# Папки сборки
bin/
obj/
[Bb]in/
[Oo]bj/
Debug/
Release/
x64/
x86/
[Any CPU]/
# Файлы кэша и настройки VS
.vscode/
*.code-workspace
.vs/ .vs/
*.sln.docstates obj/
bin/
# NuGet
packages/
*.nupkg
*.snupkg
# Дополнительные временные файлы
Thumbs.db
*.DS_Store
# Игнорировать файлы резервирования
~$*
# Опционально: игнорировать файлы конфигурации пользователя
appsettings.json
*.config.user

View File

@ -112,37 +112,39 @@ namespace DroneSimulator
private void button_UU_MouseDown(object sender, MouseEventArgs e) private void button_UU_MouseDown(object sender, MouseEventArgs e)
{ {
const float pow = 0.1f;
if (sender == button_UU) if (sender == button_UU)
{ {
sendDrone.MotorUL -= 0.1f; sendDrone.MotorUR -= 0.1f; sendDrone.MotorUL -= pow; sendDrone.MotorUR -= pow;
sendDrone.MotorDL += 0.1f; sendDrone.MotorDR += 0.1f; sendDrone.MotorDL += pow; sendDrone.MotorDR += pow;
} }
if (sender == button_DD) if (sender == button_DD)
{ {
sendDrone.MotorUL += 0.1f; sendDrone.MotorUR += 0.1f; sendDrone.MotorUL += pow; sendDrone.MotorUR += pow;
sendDrone.MotorDL -= 0.1f; sendDrone.MotorDR -= 0.1f; sendDrone.MotorDL -= pow; sendDrone.MotorDR -= pow;
} }
if (sender == button_LL) if (sender == button_LL)
{ {
sendDrone.MotorUL -= 0.1f; sendDrone.MotorUR += 0.1f; sendDrone.MotorUL -= pow; sendDrone.MotorUR += pow;
sendDrone.MotorDL -= 0.1f; sendDrone.MotorDR += 0.1f; sendDrone.MotorDL -= pow; sendDrone.MotorDR += pow;
} }
if (sender == button_RR) if (sender == button_RR)
{ {
sendDrone.MotorUL += 0.1f; sendDrone.MotorUR -= 0.1f; sendDrone.MotorUL += pow; sendDrone.MotorUR -= pow;
sendDrone.MotorDL += 0.1f; sendDrone.MotorDR -= 0.1f; sendDrone.MotorDL += pow; sendDrone.MotorDR -= pow;
} }
if (sender == button_ML) if (sender == button_ML)
{ {
sendDrone.MotorUL -= 0.1f; sendDrone.MotorUR += 0.1f; sendDrone.MotorUL -= pow; sendDrone.MotorUR += pow;
sendDrone.MotorDL += 0.1f; sendDrone.MotorDR -= 0.1f; sendDrone.MotorDL += pow; sendDrone.MotorDR -= pow;
} }
if (sender == button_MR) if (sender == button_MR)
{ {
sendDrone.MotorUL += 0.1f; sendDrone.MotorUR -= 0.1f; sendDrone.MotorUL += pow; sendDrone.MotorUR -= pow;
sendDrone.MotorDL -= 0.1f; sendDrone.MotorDR += 0.1f; sendDrone.MotorDL -= pow; sendDrone.MotorDR += pow;
} }
} }

View File

@ -1,5 +1,5 @@
using System.Net; using System.Net.Sockets;
using System.Net.Sockets; using System.Net;
namespace DroneSimulator namespace DroneSimulator
{ {

3
DroneClient/README.md Normal file
View File

@ -0,0 +1,3 @@
# Client
Образец клиента для подключения к симулятору.

View File

@ -0,0 +1,2 @@
#using <mscorlib.dll>
[assembly: System::Runtime::Versioning::TargetFrameworkAttribute(L".NETFramework,Version=v4.7.2", FrameworkDisplayName=L".NET Framework 4.7.2")];

View File

@ -9,15 +9,17 @@ namespace DroneSimulator
public float Mass; // Масса public float Mass; // Масса
public bool Active; // Живой? public bool Active; // Живой?
public float Length; // Длинна лучей public float Length; // Длинна лучей
public const float Dynamic = 10; // Динамика вращения
public Vector3 PosXYZ, SpdXYZ, AccXYZ; // Положение в пространстве: Позиция, Скорость, Ускорение public Vector3 PosXYZ, SpdXYZ, AccXYZ; // Положение в пространстве: Позиция, Скорость, Ускорение
public Quaternion Quat; // Основной кватернион public Quaternion Quat; // Основной кватернион
public float Power = 0; // Тяга всех двигателей public float Power = 0; // Тяга всех двигателей
public float MaxPower; // Тяга всех двигателей
public Vector3 SpdPRY, AccPRY; // Поворот в пространстве: pitch roll yaw public Vector3 SpdPRY, AccPRY; // Поворот в пространстве: pitch roll yaw
public Vector3 Acc, Gyr; // Имитация: Акселерометр, Гироскоп public Vector3 Acc, Gyr; // Имитация: Акселерометр, Гироскоп
public float LaserRange; // Имитация: Дальномер public float LaserRange; // Имитация: Дальномер
private const float Gravity = 1.0f; private const float Gravity = 9.8f;
private const float TO_GRAD = 180 / MathF.PI; private const float TO_GRAD = 180 / MathF.PI;
private const float TO_RADI = MathF.PI / 180; private const float TO_RADI = MathF.PI / 180;
@ -27,25 +29,16 @@ namespace DroneSimulator
private static int CounterID = 0; private static int CounterID = 0;
public static byte[] getBytes(object data)
public struct DataOut
{ {
public float AccX, AccY, AccZ; int size = Marshal.SizeOf(data);
public float GyrX, GyrY, GyrZ;
public float PosX, PosY;
public float LaserRange;
public byte[] getBytes()
{
int size = Marshal.SizeOf(this);
byte[] arr = new byte[size]; byte[] arr = new byte[size];
IntPtr ptr = IntPtr.Zero; IntPtr ptr = IntPtr.Zero;
try try
{ {
ptr = Marshal.AllocHGlobal(size); ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(this, ptr, true); Marshal.StructureToPtr(data, ptr, true);
Marshal.Copy(ptr, arr, 0, size); Marshal.Copy(ptr, arr, 0, size);
} }
finally finally
@ -54,17 +47,12 @@ namespace DroneSimulator
} }
return arr; return arr;
} }
}
public struct DataIn public static object fromBytes(byte[] arr, Type type)
{ {
public float MotorUL, MotorUR, MotorDL, MotorDR; object mem = new object();
public void fromBytes(byte[] arr) int size = Marshal.SizeOf(type);
{
DataIn mem = new DataIn();
int size = Marshal.SizeOf(mem);
IntPtr ptr = IntPtr.Zero; IntPtr ptr = IntPtr.Zero;
try try
{ {
@ -72,15 +60,53 @@ namespace DroneSimulator
Marshal.Copy(arr, 0, ptr, size); Marshal.Copy(arr, 0, ptr, size);
mem = (DataIn)Marshal.PtrToStructure(ptr, mem.GetType()); mem = Marshal.PtrToStructure(ptr, type);
} }
finally finally
{ {
Marshal.FreeHGlobal(ptr); Marshal.FreeHGlobal(ptr);
} }
this = mem; return mem;
} }
public struct DataOut
{
public float AccX, AccY, AccZ;
public float GyrX, GyrY, GyrZ;
public float PosX, PosY;
public float LaserRange;
}
public DataOut GetDataOut()
{
DataOut data = new DataOut();
data.AccX = Acc.X; data.AccY = Acc.Y; data.AccZ = Acc.Z;
data.GyrX = Gyr.X; data.GyrY = Gyr.Y; data.GyrZ = Gyr.Z;
data.PosX = PosXYZ.X; data.PosY = PosXYZ.Y;
data.LaserRange = LaserRange;
return data;
}
public struct DataIn
{
public float MotorUL, MotorUR, MotorDL, MotorDR;
}
public struct DataVisual
{
public int ID; // Идентификатор
public float W, X, Y, Z; // Кватернион вращения
public float PosX, PosY, PosZ; // Координаты в пространстве
}
public DataVisual GetVisual()
{
return new DataVisual() { ID = this.ID, W = this.Quat.W, X = this.Quat.X, Y = this.Quat.Y, Z = this.Quat.Z, PosX = this.PosXYZ.X, PosY = this.PosXYZ.Y, PosZ = this.PosXYZ.Z };
} }
private void ThreadFunction() private void ThreadFunction()
@ -89,7 +115,7 @@ namespace DroneSimulator
{ {
float time = Environment.TickCount - Timer; float time = Environment.TickCount - Timer;
Timer = Environment.TickCount; Timer = Environment.TickCount;
Action(time / 100); Action(time / 1000);
Thread.Sleep(1); Thread.Sleep(1);
} }
} }
@ -98,7 +124,7 @@ namespace DroneSimulator
{ {
ID = id; ID = id;
Active = false; Active = false;
PosXYZ = new Vector3(2000, 1000, 0); PosXYZ = Vector3.Zero;
SpdXYZ = Vector3.Zero; SpdXYZ = Vector3.Zero;
AccXYZ = Vector3.Zero; AccXYZ = Vector3.Zero;
Quat = Quaternion.Identity; Quat = Quaternion.Identity;
@ -108,10 +134,11 @@ namespace DroneSimulator
DroneThread.Start(); DroneThread.Start();
} }
public int Create(float mass, float len) public int Create(float power, float mass, float len)
{ {
Mass = Range(mass); Mass = mass;
Length = len; Length = len;
MaxPower = power;
Active = true; Active = true;
@ -170,19 +197,21 @@ namespace DroneSimulator
float flow = Power; float flow = Power;
if (PosXYZ.Z < 100) if (PosXYZ.Z < 0.3f)
{ {
flow += flow * 0.1f; // Воздушная подушка flow += flow * 0.1f; // Воздушная подушка
} }
Quaternion pow = Quaternion.Inverse(Quat) * new Quaternion(0, 0, flow, 0) * Quat; SpdPRY += AccPRY * (Dynamic * time / (Mass * Length));
AccXYZ = new Vector3(pow.X, pow.Y, pow.Z) / Mass;
SpdPRY += AccPRY * time / (Mass * Length); Quaternion pow = Quaternion.Inverse(Quat) * new Quaternion(0, 0, flow, 0) * Quat;
AccXYZ = new Vector3(pow.X, pow.Y, pow.Z) * (Gravity / Mass);
SpdXYZ += (AccXYZ + new Vector3(0, 0, -Gravity)) * time; SpdXYZ += (AccXYZ + new Vector3(0, 0, -Gravity)) * time;
PosXYZ += SpdXYZ * time; PosXYZ += SpdXYZ * time;
AccXYZ /= Gravity; // Вернуть измерения в G
if (PosXYZ.Z < 0) if (PosXYZ.Z < 0)
{ {
SpdPRY = Vector3.Zero; SpdPRY = Vector3.Zero;
@ -190,7 +219,7 @@ namespace DroneSimulator
SpdXYZ.Y = 0; SpdXYZ.Y = 0;
Quat = Quaternion.Identity; Quat = Quaternion.Identity;
} }
else Rotate(SpdPRY.X, SpdPRY.Y, SpdPRY.Z); else Rotate(SpdPRY.X * time, SpdPRY.Y * time, SpdPRY.Z * time);
Vector4 ori = GetOrientation(); Vector4 ori = GetOrientation();
@ -203,7 +232,7 @@ namespace DroneSimulator
Active = false; // Сильно ударился о землю Active = false; // Сильно ударился о землю
}*/ }*/
/*if (MathF.Abs(ori.X) > 45 || MathF.Abs(ori.Y) > 45) /*if (MathF.Abs(ori.X) > 20 || MathF.Abs(ori.Y) > 20)
{ {
Active = false; // Повредил винты при посадке Active = false; // Повредил винты при посадке
}*/ }*/
@ -216,13 +245,13 @@ namespace DroneSimulator
} }
else else
{ {
/*if (ori.W < 0) if (ori.W < 0)
{ {
Active = false; // Перевернулся вверх ногами //Active = false; // Перевернулся вверх ногами
}*/ }
Quaternion grav = new Quaternion(AccXYZ.X, AccXYZ.Y, AccXYZ.Z, 0); Quaternion grav = new Quaternion(AccXYZ.X, AccXYZ.Y, AccXYZ.Z, 0);
grav = (Quat * grav) * Quaternion.Inverse(Quat); //grav = (Quat * grav) * Quaternion.Inverse(Quat); // Инерциальный акселерометр (тест)
Acc = new Vector3(grav.X, grav.Y, grav.Z); Acc = new Vector3(grav.X, grav.Y, grav.Z);
Gyr = SpdPRY; Gyr = SpdPRY;
@ -239,7 +268,7 @@ namespace DroneSimulator
if (pow > 1) pow = 1; if (pow > 1) pow = 1;
if (pow < 0) pow = 0; if (pow < 0) pow = 0;
return pow; return pow * MaxPower;
} }
public void SetQadroPow(float ul, float ur, float dl, float dr) public void SetQadroPow(float ul, float ur, float dl, float dr)

View File

@ -38,6 +38,10 @@
tabControl_Menu = new TabControl(); tabControl_Menu = new TabControl();
tabPage_Main = new TabPage(); tabPage_Main = new TabPage();
groupBox_Visual = new GroupBox(); groupBox_Visual = new GroupBox();
numericUpDown_Visual_Limit = new NumericUpDown();
label1 = new Label();
label_Visual_Num = new Label();
label3 = new Label();
button_Visual_Start = new Button(); button_Visual_Start = new Button();
numericUpDown_Visual_Port = new NumericUpDown(); numericUpDown_Visual_Port = new NumericUpDown();
label_Visual_Port = new Label(); label_Visual_Port = new Label();
@ -63,6 +67,7 @@
tabControl_Menu.SuspendLayout(); tabControl_Menu.SuspendLayout();
tabPage_Main.SuspendLayout(); tabPage_Main.SuspendLayout();
groupBox_Visual.SuspendLayout(); groupBox_Visual.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDown_Visual_Limit).BeginInit();
((System.ComponentModel.ISupportInitialize)numericUpDown_Visual_Port).BeginInit(); ((System.ComponentModel.ISupportInitialize)numericUpDown_Visual_Port).BeginInit();
groupBox_Clients.SuspendLayout(); groupBox_Clients.SuspendLayout();
((System.ComponentModel.ISupportInitialize)numericUpDown_Clients_Limit).BeginInit(); ((System.ComponentModel.ISupportInitialize)numericUpDown_Clients_Limit).BeginInit();
@ -144,18 +149,61 @@
// //
// groupBox_Visual // groupBox_Visual
// //
groupBox_Visual.Controls.Add(numericUpDown_Visual_Limit);
groupBox_Visual.Controls.Add(label1);
groupBox_Visual.Controls.Add(label_Visual_Num);
groupBox_Visual.Controls.Add(label3);
groupBox_Visual.Controls.Add(button_Visual_Start); groupBox_Visual.Controls.Add(button_Visual_Start);
groupBox_Visual.Controls.Add(numericUpDown_Visual_Port); groupBox_Visual.Controls.Add(numericUpDown_Visual_Port);
groupBox_Visual.Controls.Add(label_Visual_Port); groupBox_Visual.Controls.Add(label_Visual_Port);
groupBox_Visual.Dock = DockStyle.Top; groupBox_Visual.Dock = DockStyle.Top;
groupBox_Visual.Location = new Point(3, 83); groupBox_Visual.Location = new Point(3, 83);
groupBox_Visual.Name = "groupBox_Visual"; groupBox_Visual.Name = "groupBox_Visual";
groupBox_Visual.Size = new Size(204, 62); groupBox_Visual.Size = new Size(204, 91);
groupBox_Visual.TabIndex = 2; groupBox_Visual.TabIndex = 2;
groupBox_Visual.TabStop = false; groupBox_Visual.TabStop = false;
groupBox_Visual.Tag = "#visual"; groupBox_Visual.Tag = "#visual";
groupBox_Visual.Text = "Visual"; groupBox_Visual.Text = "Visual";
// //
// numericUpDown_Visual_Limit
//
numericUpDown_Visual_Limit.Location = new Point(44, 57);
numericUpDown_Visual_Limit.Maximum = new decimal(new int[] { 10, 0, 0, 0 });
numericUpDown_Visual_Limit.Minimum = new decimal(new int[] { 1, 0, 0, 0 });
numericUpDown_Visual_Limit.Name = "numericUpDown_Visual_Limit";
numericUpDown_Visual_Limit.Size = new Size(42, 23);
numericUpDown_Visual_Limit.TabIndex = 13;
numericUpDown_Visual_Limit.Value = new decimal(new int[] { 1, 0, 0, 0 });
//
// label1
//
label1.AutoSize = true;
label1.Location = new Point(6, 59);
label1.Name = "label1";
label1.Size = new Size(37, 15);
label1.TabIndex = 12;
label1.Tag = "#clients_limit";
label1.Text = "Limit:";
//
// label_Visual_Num
//
label_Visual_Num.AutoSize = true;
label_Visual_Num.Location = new Point(161, 59);
label_Visual_Num.Name = "label_Visual_Num";
label_Visual_Num.Size = new Size(13, 15);
label_Visual_Num.TabIndex = 11;
label_Visual_Num.Text = "0";
//
// label3
//
label3.AutoSize = true;
label3.Location = new Point(112, 59);
label3.Name = "label3";
label3.Size = new Size(43, 15);
label3.TabIndex = 10;
label3.Tag = "#clients_count";
label3.Text = "Count:";
//
// button_Visual_Start // button_Visual_Start
// //
button_Visual_Start.Location = new Point(112, 22); button_Visual_Start.Location = new Point(112, 22);
@ -165,6 +213,7 @@
button_Visual_Start.Tag = "#visual_start"; button_Visual_Start.Tag = "#visual_start";
button_Visual_Start.Text = "Start"; button_Visual_Start.Text = "Start";
button_Visual_Start.UseVisualStyleBackColor = true; button_Visual_Start.UseVisualStyleBackColor = true;
button_Visual_Start.Click += button_Visual_Start_Click;
// //
// numericUpDown_Visual_Port // numericUpDown_Visual_Port
// //
@ -376,6 +425,7 @@
tabPage_Main.ResumeLayout(false); tabPage_Main.ResumeLayout(false);
groupBox_Visual.ResumeLayout(false); groupBox_Visual.ResumeLayout(false);
groupBox_Visual.PerformLayout(); groupBox_Visual.PerformLayout();
((System.ComponentModel.ISupportInitialize)numericUpDown_Visual_Limit).EndInit();
((System.ComponentModel.ISupportInitialize)numericUpDown_Visual_Port).EndInit(); ((System.ComponentModel.ISupportInitialize)numericUpDown_Visual_Port).EndInit();
groupBox_Clients.ResumeLayout(false); groupBox_Clients.ResumeLayout(false);
groupBox_Clients.PerformLayout(); groupBox_Clients.PerformLayout();
@ -416,5 +466,9 @@
private Panel panel1; private Panel panel1;
private ToolStripMenuItem exitToolStripMenuItem; private ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Timer timer_Test; private System.Windows.Forms.Timer timer_Test;
private NumericUpDown numericUpDown_Visual_Limit;
private Label label1;
private Label label_Visual_Num;
private Label label3;
} }
} }

View File

@ -12,6 +12,7 @@ namespace DroneSimulator
Screen2D screen2D = null; Screen2D screen2D = null;
NetServerClients netServerClient = new NetServerClients(); NetServerClients netServerClient = new NetServerClients();
NetServerVisual netServerVisual = new NetServerVisual();
List<Drone> AllDrones = new List<Drone>(); List<Drone> AllDrones = new List<Drone>();
@ -20,7 +21,7 @@ namespace DroneSimulator
InitializeComponent(); InitializeComponent();
} }
private void ConnectionCallback(object o) private void ClientConnectionCallback(object o)
{ {
NetServerClients.ConnectData data = (NetServerClients.ConnectData)o; NetServerClients.ConnectData data = (NetServerClients.ConnectData)o;
@ -32,7 +33,7 @@ namespace DroneSimulator
if (data.Connect) if (data.Connect)
{ {
Drone drone = new Drone(data.ID); Drone drone = new Drone(data.ID);
drone.Create(0.5f, 10.0f); drone.Create(1.0f, 0.5f, 1.0f);
screen2D.CreateDrone(Color.Red, data.ID); screen2D.CreateDrone(Color.Red, data.ID);
@ -53,7 +54,7 @@ namespace DroneSimulator
} }
} }
private void ReceiveCallback(object o) private void ClientReceiveCallback(object o)
{ {
NetServerClients.ReceiveData data = (NetServerClients.ReceiveData)o; NetServerClients.ReceiveData data = (NetServerClients.ReceiveData)o;
@ -68,31 +69,24 @@ namespace DroneSimulator
if (drone == null) return; if (drone == null) return;
Drone.DataIn id = new Drone.DataIn(); Drone.DataIn id = (Drone.DataIn)Drone.fromBytes(data.Buffer, typeof(Drone.DataIn));
id.fromBytes(data.Buffer);
drone.SetQadroPow(id.MotorUL, id.MotorUR, id.MotorDL, id.MotorDR); drone.SetQadroPow(id.MotorUL, id.MotorUR, id.MotorDL, id.MotorDR);
Drone.DataOut od = new Drone.DataOut(); Drone.DataOut od = drone.GetDataOut();
od.AccX= drone.Acc.X; od.AccY= drone.Acc.Y; od.AccZ= drone.Acc.Z; try { data.Client.Send(Drone.getBytes(od)); }
od.GyrX = drone.Gyr.X; od.GyrY = drone.Gyr.Y; od.GyrZ = drone.Gyr.Z;
od.PosX= drone.PosXYZ.X; od.PosY = drone.PosXYZ.Y;
od.LaserRange = drone.LaserRange;
try { data.Client.Send(od.getBytes()); }
catch { } catch { }
} }
private void button_Client_Start_Click(object sender, EventArgs e) private void button_Client_Start_Click(object sender, EventArgs e)
{ {
var done = netServerClient.StartServer((int)numericUpDown_Clients_Port.Value, (int)numericUpDown_Clients_Limit.Value, ConnectionCallback, ReceiveCallback); var done = netServerClient.StartServer((int)numericUpDown_Clients_Port.Value, (int)numericUpDown_Clients_Limit.Value, ClientConnectionCallback, ClientReceiveCallback);
switch (done) switch (done)
{ {
case NetServerClients.ServerState.Error: case NetServerClients.ServerState.Error:
{ {
MessageBox.Show("Error to start server"); MessageBox.Show("Error to start clients server", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break; break;
} }
case NetServerClients.ServerState.Start: case NetServerClients.ServerState.Start:
@ -146,5 +140,63 @@ namespace DroneSimulator
{ {
foreach (Drone d in AllDrones) d.Close(); foreach (Drone d in AllDrones) d.Close();
} }
private void VisualConnectionCallback(object o)
{
NetServerVisual.ConnectData data = (NetServerVisual.ConnectData)o;
Invoke((MethodInvoker)delegate
{
label_Clients_Num.Text = data.Count.ToString();
});
if (data.Connect)
{
//---
}
else
{
//---
}
}
private void VisualReceiveCallback(object o)
{
NetServerVisual.ReceiveData data = (NetServerVisual.ReceiveData)o;
foreach (Drone d in AllDrones)
{
Drone.DataVisual v = d.GetVisual();
try { data.Client.Send(Drone.getBytes(v)); }
catch { }
}
}
private void button_Visual_Start_Click(object sender, EventArgs e)
{
var done = netServerVisual.StartServer((int)numericUpDown_Visual_Port.Value, (int)numericUpDown_Visual_Limit.Value, VisualConnectionCallback, VisualReceiveCallback);
switch (done)
{
case NetServerVisual.ServerState.Error:
{
MessageBox.Show("Error to start visual server", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
case NetServerVisual.ServerState.Start:
{
button_Visual_Start.Text = "Stop";
button_Visual_Start.BackColor = Color.LimeGreen;
break;
}
case NetServerVisual.ServerState.Stop:
{
label_Visual_Num.Text = "0";
button_Visual_Start.Text = "Start";
button_Visual_Start.BackColor = Color.Transparent;
break;
}
}
}
} }
} }

View File

@ -1,5 +1,5 @@
using System.Net; using System.Net.Sockets;
using System.Net.Sockets; using System.Net;
namespace DroneSimulator namespace DroneSimulator
{ {
@ -87,7 +87,7 @@ namespace DroneSimulator
Socket handler; Socket handler;
try { handler = listener.EndAccept(ar); } try { handler = listener.EndAccept(ar); }
catch { ServerSocket?.Close(); Active = false; return; } catch{ ServerSocket?.Close(); Active = false; return; }
if (SocketLimit > ClientSockets.Count) if (SocketLimit > ClientSockets.Count)
{ {

View File

@ -0,0 +1,134 @@
using System.Net.Sockets;
using System.Net;
namespace DroneSimulator
{
internal class NetServerVisual
{
public class ConnectData
{
public bool Connect;
public int Count;
public Socket? Client;
}
public class ReceiveData
{
public byte[]? Buffer;
public int Size;
public Socket? Client;
}
private class ClientData
{
public Socket? workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
}
private int SocketLimit;
private Socket? ServerSocket;
private List<ClientData> ClientSockets = new List<ClientData>();
public delegate void ServerCallback(object o);
private ServerCallback? ConnectionCallback;
private ServerCallback? ReceiveCallback;
private bool Active = false;
public enum ServerState { Error, Start, Stop };
public ServerState StartServer(int Port, int Limit, ServerCallback Connection, ServerCallback Receive)
{
if (Active)
{
ServerSocket?.Close();
foreach (ClientData c in ClientSockets)
{
try { c.workSocket?.Shutdown(SocketShutdown.Both); } catch { }
c.workSocket?.Close();
}
ClientSockets.Clear();
return ServerState.Stop;
}
ConnectionCallback = Connection;
ReceiveCallback = Receive;
SocketLimit = Limit;
IPEndPoint ip = new(IPAddress.Any, Port);
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
ServerSocket.Bind(ip);
ServerSocket.Listen(10);
ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), ServerSocket);
Active = true;
}
catch { ServerSocket.Close(); return ServerState.Error; }
return ServerState.Start;
}
public void AcceptCallback(IAsyncResult ar)
{
Socket listener = (Socket)ar.AsyncState;
if (listener == null) return;
Socket handler;
try { handler = listener.EndAccept(ar); }
catch{ ServerSocket?.Close(); Active = false; return; }
if (SocketLimit > ClientSockets.Count)
{
ClientData clientData = new ClientData();
clientData.workSocket = handler;
ClientSockets.Add(clientData);
ConnectionCallback(new ConnectData { Connect = true, Count = ClientSockets.Count, Client = handler });
handler.BeginReceive(clientData.buffer, 0, ClientData.BufferSize, 0, new AsyncCallback(ReadCallback), clientData);
}
else handler.Close();
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
public void ReadCallback(IAsyncResult ar)
{
ClientData cd = (ClientData)ar.AsyncState;
if (cd == null) return;
int bytes = 0;
try { bytes = cd.workSocket.EndReceive(ar); }
catch { }
if (bytes == 0)
{
cd.workSocket?.Close();
ClientSockets.Remove(cd);
ConnectionCallback(new ConnectData { Connect = false, Count = ClientSockets.Count, Client = null });
return;
}
ReceiveCallback(new ReceiveData { Buffer = cd.buffer, Size = bytes, Client = cd.workSocket });
try
{
cd.workSocket?.BeginReceive(cd.buffer, 0, ClientData.BufferSize, 0, new AsyncCallback(ReadCallback), cd);
}
catch { }
}
}
}

View File

@ -24,6 +24,7 @@ namespace DroneSimulator
public int Azimuth = 0; public int Azimuth = 0;
} }
private float Scale = 100;
private DrawCallback drawCallback; private DrawCallback drawCallback;
private Bitmap MainArea = new Bitmap(4096, 2560); private Bitmap MainArea = new Bitmap(4096, 2560);
private List<DroneInfo> DroneList = new List<DroneInfo>(); private List<DroneInfo> DroneList = new List<DroneInfo>();
@ -161,6 +162,11 @@ namespace DroneSimulator
const float TO_GRAD = 180 / MathF.PI; const float TO_GRAD = 180 / MathF.PI;
const float TO_RADI = MathF.PI / 180; const float TO_RADI = MathF.PI / 180;
pos *= Scale;
pos.X += MainArea.Width / 2;
pos.Y += MainArea.Height / 2;
foreach (var d in DroneList) foreach (var d in DroneList)
{ {
if (d.ID != id) continue; if (d.ID != id) continue;

View File

@ -1,140 +0,0 @@
#include <iostream>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <thread>
#include <atomic>
#include <mutex>
#pragma comment(lib, "Ws2_32.lib")
struct DataIn
{
float AccX, AccY, AccZ;
float GyrX, GyrY, GyrZ;
float PosX, PosY, LaserRange;
} dataIn;
struct DataOut
{
float MotorUL, MotorUR, MotorDL, MotorDR;
} dataOut;
std::atomic<bool> running(true); // Флаг работы потоков
std::mutex dataMutex; // Мьютекс для синхронизации доступа к dataIn и dataOut
SOCKET ConnectToServer(const char* ip, int port)
{
WSAData wsaData;
WORD DLLVersion = MAKEWORD(2, 1);
if (WSAStartup(DLLVersion, &wsaData) != 0)
{
std::cout << "Error: WSAStartup failed\n";
return INVALID_SOCKET;
}
SOCKADDR_IN addr;
inet_pton(AF_INET, ip, &addr.sin_addr);
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
SOCKET Connection = socket(AF_INET, SOCK_STREAM, 0);
if (Connection == INVALID_SOCKET)
{
std::cout << "Error: Failed to create socket\n";
WSACleanup();
return INVALID_SOCKET;
}
if (connect(Connection, (SOCKADDR*)&addr, sizeof(addr)) != 0)
{
std::cout << "Error: Failed to connect to server\n";
closesocket(Connection);
WSACleanup();
return INVALID_SOCKET;
}
return Connection;
}
void CloseConnection(SOCKET& socket)
{
if (socket != INVALID_SOCKET)
{
closesocket(socket);
WSACleanup();
socket = INVALID_SOCKET;
}
}
// Функция приема данных
void ReceiveHandler(SOCKET socket)
{
while (running)
{
DataIn tempData;
int result = recv(socket, (char*)&tempData, sizeof(tempData), 0);
if (result <= 0)
{
std::cout << "Error: Connection lost (recv failed)\n";
running = false;
break;
}
// Потокобезопасное обновление данных
std::lock_guard<std::mutex> lock(dataMutex);
dataIn = tempData;
}
}
// Функция отправки данных
void SendHandler(SOCKET socket)
{
while (running)
{
{
std::lock_guard<std::mutex> lock(dataMutex);
send(socket, (char*)&dataOut, sizeof(dataOut), 0);
}
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // Задержка для уменьшения нагрузки
}
}
int main()
{
SOCKET Connection = ConnectToServer("127.0.0.1", 1001);
if (Connection == INVALID_SOCKET)
{
return 1;
}
dataOut.MotorUL = 10;
dataOut.MotorUR = 10;
dataOut.MotorDL = 10;
dataOut.MotorDR = 10;
// Создание потоков
std::thread recvThread(ReceiveHandler, Connection);
std::thread sendThread(SendHandler, Connection);
for (int i = 0; i < 1000000; i++)
{
{
std::lock_guard<std::mutex> lock(dataMutex);
std::cout << "Laser Range: " << dataIn.LaserRange << std::endl;
}
std::cout << "-----------------------------------------------------------" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500)); // Задержка вывода
}
// Завершаем работу потоков
running = false;
recvThread.join();
sendThread.join();
CloseConnection(Connection);
system("pause");
return 0;
}

View File

@ -1,135 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{b7cc5245-b628-40e9-a9a0-a904e2bf25ea}</ProjectGuid>
<RootNamespace>TestClientConnection</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="TestClientConnection.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

View File

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Исходные файлы">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Файлы заголовков">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Файлы ресурсов">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="TestClientConnection.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
</ItemGroup>
</Project>

1
www.txt Normal file
View File

@ -0,0 +1 @@
Hi!!!