forked from alexChurkin/TruckRemoteServer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UDPServer.cs
339 lines (303 loc) · 11.2 KB
/
UDPServer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
using System;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
namespace TruckRemoteServer
{
public class UDPServer
{
MainForm Main_Form = Application.OpenForms.OfType<MainForm>().Single(); //Acessing Main Form
public int port = 18250;
public bool enabled = Properties.Settings.Default.StartServerOnStartup;//true;
public bool controllerPaused, panelPaused;
public long lastControllerMsgTime, lastPanelMsgTime;
private UdpClient udpClient;
private IPEndPoint controllerEndPoint, panelEndPoint;
internal PCController pcController = new PCController();
private Label labelStatus;
private Button buttonStartStop;
public UDPServer(Label labelStatus, Button buttonStartStop)
{
this.labelStatus = labelStatus;
this.buttonStartStop = buttonStartStop;
pcController.initializeKeyMapping();
}
public void Start()
{
enabled = true;
Main_Form.StartStopButtonProperties();
Thread thread = new Thread(LaunchServer);
thread.Start();
}
public void LaunchServer()
{
try
{
IPEndPoint localIpEndPoint = new IPEndPoint(IPAddress.Any, port);
udpClient = new UdpClient(localIpEndPoint);
StartListeningForMessages();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
ShowStatus("Disabled", Color.OrangeRed);
controllerEndPoint = null;
panelEndPoint = null;
}
}
private void StartListeningForMessages()
{
ShowStatus("Enabled", Color.ForestGreen);
IPEndPoint remoteEndPoint = null;
try
{
while (true)
{
byte[] receivedBytes = udpClient.Receive(ref remoteEndPoint);
string receivedMessage = Encoding.UTF8.GetString(receivedBytes);
if (remoteEndPoint.Equals(controllerEndPoint))
{
lastControllerMsgTime = getUnixTime();
CheckTimeDifferences();
OnMessageFromController(receivedMessage);
}
else if (remoteEndPoint.Equals(panelEndPoint))
{
lastPanelMsgTime = getUnixTime();
CheckTimeDifferences();
OnMessageFromPanel(receivedMessage);
Console.WriteLine(receivedMessage);
}
else if (receivedMessage.Contains("TruckRemoteHello"))
{
lastControllerMsgTime = getUnixTime();
OnHelloFromController(receivedMessage, remoteEndPoint);
udpClient.Client.ReceiveTimeout = 3000;
}
else if (receivedMessage.Contains("TruckPanelRemoteHello"))
{
lastPanelMsgTime = getUnixTime();
OnHelloFromPanel(receivedMessage, remoteEndPoint);
udpClient.Client.ReceiveTimeout = 3000;
}
}
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.TimedOut)
{
StopServer();
LaunchServer();
}
}
}
private void OnHelloFromController(string initMessage, IPEndPoint remoteEndPoint)
{
if (controllerEndPoint != null) return;
Debug.WriteLine("Hello from controller received!");
string[] dataParts = initMessage.Substring(initMessage.IndexOf("\n") + 1).Split(',');
pcController.SetControllerStartValues(
bool.Parse(dataParts[0]),
bool.Parse(dataParts[1]),
bool.Parse(dataParts[2]),
int.Parse(dataParts[3]));
pcController.InitializeJoyIfNeccessary();
byte[] bytesToAnswer = Encoding.UTF8.GetBytes("Hi!");
udpClient.Send(bytesToAnswer, bytesToAnswer.Length, remoteEndPoint);
controllerEndPoint = remoteEndPoint;
UpdateUiState();
}
private void OnHelloFromPanel(string initMessage, IPEndPoint remoteEndPoint)
{
if (panelEndPoint != null) return;
Console.WriteLine("Hello from panel received!");
string[] dataParts = initMessage.Substring(initMessage.IndexOf("\n") + 1).Split(',');
pcController.SetPanelStartValues(
bool.Parse(dataParts[0]),
int.Parse(dataParts[1]),
bool.Parse(dataParts[2]),
bool.Parse(dataParts[3]));
byte[] bytesToAnswer = Encoding.UTF8.GetBytes("Hi!");
udpClient.Send(bytesToAnswer, bytesToAnswer.Length, remoteEndPoint);
panelEndPoint = remoteEndPoint;
UpdateUiState();
}
private void OnMessageFromController(string message)
{
if (message.Contains("paused"))
{
if (!controllerPaused)
{
controllerPaused = true;
UpdateUiState();
}
return;
}
else if (controllerPaused)
{
controllerPaused = false;
UpdateUiState();
}
string[] msgParts = message.Split(',');
double accelerometerValue = double.Parse(msgParts[0], CultureInfo.InvariantCulture);
bool breakClicked = bool.Parse(msgParts[1]);
bool gasClicked = bool.Parse(msgParts[2]);
bool leftSignalEnabled = bool.Parse(msgParts[3]);
bool rightSignalEnabled = bool.Parse(msgParts[4]);
bool parkingBrakeEnabled = bool.Parse(msgParts[5]);
int lightsState = int.Parse(msgParts[6]);
int hornState = int.Parse(msgParts[7]);
bool isCruise = bool.Parse(msgParts[8]);
pcController.UpdateAccelerometerValue(accelerometerValue);
pcController.UpdateBreakGasState(breakClicked, gasClicked);
pcController.UpdateTurnSignals(leftSignalEnabled, rightSignalEnabled);
pcController.UpdateParkingBrake(parkingBrakeEnabled);
pcController.UpdateLights(lightsState);
pcController.UpdateHorn(hornState);
pcController.UpdateCruise(isCruise);
}
private void OnMessageFromPanel(string message)
{
if (message.Contains("paused"))
{
if(!panelPaused)
{
panelPaused = true;
UpdateUiState();
}
return;
}
else if (panelPaused)
{
panelPaused = false;
UpdateUiState();
}
string[] msgParts = message.Split(',');
bool diffBlock = bool.Parse(msgParts[0]);
int wipersState = int.Parse(msgParts[1]);
bool liftingAxle = bool.Parse(msgParts[2]);
bool flashingBeacon = bool.Parse(msgParts[3]);
pcController.UpdateDiffBlock(diffBlock);
pcController.UpdateWipers(wipersState);
pcController.UpdateLiftingAxle(liftingAxle);
pcController.UpdateFlashingBeacon(flashingBeacon);
}
public void Stop()
{
enabled = false;
Main_Form.StartStopButtonProperties();
StopServer();
}
public void StopServer() //Prevent cross thread access on disconnect
{
try
{
udpClient.Close();
}
catch (Exception)
{
}
finally
{
controllerEndPoint = null;
panelEndPoint = null;
ShowStatus("Disabled", Color.OrangeRed);
}
}
private void CheckTimeDifferences()
{
long currentTime = getUnixTime();
if (controllerEndPoint != null && currentTime - lastControllerMsgTime > 3000)
{
controllerEndPoint = null;
controllerPaused = false;
UpdateUiState();
}
else if(panelEndPoint != null && currentTime - lastPanelMsgTime > 3000)
{
panelEndPoint = null;
panelPaused = false;
UpdateUiState();
}
}
public void UpdateUiState()
{
if (enabled)
{
//All devices connected
if (controllerEndPoint != null && panelEndPoint != null)
{
if (controllerPaused && panelPaused)
{
ShowStatus("All devices paused", Color.ForestGreen);
}
else if(controllerPaused)
{
ShowStatus("Controller: paused\nPanel: active", Color.ForestGreen);
}
else if(panelPaused)
{
ShowStatus("Controller: active\nPanel: paused", Color.ForestGreen);
}
else
{
ShowStatus("All devices active", Color.ForestGreen);
}
}
//Connected only controller
else if (controllerEndPoint != null)
{
if (controllerPaused)
{
ShowStatus("Controller paused", Color.ForestGreen);
}
else
{
ShowStatus("Controller active", Color.ForestGreen);
}
}
//Connected only panel
else if (panelEndPoint != null)
{
if(panelPaused)
{
ShowStatus("Panel paused", Color.ForestGreen);
}
else
{
ShowStatus("Panel active", Color.ForestGreen);
}
}
else
{
ShowStatus("Enabled", Color.ForestGreen);
}
}
else
{
ShowStatus("Disabled", Color.OrangeRed);
}
}
private void ShowStatus(string labelText, Color color)
{
try
{
labelStatus.BeginInvoke((MethodInvoker)delegate ()
{
labelStatus.Text = labelText;
labelStatus.ForeColor = color;
});
} catch(Exception) { }
}
private long getUnixTime()
{
return DateTimeOffset.Now.ToUnixTimeMilliseconds();
}
}
}