-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathMainWindow.CommandBindings.cs
More file actions
1620 lines (1396 loc) · 60.1 KB
/
Copy pathMainWindow.CommandBindings.cs
File metadata and controls
1620 lines (1396 loc) · 60.1 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
/*
Copyright (c) 2019 Festo SE & Co. KG <https://www.festo.com/net/de_de/Forms/web/contact_international>
Author: Michael Hoffmeister
Copyright (c) 2019 Phoenix Contact GmbH & Co. KG <>
Author: Andreas Orzelski
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
*/
using AasxIntegrationBase;
using AasxMqttClient;
using AasxPackageLogic;
using AasxPackageLogic.PackageCentral;
using AdminShellNS;
using AnyUi;
using Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Aas = AasCore.Aas3_0;
namespace AasxPackageExplorer
{
/// <summary>
/// This partial class contains all command bindings, such as for the main menu, in order to reduce the
/// complexity of MainWindow.xaml.cs
/// </summary>
public partial class MainWindow : Window, IFlyoutProvider, IExecuteMainCommand
{
private string lastFnForInitialDirectory = null;
//// Note for UltraEdit:
//// <MenuItem Header="([^"]+)"\s*(|InputGestureText="([^"]+)")\s*Command="{StaticResource (\w+)}"/>
//// .AddWpf\(name: "\4", header: "\1", inputGesture: "\3"\)
//// or
//// <MenuItem Header="([^"]+)"\s+([^I]|InputGestureText="([^"]+)")(.*?)Command="{StaticResource (\w+)}"/>
//// .AddWpf\(name: "\5", header: "\1", inputGesture: "\3", \4\)
public void RememberForInitialDirectory(string fn)
{
this.lastFnForInitialDirectory = fn;
}
public string DetermineInitialDirectory(string existingFn = null)
{
string res = null;
if (existingFn != null)
try
{
res = System.IO.Path.GetDirectoryName(existingFn);
}
catch (Exception ex)
{
AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex);
}
// may be can used last?
if (res == null && lastFnForInitialDirectory != null)
try
{
res = System.IO.Path.GetDirectoryName(lastFnForInitialDirectory);
}
catch (Exception ex)
{
AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex);
}
return res;
}
/// <summary>
/// Redraw tree elements (middle), AAS entitty (right side)
/// </summary>
public async Task CommandExecution_RedrawAllAsync()
{
// redraw everything
await RedrawAllAasxElementsAsync();
await RedrawElementViewAsync();
}
/// <summary>
/// Set to <c>true</c>, if the application shall be shut down via script
/// </summary>
public bool ScriptModeShutdown = false;
public async Task<int> ExecuteMainMenuCommand(string menuItemName, params object[] args)
{
if (menuItemName?.HasContent() != true)
{
Log.Singleton.Error("MainWindow execute menu command: menu item name missing!");
return -1;
}
// name of tool, find it
var foundMenu = this.GetMainMenu();
var mi = foundMenu.FindName(menuItemName);
if (mi == null)
{
foundMenu = this.GetDynamicMenu();
mi = foundMenu.FindName(menuItemName);
}
if (mi == null)
{
Log.Singleton.Error($"MainWindow execute menu command: menu item name invalid: {menuItemName}");
return -1;
}
// create a ticket
var ticket = new AasxMenuActionTicket()
{
MenuItem = mi,
ScriptMode = true,
ArgValue = new AasxMenuArgDictionary()
};
// go thru the remaining arguments and find arg names and values
var argi = 0;
while (args != null && argi < args.Length)
{
// get arg name
if (!(args[argi] is string argname))
{
Log.Singleton.Error($"MainWindow execute menu command: Argument at index {argi} is " +
$"not string type for argument name.");
return -1;
}
// find argname?
var ad = mi.ArgDefs?.Find(argname);
if (ad == null)
{
Log.Singleton.Error($"MainWindow execute menu command: Argument at index {argi} is " +
$"not valid argument name.");
return -1;
}
// create arg value (not available is okay)
object av = null;
if (argi + 1 < args.Length)
av = args[argi + 1];
// into ticket
ticket.ArgValue.Add(ad, av);
// 2 forward!
argi += 2;
}
// invoke action
await foundMenu.ActivateAction(mi, ticket);
// perform UI updates if required
if (ticket.UiLambdaAction != null && !(ticket.UiLambdaAction is AnyUiLambdaActionNone))
{
// add to "normal" event quoue
this.AddWishForToplevelAction(ticket.UiLambdaAction);
}
return 0;
}
private async Task CommandBinding_GeneralDispatch(
string cmd,
AasxMenuItemBase menuItem,
AasxMenuActionTicket ticket)
{
//
// Start
//
if (cmd == null || ticket == null)
return;
var scriptmode = ticket.ScriptMode;
Logic?.FillSelectedItem(
DisplayElements.SelectedItem, DisplayElements.SelectedItems, ticket);
//
// Dispatch
//
// REFACTOR: DIFFERENT
if (cmd == "exit")
{
// start
ticket.StartExec();
// do
ScriptModeShutdown = true;
System.Windows.Application.Current.Shutdown();
}
if (cmd == "connectopcua")
MessageBoxFlyoutShow(
"In future versions, this feature will allow connecting to an online Administration Shell " +
"via OPC UA or similar.",
"Connect", AnyUiMessageBoxButton.OK, AnyUiMessageBoxImage.Hand);
// REFACTOR: DIFFERENT
if (cmd == "about")
{
// start
ticket.StartExec();
// do
var ab = new AboutBox(_pref);
ab.ShowDialog();
}
// REFACTOR: DIFFERENT
if (cmd == "helpgithub")
{
// start
ticket.StartExec();
// do
ShowHelp();
}
// REFACTOR: DIFFERENT
if (cmd == "faqgithub")
{
// start
ticket.StartExec();
// do
BrowserDisplayLocalFile(
@"https://github.com/admin-shell-io/questions-and-answers/blob/master/README.md");
}
// REFACTOR: DIFFERENT
if (cmd == "helpissues")
{
// start
ticket.StartExec();
// do
BrowserDisplayLocalFile(
@"https://github.com/admin-shell-io/aasx-package-explorer/issues");
}
// REFACTOR: DIFFERENT
if (cmd == "helpoptionsinfo")
{
// start
ticket.StartExec();
// do
var st = Options.ReportOptions(Options.ReportOptionsFormat.Markdown, Options.Curr);
var dlg = new MessageReportWindow(st,
windowTitle: "Report on active and possible options");
dlg.ShowDialog();
}
//
// Flag handling .. (no refactor)
//
if (cmd == "editkey")
MainMenu?.SetChecked("EditMenu", MainMenu?.IsChecked("EditMenu") != true);
if (cmd == "hintskey")
MainMenu?.SetChecked("HintsMenu", MainMenu?.IsChecked("HintsMenu") != true);
if (cmd == "showirikey")
MainMenu?.SetChecked("ShowIriMenu", MainMenu?.IsChecked("ShowIriMenu") != true);
if (cmd == "editmenu" || cmd == "editkey"
|| cmd == "hintsmenu" || cmd == "hintskey"
|| cmd == "showirimenu" || cmd == "showirikey"
|| cmd == "checksmtelements")
{
// start
ticket.StartExec();
if (ticket.ScriptMode && cmd == "editmenu" && ticket["Mode"] is bool editMode)
{
MainMenu?.SetChecked("EditMenu", editMode);
}
if (ticket.ScriptMode && cmd == "hintsmenu" && ticket["Mode"] is bool hintsMode)
{
MainMenu?.SetChecked("HintsMenu", hintsMode);
}
// trigger re-indexing
TriggerPendingReIndexElements();
// try to remember current selected data object
object currMdo = null;
if (DisplayElements.SelectedItem != null)
currMdo = DisplayElements.SelectedItem.GetMainDataObject();
// edit mode affects the total element view
await RedrawAllAasxElementsAsync();
// fake selection
await RedrawElementViewAsync();
// select last object
if (currMdo != null)
{
DisplayElements.TrySelectMainDataObject(currMdo, wishExpanded: true);
}
}
// REFACTOR: DIFFERENT
if (cmd == "test")
{
// start
ticket.StartExec();
// do
DisplayElements.Test();
}
// REFACTOR: 10% DIFFERENT
if (cmd == "bufferclear")
{
// start
ticket.StartExec();
// do
DispEditEntityPanel.ClearPasteBuffer();
Log.Singleton.Info("Internal copy/ paste buffer cleared. Pasting of external JSON elements " +
"enabled.");
}
// REFACTOR: LEAVE HERE
if (cmd == "exportsmd")
CommandBinding_ExportSMD(ticket);
// REFACTOR: LEAVE HERE
if (cmd == "printasset")
CommandBinding_PrintAsset(ticket);
if (cmd == "importdictsubmodel" || cmd == "importdictsubmodelelements")
CommandBinding_ImportDictToSubmodel(cmd, ticket);
// stays in WPF
if (cmd == "serverrest")
CommandBinding_ServerRest();
// stays in WPF
if (cmd == "mqttpub")
await CommandBinding_MQTTPub(ticket);
// stays in WPF
if (cmd == "connectintegrated")
CommandBinding_ConnectIntegrated();
// stays in WPF
if (cmd == "connectsecure")
CommandBinding_ConnectSecure();
// stays in WPF, ask OZ
if (cmd == "connectrest")
CommandBinding_ConnectRest();
// dead-csharp off
// REFACTOR: STAYS HERE
//if (cmd == "exporttable")
// await CommandBinding_ExportImportTableUml(cmd, ticket, import: false);
// REFACTOR: STAYS HERE
if (cmd == "importtable")
await CommandBinding_ExportImportTableUml(cmd, ticket, import: true);
// REFACTOR: STAYS HERE
//if (cmd == "exportuml")
// await CommandBinding_ExportImportTableUml(cmd, ticket, exportUml: true);
// REFACTOR: STAYS HERE
//if (cmd == "importtimeseries")
// await CommandBinding_ExportImportTableUml(cmd, ticket, importTimeSeries: true);
// dead-csharp on
// REFACTOR: STAYS HERE
if (cmd == "serverpluginemptysample")
CommandBinding_ExecutePluginServer(
"EmptySample", "server-start", "server-stop", "Empty sample plug-in.");
// REFACTOR: STAYS HERE
if (cmd == "serverpluginmqtt")
CommandBinding_ExecutePluginServer(
"AasxPluginMqttServer", "MQTTServer-start", "server-stop", "Plug-in for MQTT Server for AASX.");
// REFACTOR: STAYS
if (cmd == "toolsfindtext" || cmd == "toolsfindforward" || cmd == "toolsfindbackward"
|| cmd == "toolsreplacetext" || cmd == "toolsreplacestay" || cmd == "toolsreplaceforward"
|| cmd == "toolsreplaceall") await CommandBinding_ToolsFind(cmd, ticket);
// REFACTOR: STAYS
if (cmd == "checkandfix")
CommandBinding_CheckAndFix();
// REFACTOR: STAYS
if (cmd == "eventsresetlocks")
{
Log.Singleton.Info($"Event interlocking reset. Status was: " +
$"update-value-pending={_eventHandling.UpdateValuePending}");
_eventHandling.Reset();
}
// REFACTOR: STAYS
if (cmd == "eventsshowlogkey")
MainMenu?.SetChecked("EventsShowLogMenu", MainMenu?.IsChecked("EventsShowLogMenu") != true);
// REFACTOR: STAYS
if (cmd == "eventsshowlogkey" || cmd == "eventsshowlogmenu")
{
PanelConcurrentSetVisibleIfRequired(PanelConcurrentCheckIsVisible());
}
// REFACTOR: STAYS
if (cmd == "attachfileassoc" || cmd == "removefileassoc")
await CommandBinding_RegistryTools(cmd, ticket);
// new hidden commands
if (cmd == "winmaximize")
{
// Note: this is experimental and a duplicate to OptionsInformation.WindowMaximized.
// Thinkink, what is the better way.
this.WindowState = WindowState.Maximized;
}
// pass dispatch on to next (lower) level of menu functions
await Logic.CommandBinding_GeneralDispatchAnyUiDialogs(cmd, menuItem, ticket);
}
public bool PanelConcurrentCheckIsVisible()
{
return MainMenu?.IsChecked("EventsShowLogMenu") == true;
}
public void PanelConcurrentSetVisibleIfRequired(
bool targetState, bool targetAgents = false, bool targetEvents = false)
{
if (!targetState)
{
RowDefinitionConcurrent.Height = new GridLength(0);
}
else
{
if (RowDefinitionConcurrent.Height.Value < 1.0)
{
var desiredH = Math.Max(140.0, this.Height / 3.0);
RowDefinitionConcurrent.Height = new GridLength(desiredH);
}
if (targetEvents)
TabControlConcurrent.SelectedItem = TabItemConcurrentEvents;
if (targetAgents)
TabControlConcurrent.SelectedItem = TabItemConcurrentAgents;
}
}
public async Task CommandBinding_CheckAndFix()
{
// work on package
var msgBoxHeadline = "Check, validate and fix ..";
var env = PackageCentral.Main?.AasEnv;
if (env == null)
{
MessageBoxFlyoutShow(
"No package/ environment open. Aborting.", msgBoxHeadline,
AnyUiMessageBoxButton.OK, AnyUiMessageBoxImage.Error);
return;
}
// try to get results
AasValidationRecordList recs = null;
try
{
// validate (logically)
recs = env.ValidateAll();
// validate as XML
var ms = new MemoryStream();
PackageCentral.Main.SaveAs("noname.xml", true, AdminShellPackageFileBasedEnv.SerializationFormat.Xml, ms,
saveOnlyCopy: true);
ms.Flush();
ms.Position = 0;
AasSchemaValidation.ValidateXML(recs, ms);
ms.Close();
// validate as JSON
var ms2 = new MemoryStream();
PackageCentral.Main.SaveAs("noname.json", true, AdminShellPackageFileBasedEnv.SerializationFormat.Json, ms2,
saveOnlyCopy: true);
ms2.Flush();
ms2.Position = 0;
AasSchemaValidation.ValidateJSONAlternative(recs, ms2);
ms2.Close();
}
catch (Exception ex)
{
Log.Singleton.Error(ex, "Checking model contents");
MessageBoxFlyoutShow(
"Error while checking model contents. Aborting.", msgBoxHeadline,
AnyUiMessageBoxButton.OK, AnyUiMessageBoxImage.Error);
return;
}
// could be nothing
if (recs.Count < 1)
{
MessageBoxFlyoutShow(
"No issues found. Done.", msgBoxHeadline,
AnyUiMessageBoxButton.OK, AnyUiMessageBoxImage.Information);
return;
}
// prompt for this list
var uc = new ShowValidationResultsFlyout();
uc.ValidationItems = recs;
this.StartFlyoverModal(uc);
if (uc.FixSelected)
{
// fix
var fixes = recs.FindAll((r) =>
{
var res = uc.DoHint && r.Severity == AasValidationSeverity.Hint
|| uc.DoWarning && r.Severity == AasValidationSeverity.Warning
|| uc.DoSpecViolation && r.Severity == AasValidationSeverity.SpecViolation
|| uc.DoSchemaViolation && r.Severity == AasValidationSeverity.SchemaViolation;
return res;
});
int done = 0;
try
{
done = env.AutoFix(fixes);
}
catch (Exception ex)
{
Log.Singleton.Error(ex, "Fixing model contents");
MessageBoxFlyoutShow(
"Error while fixing issues. Aborting.", msgBoxHeadline,
AnyUiMessageBoxButton.OK, AnyUiMessageBoxImage.Error);
return;
}
// info
MessageBoxFlyoutShow(
$"Corresponding {done} issues were fixed. Please check the changes and consider saving " +
"with a new filename.", msgBoxHeadline,
AnyUiMessageBoxButton.OK, AnyUiMessageBoxImage.Information);
// redraw
await CommandExecution_RedrawAllAsync();
}
}
public void CommandBinding_ConnectSecure()
{
// make dialgue flyout
var uc = new SecureConnectFlyout();
uc.LoadPresets(Options.Curr.SecureConnectPresets);
// modal dialogue
this.StartFlyoverModal(uc, closingAction: () =>
{
});
// succss?
if (uc.Result == null)
return;
var preset = uc.Result;
// make listing flyout
var logger = new LogInstance();
var uc2 = new LogMessageFlyout("Secure connecting ..", "Start secure connect ..", () =>
{
return logger.PopLastShortTermPrint();
});
uc2.EnableLargeScreen();
// do some statistics
Log.Singleton.Info("Start secure connect ..");
Log.Singleton.Info("Protocol: {0}", preset.Protocol.Value);
Log.Singleton.Info("AuthorizationServer: {0}", preset.AuthorizationServer.Value);
Log.Singleton.Info("AasServer: {0}", preset.AasServer.Value);
Log.Singleton.Info("CertificateFile: {0}", preset.CertificateFile.Value);
Log.Singleton.Info("Password: {0}", preset.Password.Value);
logger.Info("Protocol: {0}", preset.Protocol.Value);
logger.Info("AuthorizationServer: {0}", preset.AuthorizationServer.Value);
logger.Info("AasServer: {0}", preset.AasServer.Value);
logger.Info("CertificateFile: {0}", preset.CertificateFile.Value);
logger.Info("Password: {0}", preset.Password.Value);
// start CONNECT as a worker (will start in the background)
var worker = new BackgroundWorker();
AdminShellPackageFileBasedEnv envToload = null;
worker.DoWork += (s1, e1) =>
{
for (int i = 0; i < 15; i++)
{
var sb = new StringBuilder();
for (double j = 0; j < 1; j += 0.0025)
sb.Append($"{j}");
logger.Info("The output is: {0} gives {1} was {0}", i, sb.ToString());
logger.Info(StoredPrint.Color.Blue, "This is blue");
logger.Info(StoredPrint.Color.Red, "This is red");
logger.Error("This is an error!");
logger.InfoWithHyperlink(0, "This is an link", "(Link)", "https://www.google.de");
logger.Info("----");
Thread.Sleep(2134);
}
envToload = null;
};
worker.RunWorkerCompleted += (s1, e1) =>
{
};
worker.RunWorkerAsync();
// modal dialogue
this.StartFlyoverModal(uc2, closingAction: () =>
{
// clean up
});
// commit Package
if (envToload != null)
{
}
// done
Log.Singleton.Info("Secure connect done.");
}
public void CommandBinding_ConnectIntegrated()
{
// make dialogue flyout
var uc = new IntegratedConnectFlyout(
PackageCentral,
initialLocation: "" /* "http://admin-shell-io.com:51310/server/getaasx/0" */,
logger: new LogInstance());
uc.LoadPresets(Options.Curr.IntegratedConnectPresets);
// modal dialogue
this.StartFlyoverModal(uc, closingAction: () =>
{
});
// execute
if (uc.Result && uc.ResultContainer != null)
{
Log.Singleton.Info($"For integrated connection, trying to take over " +
$"{uc.ResultContainer.ToString()} ..");
try
{
UiLoadPackageWithNew(
PackageCentral.MainItem, null, takeOverContainer: uc.ResultContainer, onlyAuxiliary: false);
}
catch (Exception ex)
{
Log.Singleton.Error(ex, $"When opening {uc.ResultContainer.ToString()}");
}
}
}
public void CommandBinding_PrintAsset(
AasxMenuActionTicket ticket)
{
// rely on ticket availability
if (ticket == null)
return;
// start
ticket?.StartExec();
if (ticket.AAS == null || string.IsNullOrEmpty(ticket.AssetInfo?.GlobalAssetId))
{
Logic?.LogErrorToTicket(ticket,
"No asset selected or no asset identification for printing code sheet.");
return;
}
// ok!
// Note: WPF based; no command line possible
try
{
if (Options.Curr.UseFlyovers) this.StartFlyover(new EmptyFlyout());
AasxPrintFunctions.PrintSingleAssetCodeSheet(ticket.AssetInfo.GlobalAssetId, ticket.AAS.IdShort);
if (Options.Curr.UseFlyovers) this.CloseFlyover();
}
catch (Exception ex)
{
Logic?.LogErrorToTicket(ticket, ex, "When printing");
}
}
public void CommandBinding_ServerRest()
{
#if TODO
// make a logger
var logger = new AasxRestServerLibrary.GrapevineLoggerToListOfStrings();
// make listing flyout
var uc = new LogMessageFlyout("AASX REST Server", "Starting REST server ..", () =>
{
var st = logger.Pop();
return (st == null) ? null : new StoredPrint(st);
});
// start REST as a worker (will start in the background)
var worker = new BackgroundWorker();
worker.DoWork += (s1, e1) =>
{
AasxRestServerLibrary.AasxRestServer.Start(
_packageCentral.Main, Options.Curr.RestServerHost, Options.Curr.RestServerPort, logger);
};
worker.RunWorkerAsync();
// modal dialogue
this.StartFlyoverModal(uc, closingAction: () =>
{
AasxRestServerLibrary.AasxRestServer.Stop();
});
#endif
}
public class FlyoutAgentMqttPublisher : FlyoutAgentBase
{
public AasxMqttClient.AnyUiDialogueDataMqttPublisher DiaData;
public AasxMqttClient.GrapevineLoggerToStoredPrints Logger;
public AasxMqttClient.MqttClient Client;
public BackgroundWorker Worker;
}
public async Task CommandBinding_MQTTPub(AasxMenuActionTicket ticket)
{
// make an agent
var agent = new FlyoutAgentMqttPublisher();
// ask for preferences
#if __WPF_based
agent.DiaData = AasxMqttClient.AnyUiDialogueDataMqttPublisher.CreateWithOptions("AASX MQTT publisher ..",
jtoken: Options.Curr.MqttPublisherOptions);
var uc1 = new MqttPublisherFlyout(agent.DiaData);
this.StartFlyoverModal(uc1);
if (!uc1.Result)
return;
#else
agent.DiaData = AasxMqttClient.AnyUiDialogueDataMqttPublisher.CreateWithOptions("AASX MQTT publisher ..",
jtoken: Options.Curr.MqttPublisherOptions);
var uc1 = new AnyUiDialogueDataModalPanel(agent.DiaData.Caption);
uc1.DisableScrollArea = true;
uc1.ActivateRenderPanel(agent.DiaData,
(uci) =>
{
// create panel
var panel = new AnyUiStackPanel();
var helper = new AnyUiSmallWidgetToolkit();
var data = uci.Data as AnyUiDialogueDataMqttPublisher;
if (data == null)
return panel;
// outer grid
var g = helper.AddSmallGrid(13, 3, new[] { "#", "5:", "*" },
padding: new AnyUiThickness(0, 5, 0, 5));
int row = 0;
// Row : MQTT broker
helper.AddSmallLabelTo(g, row, 0, content: "Format:", verticalCenter: true);
AnyUiUIElement.SetStringFromControl(
helper.AddSmallTextBoxTo(g, row, 2,
margin: new AnyUiThickness(0, 2, 2, 2),
text: "" + data.BrokerUrl,
verticalCenter: true),
(str) => { data.BrokerUrl = str; });
// Row : retain
AnyUiUIElement.SetBoolFromControl(
helper.Set(
helper.AddSmallCheckBoxTo(g, ++row, 2,
content: "Set retain flag in MQTT messages",
isChecked: data.MqttRetain,
verticalContentAlignment: AnyUiVerticalAlignment.Center)),
(b) => { data.MqttRetain = b; });
// VSpace
helper.AddVerticalSpaceTo(g, ++row);
// Row : first time publish
helper.AddSmallLabelTo(g, ++row, 0, content: "First time publish:", verticalCenter: true);
AnyUiUIElement.SetBoolFromControl(
helper.AddSmallCheckBoxTo(g, row, 2,
content: "Enable publishing",
isChecked: data.EnableFirstPublish,
verticalContentAlignment: AnyUiVerticalAlignment.Center),
(b) => { data.EnableFirstPublish = b; });
// Row : Topic AAS
helper.Set(
helper.AddSmallLabelTo(g, ++row, 0, content: "Topic AAS:", verticalCenter: true),
horizontalAlignment: AnyUiHorizontalAlignment.Right,
horizontalContentAlignment: AnyUiHorizontalAlignment.Right);
AnyUiUIElement.SetStringFromControl(
helper.AddSmallTextBoxTo(g, row, 2,
margin: new AnyUiThickness(0, 2, 2, 2),
text: "" + data.FirstTopicAAS,
verticalCenter: true),
(str) => { data.FirstTopicAAS = str; });
// Row : Topic Submodel
helper.Set(
helper.AddSmallLabelTo(g, ++row, 0, content: "Topic Submodel:", verticalCenter: true),
horizontalAlignment: AnyUiHorizontalAlignment.Right,
horizontalContentAlignment: AnyUiHorizontalAlignment.Right);
AnyUiUIElement.SetStringFromControl(
helper.AddSmallTextBoxTo(g, row, 2,
margin: new AnyUiThickness(0, 2, 2, 2),
text: "" + data.FirstTopicSubmodel,
verticalCenter: true),
(str) => { data.FirstTopicSubmodel = str; });
// VSpace
helper.AddVerticalSpaceTo(g, ++row);
// Row : continous event time publish
helper.AddSmallLabelTo(g, ++row, 0, content: "Continous event publish:", verticalCenter: true);
AnyUiUIElement.SetBoolFromControl(
helper.AddSmallCheckBoxTo(g, row, 2,
content: "Enable publishing",
isChecked: data.EnableEventPublish,
verticalContentAlignment: AnyUiVerticalAlignment.Center),
(b) => { data.EnableEventPublish = b; });
// Row : Topic event publish
helper.Set(
helper.AddSmallLabelTo(g, ++row, 0, content: "Topic:", verticalCenter: true),
horizontalAlignment: AnyUiHorizontalAlignment.Right,
horizontalContentAlignment: AnyUiHorizontalAlignment.Right);
AnyUiUIElement.SetStringFromControl(
helper.AddSmallTextBoxTo(g, row, 2,
margin: new AnyUiThickness(0, 2, 2, 2),
text: "" + data.EventTopic,
verticalCenter: true),
(str) => { data.EventTopic = str; });
// VSpace
helper.AddVerticalSpaceTo(g, ++row);
// Row : single value publish
helper.AddSmallLabelTo(g, ++row, 0, content: "Single value publish:", verticalCenter: true);
AnyUiUIElement.SetBoolFromControl(
helper.AddSmallCheckBoxTo(g, row, 2,
content: "Enable publishing",
isChecked: data.SingleValuePublish,
verticalContentAlignment: AnyUiVerticalAlignment.Center),
(b) => { data.SingleValuePublish = b; });
// Row : single value first time
AnyUiUIElement.SetBoolFromControl(
helper.AddSmallCheckBoxTo(g, ++row, 2,
content: "First time",
isChecked: data.SingleValueFirstTime,
verticalContentAlignment: AnyUiVerticalAlignment.Center),
(b) => { data.SingleValueFirstTime = b; });
// Row : Topic single value publish
helper.Set(
helper.AddSmallLabelTo(g, ++row, 0, content: "Topic:", verticalCenter: true),
horizontalAlignment: AnyUiHorizontalAlignment.Right,
horizontalContentAlignment: AnyUiHorizontalAlignment.Right);
AnyUiUIElement.SetStringFromControl(
helper.AddSmallTextBoxTo(g, row, 2,
margin: new AnyUiThickness(0, 2, 2, 2),
text: "" + data.SingleValueTopic,
verticalCenter: true),
(str) => { data.SingleValueTopic = str; });
// give back
return g;
});
if (!ticket.ScriptMode)
{
// do the dialogue
if (!(await DisplayContext.StartFlyoverModalAsync(uc1)))
return;
// stop
await Task.Delay(2000);
}
#endif
// make a logger
agent.Logger = new AasxMqttClient.GrapevineLoggerToStoredPrints();
// make listing flyout
var uc2 = new LogMessageFlyout("AASX MQTT Publisher", "Starting MQTT Client ..", () =>
{
var sp = agent.Logger.Pop();
return sp;
});
uc2.Agent = agent;
// start MQTT Client as a worker (will start in the background)
agent.Client = new AasxMqttClient.MqttClient();
agent.Worker = new BackgroundWorker();
agent.Worker.DoWork += async (s1, e1) =>
{
try
{
await agent.Client.StartAsync(PackageCentral.Main, agent.DiaData, agent.Logger);
}
catch (Exception e)
{
agent.Logger.Error(e);
}
};
agent.Worker.RunWorkerAsync();
// wire events
agent.EventTriggered += (ev) =>
{
// trivial
if (ev == null)
return;
// safe
try
{
// potentially expensive .. get more context for the event source
ExtendEnvironment.ReferableRootInfo foundRI = null;
if (PackageCentral != null && ev.Source?.Keys != null)
foreach (var pck in PackageCentral.GetAllPackageEnv())
{
var ri = new ExtendEnvironment.ReferableRootInfo();
var res = pck?.AasEnv?.FindReferableByReference(ev.Source, rootInfo: ri);
if (res != null && ri.IsValid)
foundRI = ri;
}
// publish
agent.Client?.PublishEvent(ev, foundRI);
}
catch (Exception e)
{
agent.Logger.Error(e);
}
};
agent.GenerateFlyoutMini = () =>
{
var storedAgent = agent;
var mini = new LogMessageMiniFlyout("AASX MQTT Publisher", "Executing minimized ..", () =>
{
var sp = storedAgent.Logger.Pop();
return sp;
});
mini.Agent = agent;
return mini;
};
// modal dialogue
this.StartFlyoverModal(uc2, closingAction: () => { });
}
static string lastConnectInput = "";
public async void CommandBinding_ConnectRest()
{
var uc = new TextBoxFlyout("REST server adress:", AnyUiMessageBoxImage.Question);
if (lastConnectInput == "")
{
uc.Text = "http://" + Options.Curr.RestServerHost + ":" + Options.Curr.RestServerPort;
}
else
{
uc.Text = lastConnectInput;
}
this.StartFlyoverModal(uc);
if (uc.Result)
{
string value = "";
string input = uc.Text.ToLower();
lastConnectInput = input;
if (!input.StartsWith("http://localhost:1111"))
{