-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
3110 lines (2717 loc) · 126 KB
/
MainWindow.xaml.cs
File metadata and controls
3110 lines (2717 loc) · 126 KB
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO;
using System.Timers;
using System.Collections.ObjectModel;
using System.ComponentModel;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System.Configuration;
using System.Windows.Markup;
using System.Globalization;
using MahApps.Metro.IconPacks;
using OxyPlot.Series;
using System.Windows.Data;
using System.Threading;
using System.Runtime.InteropServices;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using System.Xml;
using System.Security;
using System.Diagnostics;
using EtherCAT_Master.Core.Controls;
using EtherCAT_Master.Core.Dictionary;
using EtherCAT_Master.Core;
using EtherCAT_Master.Core.Communication;
/*
* TODO 07-01-2019
* -Make the dictionary for the emergency messages from the config file.
*
* TODO 26-03-2019
* ???-Make instance of object dictionary in each device. ?Maybe? Do we still need this? Probably yes if two processes.
* for different devices are working in the background.
*
* TODO 12-04-2019
* -In communication SOEM make it so that the SCOPE is not on the same thread as the PDO.
* -Make it so that the EoE write protect of the UI only protects write of PDO or something like that.
*/
namespace EtherCAT_Master
{
public partial class MainWindow : MetroWindow
{
public System.Timers.Timer MyTimer1 = new System.Timers.Timer(); // timer for triggering every 500ms
private readonly System.Timers.Timer _timerUpdatePlots = new System.Timers.Timer();
/* Variables for the selection of device */
private const int HALT_BIT = 0x0100;
/* Path to the program executable */
public readonly string exePath;
private ModeSpecificBits _modeSpecBits = new ModeSpecificBits();
private readonly DriveSwitch DriveSwitch = new DriveSwitch();
public DictionaryBuilder ObjectDictionary;
private readonly ScopeUserControl _scopeUserControl = new ScopeUserControl();
private UserControl CommControl;
public int AdapterNumber = 0;
public int SelectedDevice { get; set; }
//private ModeSpecificBits test_modspec = new ModeSpecificBits();
private int slide_size_ticks_vel;
private int slide_size_ticks_acc;
private int slide_size_ticks_dec;
private int slide_size_ticks_pos;
private int slider_max_vel;
private int slider_max_acc;
private int slider_max_dec;
private int slider_max_pos;
private double ds_time_minimum;
private double ds_time_interval;
public ErrorNotificationsViewModel ErrorNoti = new ErrorNotificationsViewModel();
public PythonScripting PyScripting;
public PythonOutput pyOutput;
private ObservableCollection<HambMenuItemDict> HambMenuDict = new ObservableCollection<HambMenuItemDict>();
private static RoutedCommand CommandEnable = new RoutedCommand(); /* Command for the drive switch to action the drive State Machine */
private static RoutedCommand CommandFindCtrlF = new RoutedCommand();
private static RoutedCommand CommandF5 = new RoutedCommand();
private static RoutedCommand CommandF2 = new RoutedCommand();
private static RoutedCommand CommandDel = new RoutedCommand();
private static RoutedCommand CommandChangeDecHexCoeDict = new RoutedCommand();
private ObservableCollection<CtrlDgItem> obj_dg_ds = new ObservableCollection<CtrlDgItem>();
private ObservableCollection<CtrlDgItem> obj_dg_pvm = new ObservableCollection<CtrlDgItem>();
private HomingMethods homing;
public CommunicationBase Communication;
public MainWindow()
{
/* Set at the beginning Selected device to -1 so no device is selected*/
SelectedDevice = -1;
/* Create dummy instance of communication because the application needs it */
Communication = new CommunicationDummy();
/* Get path to the executable of the application*/
exePath = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath);
InitializeComponent();
}
/// <summary>
/// Event for when the Main Window has been loaded
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
DictionaryStartUp();
SetUpUiElements();
LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
}
/// <summary>
/// Event for when the content of the Main Window has been rendered
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_ContentRendered(object sender, EventArgs e)
{
MyTimer1.Elapsed += new ElapsedEventHandler(DoTimeEvent1); /* Timer for update of some UI things like the "LEDs" in the General Tab */
MyTimer1.Interval = 200; /* in milliseconds */
_timerUpdatePlots.Elapsed += new ElapsedEventHandler(UpdatePlotsTimeEvent); /* Timer for update of plots */
_timerUpdatePlots.Interval = 487; /* in milliseconds */
}
/*
*
* ######## ## ## ######## ## ## ####### ## ##
* ## ## ## ## ## ## ## ## ## ### ##
* ## ## #### ## ## ## ## ## #### ##
* ######## ## ## ######### ## ## ## ## ##
* ## ## ## ## ## ## ## ## ####
* ## ## ## ## ## ## ## ## ###
* ## ## ## ## ## ####### ## ##
*
*/
private void InitializePythonScripting()
{
PyScripting = new PythonScripting(exePath, appSettings.LastOpenPyScript);
fileNameText.DataContext = PyScripting;
CodeTextEditor.Text = PyScripting.CurrentScriptText;
CodeTextEditor.SyntaxHighlighting =
HighlightingLoader.Load(new XmlTextReader(@"Resources\Python.xshd"),
HighlightingManager.Instance);
pyOutput = new PythonOutput(this, outputBox);
}
private async void Button_Python_Click(object sender, RoutedEventArgs e) /* Button event for testing stuff */
{
try
{
var code = CodeTextEditor.Text;
PyScripting.PyScope.SetVariable("devices", Communication.Devices);
PyScripting.PyScope.SetVariable("device", Communication.Devices[SelectedDevice]);
PyScripting.PyScope.SetVariable("output", pyOutput);
pyOutput.println("");
pyOutput.println(string.Format("--- Running script: {0} ---", PyScripting.CurrentFileName));
pyOutput.println("");
var source = PyScripting.PyEngine.CreateScriptSourceFromString(code, SourceCodeKind.Statements);
await Task.Run(() =>
{
try
{
source.Execute(PyScripting.PyScope);
}
catch (Exception ex)
{
var eo = PyScripting.PyEngine.GetService<ExceptionOperations>();
var error = eo.FormatException(ex);
MessageBox.Show(error, "There was an Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
});
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void CodeTextEditor_TextChanged(object sender, EventArgs e)
{
PyScripting.CurrentScriptText = CodeTextEditor.Text;
if (PyScripting.CurrentFileName == "temp.py")
{
PyScripting.SaveScript();
}
}
private void ButtonSaveScript_Click(object sender, RoutedEventArgs e)
{
if (PyScripting.CurrentFileName != "temp.py")
{
PyScripting.SaveScript();
}
else
{
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog
{
Title = "Save file",
FileName = "NewDocument",
DefaultExt = "py",
Filter = "Python files (*.py)|*.py"
};
/* Display OpenFileDialog by calling ShowDialog method */
bool? result = dlg.ShowDialog();
/* Get the selected file name and display in a TextBox */
if (result == true)
{
PyScripting.CurrentFileName = dlg.SafeFileName;
appSettings.LastOpenPyScript = PyScripting.CurrentFileName;
PyScripting.SaveScript();
}
else
{
return;
}
}
}
private void ButtonOpenScript_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog
{
Tag = "Select a python script file",
DefaultExt = "py",
Filter = "Python files (*.py)|*.py"
};
/* Display OpenFileDialog by calling ShowDialog method */
bool? result = dlg.ShowDialog();
/* Get the selected file name and display in a TextBox */
if (result == true)
{
PyScripting.OpenScript( dlg.SafeFileName );
CodeTextEditor.Text = PyScripting.CurrentScriptText;
appSettings.LastOpenPyScript = PyScripting.CurrentFileName;
}
else
{
return;
}
}
private void Button_PySaveOutput_Click(object sender, RoutedEventArgs e)
{
pyOutput.saveToText();
}
private void Button_PyClearOutput_Click(object sender, RoutedEventArgs e)
{
pyOutput.Clear();
}
private void ButtonNewScript_Click(object sender, RoutedEventArgs e)
{
PyScripting.CurrentFileName = "temp.py";
CodeTextEditor.Text = "import time\n\n";
appSettings.LastOpenPyScript = "temp.py";
}
//###################################################################################
//###################################################################################
//###################################################################################
//###################################################################################
//###################################################################################
//###################################################################################
#region Initialization of UI things
private AppSettings appSettings;
/// <summary>
/// Set Up of UI Properties and Data Context from MainWindow
/// </summary>
private void SetUpUiElements()
{
_scopeUserControl.hamburger1.ItemClick += OnMenuItemClick1;
ContentScope.DataContext = _scopeUserControl;
appSettings = new AppSettings();
/* Get the config data for the controls (like the sliders) for velocity, acceleration, position, etc.*/
ds_time_minimum = appSettings.DriveSequenceTimeMinimum;
ds_time_interval = appSettings.DriveSequenceTimeInterval; ;
slider_max_vel = appSettings.SliderMaxVelocity; ;
slide_size_ticks_vel = appSettings.SliderStepVelocity; ;
slider_max_acc = appSettings.SliderMaxAcceleration; ;
slide_size_ticks_acc = appSettings.SliderStepAcceleration; ;
slider_max_dec = appSettings.SliderMaxDeceleration; ;
slide_size_ticks_dec = appSettings.SliderStepDeceleration; ;
slider_max_pos = appSettings.SliderMaxPosition; ;
slide_size_ticks_pos = appSettings.SliderStepPosition; ;
WindowState = WindowState.Maximized;/* Maximize Main Window */
/* Get image*/
var uri = new Uri(exePath + @"\Images\20171122_Logo_NodeMaster_EC.png");
var bitmapImage = new BitmapImage(uri);
//INTECLogo.Source = bitmapImage;
/* Get the "Intec" Icon */
uri = new Uri(exePath + @"\Images\intec_icon.ico");
bitmapImage = new BitmapImage(uri);
Icon = bitmapImage;
/////////////////////////////////////////////////////////////////////////////
///////////////////////////// DRIVE SEQUENCE PPM ////////////////////////////
/////////////////////////////////////////////////////////////////////////////
HaltContinueDS.Content = new PackIconMaterial() { Kind = PackIconMaterialKind.Pause };
HaltContinueDS.Foreground = new SolidColorBrush(IntecColors.dark_grey);
driveSequence.ItemsSource = null;
obj_dg_ds.Add(new CtrlDgItem() /* Add first element to the drive sequence DataGrid by default */
{
Id = 0,
AddRemoveText = new PackIconMaterial() { Kind = PackIconMaterialKind.Minus },
ButtonColor = new SolidColorBrush(IntecColors.light_red),
TargetPosition = 0,
Velocity = 500,
Acceleration = slider_max_acc / 2,
Deceleration = slider_max_dec / 2,
TimeWait = 1000,
TimeMinimum = ds_time_minimum,
TimeInterval = ds_time_interval,
TickPos = slide_size_ticks_pos,
TickVel = slide_size_ticks_vel,
TickAcc = slide_size_ticks_acc,
TickDec = slide_size_ticks_dec,
PB = new ProgressBar(),
MaxPosSlide = slider_max_pos,
MinPosSlide = -slider_max_pos,
MaxVelSlide = slider_max_vel,
MinVelSlide = 1,
MaxAccSlide = slider_max_acc,
MinAccSlide = 1,
MaxDecSlide = slider_max_dec,
MinDecSlide = 1,
RampType = 0,
Vis = Visibility.Visible
});
obj_dg_ds.Add(new CtrlDgItem() /* Add the "last" element of the drive sequence DataGrid that will only include a button to add more elements to the sequence */
{
Id = 1,
AddRemoveText = new PackIconMaterial() { Kind = PackIconMaterialKind.Plus },
ButtonColor = new SolidColorBrush(IntecColors.green),
PB = new ProgressBar(),
Vis = Visibility.Hidden
});
driveSequence.ItemsSource = obj_dg_ds;
/////////////////////////////////////////////////////////////////////////////
///////////////////////////// PROFILE VELOCITY MODE /////////////////////////
/////////////////////////////////////////////////////////////////////////////
obj_dg_pvm.Add(new CtrlDgItem()
{
Id = 0,
Velocity = 0,
Acceleration = slider_max_acc / 2,
Deceleration = slider_max_dec / 2,
PB = new ProgressBar(),
TickVel = slide_size_ticks_vel,
TickAcc = slide_size_ticks_acc,
TickDec = slide_size_ticks_dec,
MaxVelSlide = slider_max_vel,
MinVelSlide = -slider_max_vel,
MaxAccSlide = slider_max_acc,
MaxDecSlide = slider_max_dec,
RampType = 0,
Vis = Visibility.Visible
});
dataGridPVM.ItemsSource = obj_dg_pvm;
foreach (var obj in obj_dg_pvm)
{
obj.PropertyChanged += VelocityPropertyChangedHandler;
}
////////////////////////////////////////////
////////////////////////////////////////////
/* Initialize some colors for the UI elements */
MWindow.Background = new SolidColorBrush(IntecColors.bg_grey);
statusBit0.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit1.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit2.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit3.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit4.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit5.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit6.Fill = new SolidColorBrush(IntecColors.light_grey);
statusBit7.Fill = new SolidColorBrush(IntecColors.light_grey);
_modeSpecBits.statusBit10.Fill = new SolidColorBrush(IntecColors.light_grey);
_modeSpecBits.statusBit12.Fill = new SolidColorBrush(IntecColors.light_grey);
_modeSpecBits.statusBit13.Fill = new SolidColorBrush(IntecColors.light_grey);
_modeSpecBits.warningBit.Fill = new SolidColorBrush(IntecColors.light_grey);
/* Text for the Headers of the DataGrid of the Profile Velocity Mode */
dataGridPVM.Columns[0].Header = "Velocity\n[min\x207B\xB9]";
dataGridPVM.Columns[1].Header = "Acceleration\n[1/s\xB2]";
dataGridPVM.Columns[2].Header = "Deceleration\n[1/s\xB2]";
/* Text for the Headers of the DataGrid of the Profile Position Mode */
driveSequence.Columns[1].Header = "Velocity\n[min\x207B\xB9]";
driveSequence.Columns[2].Header = "Acceleration\n[1/s\xB2]";
driveSequence.Columns[3].Header = "Deceleration\n[1/s\xB2]";
/* Set the data context of the Mode-Specific-Bit Control to respective object */
DriveSwitch.ContentGeneralModeSpecBits.DataContext = _modeSpecBits;
/////////////////////////////////////////////////////////////////////////////
///////////////////////////// ErrorNoti.Items //////////////////////////////
/////////////////////////////////////////////////////////////////////////////
ErrorNoti.Items = new ObservableCollection<ErrorNotifications>();
dataGridNotifications.DataContext = ErrorNoti.Items;
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////// Drive Switch ///////////////////////////////
/////////////////////////////////////////////////////////////////////////////
ContentSwitchDS.DataContext = DriveSwitch;
DriveSwitch.IsEnabled = false;
/////////////////// Command declaration for Drive Switch
var cb = new CommandBinding(CommandEnable,
CommandExecute, MyCommandCanExecute);
this.CommandBindings.Add(cb);
DriveSwitch.CmdSM.Command = CommandEnable;
var kg = new KeyGesture(Key.M, ModifierKeys.Control);
var ib = new InputBinding(CommandEnable, kg);
this.InputBindings.Add(ib);
/////////////////////////////////////////////////////////////////////////////
///////////////////////////// Get ADAPTERS //////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
AdapterNumber = appSettings.NumberNetworkAdapter;
ScanAdapters();
CmbxNetworkAdapter.SelectedIndex = AdapterNumber;
//////////////////////////////////////////////////////////////////////////////
///////////////////////////// CoE Dictionary /////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
dataGridDictionary.DataContext = ObjectDictionary.DictViewModel;
hamburgerDict.HamburgerButtonClick += HamburgerDict_HamburgerButtonClick;
HambMenuDict = (new HambMenuItemDict()).GetItems();
HambMenuDict[2].TxtBox.TextChanged += TxtBox_TextChanged;
hamburgerDict.ItemsSource = HambMenuDict;
CommandChangeDecHexCoeDict.InputGestures.Add(new KeyGesture(Key.F6)); /* Declare command for Change dec/hex hotkey */
CommandBindings.Add(new CommandBinding(CommandChangeDecHexCoeDict, CommandChangeDecHexCoeDictExcecuted));
/////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Declare Commands //////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
CommandFindCtrlF.InputGestures.Add(new KeyGesture(Key.F, ModifierKeys.Control)); /* Declare command for find hotkey */
CommandBindings.Add(new CommandBinding(CommandFindCtrlF, CommandFindCtrlFExecuted));
CommandF5.InputGestures.Add(new KeyGesture(Key.F5)); /* Declare command for Refresh hotkey */
CommandBindings.Add(new CommandBinding(CommandF5, CommandF5Executed));
CommandDel.InputGestures.Add(new KeyGesture(Key.Delete)); /* Declare command for Refresh hotkey */
CommandBindings.Add(new CommandBinding(CommandF5, CommandDelExecuted));
/////////////////////////////////////////////////////////////////////////////////
///////////////////////////// Homing Methods ////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
homing = new HomingMethods();
ComboBoxHoming.ItemsSource = homing.methodDict;
ComboBoxHoming.SelectedIndex = 30;
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
RadButEcat.IsChecked = true;
ChooseComm.DataContext = Communication;
/* */
buttonSplitScope.Content = new PackIconMaterial() { Kind = PackIconMaterialKind.ChartLine };
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
///
InitializePythonScripting();
}
//private void MakeNewScopeHambMenus()
//{
//}
/// <summary>
/// Event whene the EtherCAT Radial Button was Checked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RadButEcat_Checked(object sender, RoutedEventArgs e)
{
CommControl = new EtherCatControl(this);
CommContentControl.DataContext = CommControl;
(CommControl as EtherCatControl).dataGridDevices.SelectedCellsChanged += dataGridDevices_SelectedCellsChanged;
CommContentControl.IsEnabled = true;
}
/// <summary>
/// Event whene the UDP/IP Radial Button was Checked
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RadButUdp_Checked(object sender, RoutedEventArgs e)
{
CommControl = new UdpCommControl(this);
CommContentControl.DataContext = CommControl;
(CommControl as UdpCommControl).dataGridDevices.SelectedCellsChanged += dataGridDevices_SelectedCellsChanged;
CommContentControl.IsEnabled = true;
}
/// <summary>
/// Command to execute when the Hotkey Ctrl+F is pressed. On Tab Scope it will focus on the first Combobox. On the Dictionary Tab it will focus on the search TextBox.
/// </summary>
private void CommandFindCtrlFExecuted(object sender, ExecutedRoutedEventArgs e)
{
try
{
if (Tabs.SelectedIndex == 4) /* If tab CoE Dictionary is open */
{
hamburgerDict.IsPaneOpen = true;
dataGridDictionary.Margin = new Thickness(240, 0, 0, 0);
HambMenuDict[2].TxtBox.Text = "";
HambMenuDict[2].TxtBox.Focusable = true;
Keyboard.Focus(HambMenuDict[2].TxtBox);
}
else if (Tabs.SelectedIndex == 3) /* If tab Scope is open */
{
if (!(Communication.Devices[SelectedDevice] is PCS device))
{
throw new Exception("No device of type PCS connected and/or selected");
}
_scopeUserControl.hamburger1.IsPaneOpen = true;
_scopeUserControl.scope1.Margin = new Thickness(240, 0, 0, 0);
device.scopeControl.Hamb1.Items[2].Combo.Focusable = true;
Keyboard.Focus(device.scopeControl.Hamb1.Items[2].Combo);
}
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
/// <summary>
/// Command to execute when the Hotkey F5 is pressed.
/// </summary>
private void CommandF5Executed(object sender, ExecutedRoutedEventArgs e)
{
try
{
if (Tabs.SelectedIndex == 4)
{
RefreshCoeValues();
}
else if (Tabs.SelectedIndex == 3)
{
StartStopPlottingAction();
}
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void CommandDelExecuted(object sender, ExecutedRoutedEventArgs e)
{
try
{
Console.WriteLine("Del");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
/// <summary>
/// Declaration of external SOEM Function to read the names of the Network adapters
/// </summary>
/// <param name="buf"></param>
[DllImport("Resources\\soem.dll", CallingConvention = CallingConvention.StdCall)]
private static extern void GetNetworkAdapter(byte[] buf);
public void EcGetNetworkAdapter(byte[] buf)
{
if (!Communication.Connected)
{
GetNetworkAdapter(buf);
}
}
/// <summary>
/// Scan for Network Interface Controllers on the system and return them to the Combobox "CmbxNetWorkAdapter" so one can be selected.
/// </summary>
private void ScanAdapters()
{
try
{
byte[] buf = new byte[1024];
EcGetNetworkAdapter(buf);
var ret = Encoding.ASCII.GetString(buf);
var retSplitString = ret.Split('*');
var retTokens = new List<string>();
for (var i = 0; i < retSplitString.Length - 1; i++)
{
retTokens.Add(retSplitString[i]);
}
CmbxNetworkAdapter.ItemsSource = retTokens;
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
/// <summary>
/// Button Click event for calling the function to scan for Network Interface Controllers.
/// </summary>
private void ScanAdapters_Click(object sender, RoutedEventArgs e)
{
ScanAdapters();
}
/// <summary>
/// Event triggered when the selection of a NIC is done. The function saves the index of the adapter for soem and it saves this index into the config file for the next time.
/// </summary>
private void CmbxNetworkAdapter_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
AdapterNumber = (sender as ComboBox).SelectedIndex;
appSettings.NumberNetworkAdapter = AdapterNumber;
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
public ObservableCollection<string> scanned_devices = new ObservableCollection<string>();
/// <summary>
/// This is a function triggered for the selected cells event from the Devices DatGrid.
/// It is mainly used to set the ItemsSource and DataContext of the View elements
/// to the PCS device object that is being selected, so that data bindings will work.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridDevices_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
try
{
/* check if selected device is of type PCS */
if (!((sender as DataGrid).SelectedItem is PCS device))
{
return;
}
foreach (PCS dev in Communication.Devices)
{
if (dev is PCS)
{
dev.timerNonRealTime.Stop();
}
}
SelectedDevice = (sender as DataGrid).SelectedIndex;
_scopeUserControl.scope1.DataContext = device.scopeControl.plotScope;
dataGridEmcyMsgs.ItemsSource = device.EmcyMsgs;
DriveSwitch.CmdSM.DataContext = device.stateMachineDsp402;
DriveSwitch.statusLabel.DataContext = device.stateMachineDsp402;
DriveSwitch.IsEnabled = true;
_modeSpecBits.DataContext = device.OmBits;
HaltContinuePVM.DataContext = device;
ppmGrid.DataContext = device.stateMachineDsp402;
pvmGrid.DataContext = device.stateMachineDsp402;
hmGrid.DataContext = device.stateMachineDsp402;
_scopeUserControl.hamburger1.DataContext = device.scopeControl.Hamb1;
_scopeUserControl.hamburger1.HamburgerButtonClick += Hamburger1_HamburgerButtonClick;
device.TargetVelocity = 0;
obj_dg_pvm[0].Velocity = 0;
myGauge0.DataContext = device.Gauges[0];
myGauge1.DataContext = device.Gauges[1];
if (Tabs.SelectedIndex == 5)
{
if (Communication.Connected)
{
device.timerNonRealTime.Interval = 100;
device.timerNonRealTime.Start();
}
}
myGauge0.InvalidateArrange();
myGauge1.InvalidateArrange();
myGauge0.InvalidateVisual();
myGauge1.InvalidateVisual();
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
/// <summary>
/// Can execute command of drive switch
/// </summary>
private static void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
/// <summary>
/// Execute command when drive switch is clicked.
/// </summary>
private async void CommandExecute(object sender, ExecutedRoutedEventArgs e)
{
try
{
if (!(Communication.Devices[SelectedDevice] is PCS device))
{
MessageBox.Show("Selected device is not of type PCS.");
return;
}
if (device.EcStateMachine == EC_SM.EC_STATE_OPER
|| device.EcStateMachine == EC_SM.EC_STATE_SAFE_OP
|| device.EcStateMachine == EC_SM.EC_STATE_PRE_OP
|| Communication.commType == CommType.COMM_UDP)
{
if (device.stateMachineDsp402.IS_FAULT()
|| device.stateMachineDsp402.IS_FAULT_REACTION_ACTIVE())
{
await Task.Run(() =>
{
device.SetControlWordPdo(StateMachine.SM_CW_FAULT_RESET, 0x0100);
});
await Task.Delay(100);
await Task.Run(() =>
{
device.SetControlWordPdo(StateMachine.SM_CW_DISABLE_VOLT, 0x0100);
});
if (device.EcStateMachine == EC_SM.EC_STATE_PRE_OP)
{
await Task.Delay(100);
//device.StateMach.StateWord = (ushort)
//device.SdoRead(0x6041, 0x00);
}
Dispatcher.Invoke(() =>
{
TabPPM.IsEnabled = true;
TabPVM.IsEnabled = true;
TabHM.IsEnabled = true;
TabSCOPE.IsEnabled = true;
});
}
else if (device.stateMachineDsp402.IS_OPERATION_ENABLED())
{
Console.WriteLine("Is Operation Enabled");
await Task.Run(() =>
{
StopDriveSequence();
device.SetOperMode0();
device.SetControlWordPdo(StateMachine.SM_CW_SHUTDOWN, 0x0100);
});
}
else if(device.stateMachineDsp402.IS_QUICK_STOP_ACTIVE())
{
device.SetControlWordPdo(StateMachine.SM_CW_DISABLE_VOLT, 0x0100);
}
else if (!device.stateMachineDsp402.IS_OPERATION_ENABLED())
{
Console.WriteLine("NOT Operation Enabled");
device.SetControlWordPdo(StateMachine.SM_CW_SHUTDOWN, 0x0100);
await Task.Delay(150);
device.SetControlWordPdo(StateMachine.SM_CW_ENABLE_OP, 0x0100);
switch(Tabs.SelectedIndex)
{
case 0:
device.SetOperModePPM();
break;
case 1:
device.SetOperModePVM();
break;
case 2:
device.SetOperModeHM();
break;
default:
device.SetOperMode0();
break;
}
}
}
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
/// <summary>
/// Event for when the
/// </summary>
private void Tabs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.Source is TabControl && Communication.Connected && SelectedDevice > -1)
{
foreach (PCS dev in Communication.Devices)
{
if (dev is PCS)
{
dev.timerNonRealTime.Stop();
}
}
var device = Communication.Devices[SelectedDevice] as PCS;
var tab = sender as TabControl;
if (tab.SelectedIndex == 0)
{
Dispatcher.Invoke(() => { StartDS.Content = "Start"; });
}
else if (tab.SelectedIndex == 1)
{
}
else if (tab.SelectedIndex == 2)
{
}
else if (tab.SelectedIndex == 3) /* Scope Tab */
{
RemoveScopeToSplitWindow();
}
else if (tab.SelectedIndex == 4) /* Dict Tab */
{
}
else if (tab.SelectedIndex == 5)
{
if (Communication.Connected)
{
device.timerNonRealTime.Interval = 100;
device.timerNonRealTime.Start();
}
myGauge0.DataContext = device.Gauges[0];
myGauge1.DataContext = device.Gauges[1];
}
}
}
/// <summary>
/// Disconnect the communication
/// </summary>
public void Disconnect()
{
MyTimer1.Stop();
StopPlots1();
Communication.Disconnect();
}
/// <summary>
/// The disconnect function that is called when the application is being shut down
/// </summary>
public async void Disconnect_Shutdown()
{
try
{
MyTimer1.Stop();
StopPlots1();
await Task.Run(() =>
{
foreach (PCS device in Communication.Devices)
{
if (device is PCS)
{
device.SetControlWordPdo(StateMachine.SM_CW_DISABLE_VOLT, 0);
StopDriveSequence();
foreach (PCS dev in Communication.Devices)
{
if (dev is PCS)
{
dev.timerNonRealTime.Stop();
}
}
if (device.scopeControl.ts_scope != null)
{
device.scopeControl.ts_scope.Cancel();
}
}
}
});
await Task.Delay(400);
Communication.Disconnect();
//await Task.Delay(400);
//ObjectDictionary.Dispose();
//DictionaryStartUp();
//dataGridDictionary.DataContext = ObjectDictionary.DictViewModel;
}
catch (Exception err)
{
Console.WriteLine(err.ToString());
}
}
/// <summary>
/// Calls the construction of the main dictionary and created the instance of the Object Dictionary
/// </summary>
private void DictionaryStartUp()
{
/* Construct the dictionary from the path to the ESI file. */
ObjectDictionary = new DictionaryBuilder(Path.Combine(exePath, @"ESI\INTEC_PCS.xml"));