-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
548 lines (467 loc) · 18.8 KB
/
MainWindow.xaml.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Globalization;
using System.IO.Ports;
using System.Collections.ObjectModel;
using System.ComponentModel;
using robot_teachbox.src.robot;
using robot_teachbox.view;
using robot_teachbox.src.main;
using System.IO;
using System.Text.Json;
using System.Diagnostics;
using System.Data;
using robot_teachbox.src.inventory;
using robot_teachbox.src.control;
namespace robot_teachbox
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// Works on top of the KeyPressHandler which is the original console-solution
/// which primarily accepts Keypresses.
/// </summary>
public partial class MainWindow : Window
{
static KeyPressInterpreter KeyPressInt;
static RobotSender RobotSend;
static Settings ProgSettings;
bool keyEventActive = true;
public MainWindow()
{
InitializeComponent();
Console.WriteLine("App started");
const string culture = "en-US";
CultureInfo ci = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentCulture = ci;
Console.SetOut(new view.ControlWriter(textBox));
Logger.Instance.SetControl(textBox);
InitializeRobotObjects();
InitializeControls();
//The UI-thread must be the one to print to console since its bound to a UI-control.
//therefore implemented here as async code which runs for the entire life-time.
Func<Task> x = (async () => {
while (true)
{
await Task.Delay(500);
Logger.Instance.Print();
}
});
x();
}
private void InitializeControls()
{
LoadPositionFromFile();
var ports = SerialPort.GetPortNames();
Closing += this.OnWindowClosing;
foreach (string port in ports)
{
comboBox.Items.Add(port);
}
if (ports.Count() > 0)
{
comboBox.SelectedIndex = 0;
}
}
private void SavePositionsToFile()
{
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result
// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
string fullPathGrab = System.IO.Path.Combine(projectDirectory, "grab_saved.txt");
string fullPathCircle = System.IO.Path.Combine(projectDirectory, "circle_saved.txt");
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fullPathGrab))
{
var gridJson = JsonSerializer.Serialize(this.dataGrid.ItemsSource);
file.Write(gridJson);
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter(fullPathCircle))
{
var gridJson = JsonSerializer.Serialize(this.dataCirclePourGrid.ItemsSource);
file.Write(gridJson);
}
}
ObservableCollection<Circle3D> pourPositions;
ObservableCollection<PositionGrab> grabPositions;
//#TODO: remove duplication
private void LoadPositionFromFile()
{
string workingDirectory = Environment.CurrentDirectory;
// or: Directory.GetCurrentDirectory() gives the same result
// This will get the current PROJECT directory
string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
string fullPathGrab = System.IO.Path.Combine(projectDirectory, "grab_saved.txt");
string fullPathCircle = System.IO.Path.Combine(projectDirectory, "circle_saved.txt");
using (System.IO.StreamReader file = new System.IO.StreamReader(fullPathGrab))
{
var gridJson = file.ReadToEnd();
grabPositions = JsonSerializer.Deserialize<ObservableCollection<PositionGrab>>(gridJson);
this.dataGrid.ItemsSource=grabPositions;
}
using (System.IO.StreamReader file = new System.IO.StreamReader(fullPathCircle))
{
var gridJson = file.ReadToEnd();
pourPositions = JsonSerializer.Deserialize<ObservableCollection<Circle3D>>(gridJson);
this.dataCirclePourGrid.ItemsSource = pourPositions;
}
}
private void InitializeRobotObjects()
{
ProgSettings = new Settings(new MyScreen());
this.DataContext = ProgSettings;
KeyPressInt = new KeyPressInterpreter(ProgSettings);
RobotSend = new RobotSender();
RobotSend.StartProcess();
Console.WriteLine("App started, select COM-port and press connect");
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.button.IsEnabled = !RobotSend.OpenPort(ProgSettings.port);
}
private void Standard_move_key_click(object sender, RoutedEventArgs e)
{
var btnPress = sender as Button;
string key = btnPress.Name.Replace("btn_key", "");
Key parsedKey;
try
{
Enum.TryParse(key, out parsedKey);
var cmd = ProcessKeyActivation(parsedKey);
if (cmd != null)
{
RobotSend.Send((CmdMsg)cmd);
}
Console.WriteLine("got:" + parsedKey.ToString());
} catch (ArgumentException ex)
{
Console.WriteLine(ex);
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (keyEventActive)
{
CmdMsg? msg = ProcessKeyActivation(e.Key);
if (msg != null)
{
RobotSend.Send((CmdMsg)msg);
}
if (e.Key == Key.Up || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right)
{
// dont let the arrowkeys change control focus(tab between controls)
e.Handled = true;
}
}
}
private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var port = comboBox.SelectedItem.ToString();
Console.WriteLine("Selected port:" + port);
ProgSettings.SetPort(port);
} catch (NullReferenceException exp)
{
;
}
}
private CmdMsg? ProcessKeyActivation(Key k)
{
switch (k)
{ // Special cases where we want to do something in addition to the KeyPressInterpreter
case Key.A:
UpdateMovementTypeView(Command.MoveAngle);
break;
case Key.X:
UpdateMovementTypeView(Command.MoveXYZ);
break;
}
return KeyPressInt.processKey(k);
}
private void UpdateMovementTypeView(Command cmd)
{
if (cmd == Command.MoveAngle)
{
this.radio1.IsChecked = false;
this.radio2.IsChecked = true;
SetViewMovementBtnLabels(cmd);
}
else if (cmd == Command.MoveXYZ)
{
KeyPressInt.processKey(Key.X);
this.radio1.IsChecked = true;
this.radio2.IsChecked = false;
SetViewMovementBtnLabels(cmd);
}
}
private void MovementType_RadioButton_Checked(object sender, RoutedEventArgs e)
{
Console.WriteLine("radiobutton triggered");
RadioButton r = sender as RadioButton;
if (ProgSettings != null)
{
if ((bool)this.radio1.IsChecked)
{
KeyPressInt.processKey(Key.X);
SetViewMovementBtnLabels(Command.MoveXYZ);
}
else if ((bool)this.radio2.IsChecked)
{
KeyPressInt.processKey(Key.A);
SetViewMovementBtnLabels(Command.MoveAngle);
}
}
}
Dictionary<string, string> numpadNameMapXYZ = new Dictionary<string, string> {
{ "btn_keyNumPad0", "-Z[0]" },
{ "btn_keyNumPad2", "+X[2]" },
{ "btn_keyNumPad4", "-Y[4]" },
{ "btn_keyNumPad5", "+Z[5]" },
{ "btn_keyNumPad6", "+Y[6]" },
{ "btn_keyNumPad8", "-X[8]" },
{ "btn_keyUp", "-TStrght[▲]" },
{ "btn_keyDown", "+TStrght[▼]" },
{ "btn_keyLeft", "[◄]" },
{ "btn_keyRight", "[►]" }};
Dictionary<string, string> numpadNameMapAngle = new Dictionary<string, string> {
{ "btn_keyNumPad0", "-Elbow[0]" },
{ "btn_keyNumPad2", "+Elbow[2]" },
{ "btn_keyNumPad4", "-Waist[4]" },
{ "btn_keyNumPad5", "+Shoulder[5]" },
{ "btn_keyNumPad6", "+Waist[6]" },
{ "btn_keyNumPad8", "-Shoulder[8]" },
{ "btn_keyUp", "-Pitch[▲]" },
{ "btn_keyDown", "+Pitch[▼]" },
{ "btn_keyLeft", "+Roll[◄]" },
{ "btn_keyRight", "-Roll[►]" }};
public DataRowView rowBeingEdited { get; private set; }
private void SetViewMovementBtnLabels(Command movType)
{
Dictionary<string, string> btnNames=null;
if(movType == Command.MoveAngle)
{
btnNames = numpadNameMapAngle;
} else if (movType == Command.MoveXYZ)
{
btnNames = numpadNameMapXYZ;
}
var btns = numpadGrid.Children;
foreach(var element in btns)
{
var btn = element as Button;
//Only update the buttons associated with movementtype
if (btnNames.Keys.Contains(btn.Name))
{
btn.Content = btnNames[btn.Name];
}
}
}
private void DataGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
keyEventActive = false;
Console.WriteLine("Keyinput disabled while editing");
}
private bool isManualEditCommit;
private void HandleMainDataGridCellEditEnding(
object sender, DataGridCellEditEndingEventArgs e)
{
if (!isManualEditCommit)
{
isManualEditCommit = true;
DataGrid grid = (DataGrid)sender;
grid.CommitEdit(DataGridEditingUnit.Row, true);
isManualEditCommit = false;
keyEventActive = true;
Console.WriteLine("Edit finished, Keyinput enabled, commit cell change");
}
}
private void PolarPosRow_Button_Click(object sender, RoutedEventArgs e)
{
var rows = this.dataGrid.SelectedCells;
var pos = rows.ElementAt(0).Item as PositionGrab;
//we only care about a single selection, a button should map to only its own row.
if (pos != null)
{
//RobotSend.GrabPolar(pos);
RobotSend.Send(new CmdMsg(Command.QueryPolar,(PolarPosition)pos));
Console.WriteLine("Grab polar"+pos.ToMelfaPosString());
}
}
private void Circle3DPosRow_Button_Click(object sender, RoutedEventArgs e)
{
var rows = this.dataCirclePourGrid.SelectedCells;
var pos = rows.ElementAt(0).Item as Circle3D;
//we only care about a single selection, a button should map to only its own row.
if (pos != null)
{
//Send the clone, we want to set the original in the datagrid to be reversed. If pointing
//to the same reference as the command we cant do that without reversing the command.
RobotSend.Send(new CmdMsg(Command.QueryPour, (PolarPosition)pos.Clone()));
Console.WriteLine("Pour:"+pos.ToMelfaPosString());
pos.Reverse = !pos.Reverse;
dataCirclePourGrid.Items.Refresh();
}
}
public void OnWindowClosing(object sender, CancelEventArgs e )
{
Logger.Instance.Log("Exiting application");
SavePositionsToFile();
//await Task.Delay(1000); //Give the logger time to show exit.
RobotSend.Dispose();
Console.WriteLine("Wait while window closes..");
//This is a hack. Need to output a bunch of stuff to
for(int i = 0; i < 20; i++)
{
Logger.Instance.Refresh();
Console.Write(" ");
Console.Out.Flush();
}
Debug.WriteLine("msg queue:"+Logger.Instance.GetLength());
//give time for printouts before exit
Thread.Sleep(1000);
//e.Cancel=true;
}
//For test
private void testButton1_Click(object sender, RoutedEventArgs e)
{
/*Type t = dataGrid.ItemsSource.GetType().GetGenericArguments().Single();
var inst = Activator.CreateInstance(t);
Console.WriteLine(inst.ToString());*/
//So decimal in 20.00 will parse correctly
var _inventory = new Inventory();
_inventory.AddBottle("Whiskey", 0, 50, 0, 60);
_inventory.AddBottle("Cola", 1, 50, 1, 60);
_inventory.AddBottle("Juice", 2, 50, 2, 60);
_inventory.AddBottle("Rum", 3, 50, 3, 60);
Debug.WriteLine(_inventory.ToString());
var jf = new JobFactory(_inventory);
var ingredientsWC = new Dictionary<string, int>
{
{"Whiskey",6 }, {"Cola",12}
};
var ingredientsRC = new Dictionary<string, int>
{
{"Rum",4 }, {"Cola",6}
};
var ingredientsJW = new Dictionary<string, int>
{
{"Juice",10 }, {"Whiskey",10}
};
var jobW = jf.CreateDrinkByIngredients(1, ingredientsWC);
var jobR = jf.CreateDrinkByIngredients(2, ingredientsRC);
var jobJW = jf.CreateDrinkByIngredients(0, ingredientsJW);
var jc = new JobCoordinator();
jc.AddJob(jobW);
jc.AddJob(jobR);
jc.AddJob(jobJW);
var controller = new DrinkRobotController(jc, _inventory, new WorldPositions(),RobotSend);
controller.RunJobs();
}
//for test
private void testButton2_Click(object sender, RoutedEventArgs e)
{
var rows = this.dataGrid.SelectedCells;
var pos = rows.ElementAt(0).Item as PositionGrab;
Console.WriteLine("melfa:"+pos.ToMelfaPosString());
}
private void exitClicked(object sender, RoutedEventArgs e)
{
OnWindowClosing(this,null);
System.Windows.Application.Current.Shutdown();
}
private void DataGrid_GotoButton_Click(object sender, RoutedEventArgs e)
{
Action<DataGrid,string> GotoSelectedGridPos = (grid,type) =>
{
var rows = grid.SelectedCells;
var pos = rows.ElementAt(0).Item as PolarPosition;
if (pos != null)
{
CmdMsg msg;
Logger.Instance.Log(pos.ToMelfaPosString());
if (type == "grab")
{
msg = new CmdMsg(Command.MovePosition, pos);
} else
{
var pourPos = pos as Circle3D;
msg = new CmdMsg(Command.MovePosition, pourPos.GetPositionAtStartAngle());
}
RobotSend.Send(msg);
}
};
var btn = sender as Button;
if (btn == null){ return; }
else if (btn.Name == "GotoGrab")
{
GotoSelectedGridPos(this.dataGrid,"grab");
} else if (btn.Name == "GotoCircle")
{
GotoSelectedGridPos(this.dataCirclePourGrid,"pour");
}
}
private void DataGrid_SetButton_Click(object sender, RoutedEventArgs e)
{
Action<DataGrid> SetPosToCurrent = (grid) =>
{
//finish the edit-event and refresh items in case the
//previous selection was editing a cell.
grid.CommitEdit();
var rows = grid.SelectedCells;
var robotPosNow = RobotSend.GetPosition();
var rowPos = rows.ElementAt(0).Item as PolarPosition;
Type t = grid.ItemsSource.GetType().GetGenericArguments().Single();
if (rowPos == null) //
{
var position = Activator.CreateInstance(t) as PolarPosition;
position.UpdatePosition(robotPosNow);
//grid.Items.Add(position);
if (t == typeof(PositionGrab))
{
grabPositions.Add((PositionGrab)position);
}
else if (t == typeof(Circle3D))
{
var cposition = position as Circle3D;
//Make the tip of the bottle the rotation center
//so we can use "goto" and be at the position we are now.
cposition.OffsetRotationCenterToTip();
pourPositions.Add(cposition);
}
} else
{
rowPos.UpdatePosition(robotPosNow);
if (t == typeof(Circle3D))
{
var pos = rowPos as Circle3D;
pos.OffsetRotationCenterToTip();
}
}
grid.Items.Refresh();
};
var btn = sender as Button;
if (btn == null) { return; }
else if (btn.Name == "SetGrab")
{
SetPosToCurrent(this.dataGrid);
}
else if (btn.Name == "SetCircle")
{
SetPosToCurrent(this.dataCirclePourGrid);
}
}
}
}