-
Notifications
You must be signed in to change notification settings - Fork 4
/
Program.cs
896 lines (805 loc) · 46.4 KB
/
Program.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
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
using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using CommandLine;
using System.Linq;
using System.Xml.Linq;
using MultiplyChannels.Signing;
// using Knx.Ets.Xml.ObjectModel;
//using Knx.Ets.Converter.ConverterEngine;
namespace MultiplyChannels {
struct EtsVersion {
public EtsVersion(string iSubdir, string iEts) {
Subdir = iSubdir;
ETS = iEts;
}
public string Subdir { get; private set; }
public string ETS { get; private set; }
}
class Program {
private static Dictionary<string, EtsVersion> EtsVersions = new Dictionary<string, EtsVersion>() {
{"http://knx.org/xml/project/11", new EtsVersion("4.0.1997.50261", "ETS 4")},
{"http://knx.org/xml/project/12", new EtsVersion("5.0.204.12971", "ETS 5")},
{"http://knx.org/xml/project/13", new EtsVersion("5.1.84.17602", "ETS 5.5")},
{"http://knx.org/xml/project/14", new EtsVersion("5.6.241.33672", "ETS 5.6")},
{"http://knx.org/xml/project/20", new EtsVersion("5.7", "ETS 5.7")},
{"http://knx.org/xml/project/21", new EtsVersion("6.0", "ETS 6.0")}
};
private const string gtoolName = "KNX MT";
private const string gtoolVersion = "5.1.255.16695";
//installation path of a valid ETS instance (only ETS4 or ETS5 supported)
private static List<string> gPathETS = new List<string> {
@"C:\Program Files (x86)\ETS6",
@"C:\Program Files (x86)\ETS5",
AppDomain.CurrentDomain.BaseDirectory
};
static string FindEtsPath(string lXmlns) {
string lResult = "";
int lProjectVersion = int.Parse(lXmlns.Substring(27));
if (EtsVersions.ContainsKey(lXmlns)) {
string lEts = "";
//if we found an ets6, we can generate all versions with it
if(Directory.Exists(@"C:\Program Files (x86)\ETS6")) {
lResult = @"C:\Program Files (x86)\ETS6";
lEts = "ETS 6";
}
//if we found ets6 dlls, we can generate all versions with it
if(Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CV", "6.0"))) {
lResult = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CV", "6.0");
lEts = "ETS 6 (local)";
}
//else search for an older ETS or CV files
if(string.IsNullOrEmpty(lResult)) {
string lSubdir = EtsVersions[lXmlns].Subdir;
lEts = EtsVersions[lXmlns].ETS;
foreach(string path in gPathETS) {
if(!Directory.Exists(path)) continue;
if(Directory.Exists(Path.Combine(path, "CV", lSubdir))) //If subdir exists everything ist fine
{
lResult = Path.Combine(path, "CV", lSubdir);
break;
}
else { //otherwise it might be the file in the root folder
if(!File.Exists(Path.Combine(path, "Knx.Ets.XmlSigning.dll"))) continue;
System.Diagnostics.FileVersionInfo versionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(Path.Combine(path, "Knx.Ets.XmlSigning.dll"));
string newVersion = versionInfo.FileVersion;
if (lSubdir.Split('.').Length == 2) newVersion = string.Join('.', newVersion.Split('.').Take(2));
// if(newVersion.Split('.').Length != 4) newVersion += ".0";
if(lSubdir == newVersion)
{
lResult = path;
break;
}
}
}
}
if (!string.IsNullOrEmpty(lResult))
Console.WriteLine("Found namespace {1} in xml, will use {0} for conversion... (Path: {2})", lEts, lXmlns, lResult);
}
if (string.IsNullOrEmpty(lResult)) Console.WriteLine("No valid conversion engine available for xmlns {0}", lXmlns);
return lResult;
}
public static void WriteFail(ref bool iFail, string iFormat, params object[] iParams) {
if (!iFail) Console.WriteLine();
Console.WriteLine(" --> " + iFormat, iParams);
iFail = true;
}
// Node cache
static Dictionary<string, XmlNode> gIds = new Dictionary<string, XmlNode>();
static XmlNode GetNodeById(XmlNode iRootNode, string iId) {
XmlNode lResult = null;
if (gIds.ContainsKey(iId)) {
lResult = gIds[iId];
} else {
lResult = iRootNode.SelectSingleNode(string.Format("//*[@Id='{0}']", iId));
if (lResult != null) gIds.Add(iId, lResult);
}
return lResult;
}
private static void CreateComment(XmlDocument iTargetNode, XmlNode iNode, string iId, string iSuffix = "") {
string lNodeId = iId.Substring(0, iId.LastIndexOf("_R"));
string lTextId = iId;
string lNodeName = "Id-mismatch! Name not found!";
string lText = "Id-mismatch! Text not found!";
if (gIds.ContainsKey(lNodeId)) lNodeName = gIds[lNodeId].NodeAttr("Name");
if (gIds.ContainsKey(lTextId) && gIds[lTextId].NodeAttr("Text") == "") lTextId = lNodeId;
if (gIds.ContainsKey(lTextId)) lText = gIds[lTextId].NodeAttr("Text");
XmlComment lComment = iTargetNode.CreateComment(string.Format(" {0}{3} {1} '{2}'", iNode.Name, lNodeName, lText, iSuffix));
iNode.ParentNode.InsertBefore(lComment, iNode);
}
static bool ProcessSanityChecks(XmlDocument iTargetNode) {
Console.WriteLine();
Console.WriteLine("Sanity checks... ");
bool lFail = false;
Console.Write("- Id-Uniqueness...");
bool lFailPart = false;
XmlNodeList lNodes = iTargetNode.SelectNodes("//*[@Id]");
foreach (XmlNode lNode in lNodes) {
string lId = lNode.Attributes.GetNamedItem("Id").Value;
if (gIds.ContainsKey(lId)) {
WriteFail(ref lFailPart, "{0} is a duplicate Id in {1}", lId, lNode.NodeAttr("Name"));
} else {
gIds.Add(lId, lNode);
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
Console.Write("- Id-R_Suffix-Uniqueness...");
lFailPart = false;
Dictionary<string, bool> lParameterSuffixes = new Dictionary<string, bool>();
Dictionary<string, bool> lComObjectSuffixes = new Dictionary<string, bool>();
foreach (XmlNode lNode in lNodes) {
string lId = lNode.Attributes.GetNamedItem("Id").Value;
int lPos = lId.LastIndexOf("_R-");
Dictionary<string, bool> lSuffixes = null;
if (lPos > 0) {
if (lId.Substring(0, lPos).Contains("_P-"))
lSuffixes = lParameterSuffixes;
else if (lId.Substring(0, lPos).Contains("_O-"))
lSuffixes = lComObjectSuffixes;
if (lSuffixes != null) {
string lSuffix = lId.Substring(lPos + 3);
if (lSuffixes.ContainsKey(lSuffix)) {
WriteFail(ref lFailPart, "{0} is a duplicate _R-Suffix in {1}", lId, lNode.Name);
} else {
lSuffixes.Add(lSuffix, false);
}
}
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- RefId-Integrity...");
lNodes = iTargetNode.SelectNodes("//*[@RefId]");
foreach (XmlNode lNode in lNodes) {
if (lNode.Name != "Manufacturer") {
string lRefId = lNode.Attributes.GetNamedItem("RefId").Value;
if (!gIds.ContainsKey(lRefId)) {
WriteFail(ref lFailPart, "{0} is referenced in {1} {2}, but not defined", lRefId, lNode.Name, lNode.NodeAttr("Name"));
} else if (lRefId.Contains("_R")) {
CreateComment(iTargetNode, lNode, lRefId);
}
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- ParamRefId-Integrity...");
lNodes = iTargetNode.SelectNodes("//*[@ParamRefId]");
foreach (XmlNode lNode in lNodes) {
if (lNode.Name != "Manufacturer") {
string lParamRefId = lNode.Attributes.GetNamedItem("ParamRefId").Value;
if (!gIds.ContainsKey(lParamRefId)) {
WriteFail(ref lFailPart, "{0} is referenced in {1} {2}, but not defined", lParamRefId, lNode.Name, lNode.NodeAttr("Name"));
} else {
CreateComment(iTargetNode, lNode, lParamRefId);
}
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- TextParameterRefId-Integrity...");
lNodes = iTargetNode.SelectNodes("//*[@TextParameterRefId]");
foreach (XmlNode lNode in lNodes) {
string lTextParamRefId = lNode.Attributes.GetNamedItem("TextParameterRefId").Value;
if (!gIds.ContainsKey(lTextParamRefId)) {
WriteFail(ref lFailPart, "{0} is referenced in {1} {2}, but not defined", lTextParamRefId, lNode.Name, lNode.NodeAttr("Name"));
} else {
CreateComment(iTargetNode, lNode, lTextParamRefId);
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- SourceParamRefRef-Integrity...");
lNodes = iTargetNode.SelectNodes("//*[@SourceParamRefRef]");
foreach (XmlNode lNode in lNodes) {
string lSourceParamRefRef = lNode.Attributes.GetNamedItem("SourceParamRefRef").Value;
if (!gIds.ContainsKey(lSourceParamRefRef)) {
WriteFail(ref lFailPart, "{0} is referenced in {1} {2}, but not defined", lSourceParamRefRef, lNode.Name, lNode.NodeAttr("Name"));
} else {
CreateComment(iTargetNode, lNode, lSourceParamRefRef, "-Source");
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- TargetParamRefRef-Integrity...");
lNodes = iTargetNode.SelectNodes("//*[@TargetParamRefRef]");
foreach (XmlNode lNode in lNodes) {
string lTargetParamRefRef = lNode.Attributes.GetNamedItem("TargetParamRefRef").Value;
if (!gIds.ContainsKey(lTargetParamRefRef)) {
WriteFail(ref lFailPart, "{0} is referenced in {1} {2}, but not defined", lTargetParamRefRef, lNode.Name, lNode.NodeAttr("Name"));
} else {
CreateComment(iTargetNode, lNode, lTargetParamRefRef, "-Target");
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- ParameterType-Integrity...");
lNodes = iTargetNode.SelectNodes("//*[@ParameterType]");
foreach (XmlNode lNode in lNodes) {
string lParameterType = lNode.Attributes.GetNamedItem("ParameterType").Value;
if (!gIds.ContainsKey(lParameterType)) {
WriteFail(ref lFailPart, "{0} is referenced in {1} {2}, but not defined", lParameterType, lNode.Name, lNode.NodeAttr("Name"));
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- Union-Integrity...");
lNodes = iTargetNode.SelectNodes("//Union");
foreach (XmlNode lNode in lNodes) {
string lSize = lNode.NodeAttr("SizeInBit");
if (lSize == "") {
WriteFail(ref lFailPart, "Union without SizeInBit-Attribute found");
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
Console.Write("- Parameter-Name-Uniqueness...");
lFailPart = false;
lNodes = iTargetNode.SelectNodes("//Parameter[@Name]");
Dictionary<string, bool> lParameterNames = new Dictionary<string, bool>();
foreach (XmlNode lNode in lNodes) {
string lName = lNode.Attributes.GetNamedItem("Name").Value;
if (lParameterNames.ContainsKey(lName)) {
WriteFail(ref lFailPart, "{0} is a duplicate Name in Parameter '{1}'", lName, lNode.NodeAttr("Text"));
} else {
lParameterNames.Add(lName, true);
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- Parameter-Value-Integrity...");
lNodes = iTargetNode.SelectNodes("//Parameter");
foreach (XmlNode lNode in lNodes) {
// we add the node to parameter cache
string lNodeId = lNode.NodeAttr("Id");
string lMessage = string.Format("Parameter {0}", lNode.NodeAttr("Name"));
string lParameterValue = lNode.NodeAttr("Value", null);
if (lParameterValue == null) {
WriteFail(ref lFailPart, "{0} has no Value attribute", lMessage);
}
lFailPart = CheckParameterValueIntegrity(iTargetNode, lFailPart, lNode, lParameterValue, lMessage);
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
bool lSkipTest = false;
Console.Write("- ParameterRef-Value-Integrity...");
lNodes = iTargetNode.SelectNodes("//ParameterRef[@Value]");
foreach (XmlNode lNode in lNodes) {
string lParameterRefValue = lNode.NodeAttr("Value");
// find parameter
XmlNode lParameterNode = GetNodeById(iTargetNode, lNode.NodeAttr("RefId"));
if (lParameterNode == null) {
lSkipTest = true;
break;
}
string lMessage = string.Format("ParameterRef {0}, referencing Parameter {1},", lNode.NodeAttr("Id"), lParameterNode.NodeAttr("Name"));
lFailPart = CheckParameterValueIntegrity(iTargetNode, lFailPart, lParameterNode, lParameterRefValue, lMessage);
}
if (lSkipTest) {
WriteFail(ref lFailPart, "Test not possible due to Errors in ParameterRef definitions (sove above problems first)");
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
Console.Write("- ComObject-Name-Uniqueness...");
lFailPart = false;
lNodes = iTargetNode.SelectNodes("//ComObject[@Name]");
Dictionary<string, bool> lKoNames = new Dictionary<string, bool>();
foreach (XmlNode lNode in lNodes) {
string lName = lNode.Attributes.GetNamedItem("Name").Value;
if (lKoNames.ContainsKey(lName)) {
WriteFail(ref lFailPart, "{0} is a duplicate Name in ComObject number {1}", lName, lNode.NodeAttr("Number"));
} else {
lKoNames.Add(lName, true);
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
Console.Write("- ComObject-Number-Uniqueness...");
lFailPart = false;
lNodes = iTargetNode.SelectNodes("//ComObject[@Number]");
Dictionary<int, bool> lKoNumbers = new Dictionary<int, bool>();
foreach (XmlNode lNode in lNodes) {
int lNumber = 0;
bool lIsInt = int.TryParse(lNode.Attributes.GetNamedItem("Number").Value, out lNumber);
if (lIsInt) {
if (lKoNumbers.ContainsKey(lNumber)) {
WriteFail(ref lFailPart, "{0} is a duplicate Number in ComObject with name {1}", lNumber, lNode.NodeAttr("Name"));
} else {
lKoNumbers.Add(lNumber, true);
}
} else {
WriteFail(ref lFailPart, "ComObject.Number is not an Integer in ComObject with name {0}", lNode.NodeAttr("Name"));
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
Console.Write("- Id-Namespace...");
// find refid
lFailPart = false;
XmlNode lApplicationProgramNode = iTargetNode.SelectSingleNode("/KNX/ManufacturerData/Manufacturer/ApplicationPrograms/ApplicationProgram");
string lApplicationId = lApplicationProgramNode.Attributes.GetNamedItem("Id").Value;
string lRefNs = lApplicationId; //.Replace("M-00FA_A", "");
if(lRefNs.StartsWith("M-")) lRefNs = lRefNs.Substring(8);
// check all nodes according to refid
lNodes = iTargetNode.SelectNodes("//*/@*[string-length() > '13']");
foreach (XmlNode lNode in lNodes) {
if (lNode.Value != null) {
var lMatch = Regex.Match(lNode.Value, "-[0-9A-F]{4}-[0-9A-F]{2}-[0-9A-F]{4}");
if (lMatch.Success) {
if (lMatch.Value != lRefNs) {
XmlElement lElement = ((XmlAttribute)lNode).OwnerElement;
WriteFail(ref lFailPart, "{0} of node {2} {3} is in a different namespace than application namespace {1}", lMatch.Value, lRefNs, lElement.Name, lElement.NodeAttr("Name"));
}
}
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
Console.Write("- Id-Format...");
// An id has to fulfill a specific format
lFailPart = false;
string lIdPart = "";
foreach (var lKeyValuePair in gIds) {
string lId = lKeyValuePair.Key;
string lIdMatch = "";
string lIdMatchReadable = "";
lId = lId.Replace(lApplicationId, "");
XmlNode lElement = lKeyValuePair.Value;
switch (lElement.Name)
{
case "Parameter":
if (lElement.ParentNode.Name == "Union") {
lIdPart = "_UP-";
} else {
lIdPart = "_P-";
}
lIdMatch = lIdPart + @"[1-3]?\d\d{6}";
lIdMatchReadable = lIdPart + "tcccnnn";
break;
case "ComObject":
lIdPart = "_O-";
lIdMatch = lIdPart + @"[1-3]?\d\d{6}";
lIdMatchReadable = lIdPart + "tcccnnn";
break;
case "ParameterType":
case "Enumeration":
lIdPart = "_PT-";
break;
case "ParameterRef":
case "ComObjectRef":
lIdPart = "_R-";
if (lId.Contains(lIdPart)) lIdPart = "";
lIdMatch = @"([1-3]?\d\d{6})_R-\1\d\d";
lIdMatchReadable = "tcccnnn_R-tcccnnnrr";
break;
case "ParameterBlock":
lIdPart = "_PB-";
break;
case "ParameterSeparator":
lIdPart = "_PS-";
break;
case "Channel":
lIdPart = "_CH-";
break;
case "Row":
lIdPart = "_R-";
if (lId.Contains(lIdPart)) lIdPart = "_PB-";
break;
case "Column":
lIdPart = "_C-";
if (lId.Contains(lIdPart)) lIdPart = "_PB-";
break;
default:
lIdPart = "";
break;
}
if (lIdPart != "" && !lId.StartsWith(lIdPart)) {
WriteFail(ref lFailPart, "{0} {1} has the Id={2}, but this Id is missing the required part {3}", lElement.Name, lElement.NodeAttr("Name"), lKeyValuePair.Key, lIdPart);
}
if (lIdMatch != "" && !Regex.IsMatch(lId, lIdMatch)) {
WriteFail(ref lFailPart, "{0} {1} has the Id={2}, but this Id has not the OpenKNX-Format {3}", lElement.Name, lElement.NodeAttr("Name"), lKeyValuePair.Key, lIdMatchReadable);
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- Serial number...");
lNodes = iTargetNode.SelectNodes("//*[@SerialNumber]");
foreach (XmlNode lNode in lNodes) {
string lSerialNumber = lNode.Attributes.GetNamedItem("SerialNumber").Value;
if (lSerialNumber.Contains("-")) {
WriteFail(ref lFailPart, "Hardware.SerialNumber={0}, it contains a dash (-), this will cause problems in knxprod.", lSerialNumber);
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
lFailPart = false;
Console.Write("- Application data...");
lNodes = iTargetNode.SelectNodes("//ApplicationProgram");
foreach (XmlNode lNode in lNodes) {
int lNumber = -1;
bool lIsInt = int.TryParse(lNode.Attributes.GetNamedItem("ApplicationNumber").Value, out lNumber);
if (!lIsInt || lNumber < 0) {
WriteFail(ref lFailPart, "Applicationprogram.ApplicationNumber is incorrect or could not be parsed");
}
lNumber = -1;
lIsInt = int.TryParse(lNode.Attributes.GetNamedItem("ApplicationVersion").Value, out lNumber);
if (!lIsInt || lNumber < 0) {
WriteFail(ref lFailPart, "Applicationprogram.ApplicationVersion is incorrect or could not be parsed");
}
}
if (!lFailPart) Console.WriteLine(" OK");
lFail = lFail || lFailPart;
return !lFail;
}
private static bool CheckParameterValueIntegrity(XmlNode iTargetNode, bool iFailPart, XmlNode iParameterNode, string iValue, string iMessage) {
string lParameterType = iParameterNode.NodeAttr("ParameterType");
if (lParameterType == "") {
WriteFail(ref iFailPart, "Parameter {0} has no ParameterType attribute", iParameterNode.NodeAttr("Name"));
}
if (iValue != null && lParameterType != "") {
// find parameter type
XmlNode lParameterTypeNode = iTargetNode.SelectSingleNode(string.Format("//ParameterType[@Id='{0}']", lParameterType));
if (lParameterTypeNode != null) {
// get first child ignoring comments
XmlNode lChild = lParameterTypeNode.ChildNodes[0];
while (lChild != null && lChild.NodeType != XmlNodeType.Element) lChild = lChild.NextSibling;
int sizeInBit;
long maxSize = 0;
switch(lChild.Name)
{
case "TypeText":
if (!int.TryParse(lChild.Attributes["SizeInBit"]?.Value, out sizeInBit))
WriteFail(ref iFailPart, "SizeInBit of {0} cannot be converted to a number, value is '{1}'", iMessage, lChild.Attributes["SizeInBit"]?.Value ?? "empty");
maxSize = sizeInBit / 8;
break;
case "TypeFloat":
//There is no SizeInBit attribute
break;
case "TypeColor":
//There is no SizeInBit attribute
break;
default:
if (!int.TryParse(lChild.Attributes["SizeInBit"]?.Value, out sizeInBit))
WriteFail(ref iFailPart, "SizeInBit of {0} cannot be converted to a number, value is '{1}'", iMessage, lChild.Attributes["SizeInBit"]?.Value ?? "empty");
maxSize = Convert.ToInt64(Math.Pow(2, int.Parse(lChild.Attributes["SizeInBit"]?.Value ?? "0")));
break;
}
int min=0, max=0;
switch (lChild.Name) {
case "TypeNumber":
int lDummyInt;
bool lSuccess = int.TryParse(iValue, out lDummyInt);
if (!lSuccess) {
WriteFail(ref iFailPart, "Value of {0} cannot be converted to a number, value is '{1}'", iMessage, iValue);
}
if(!int.TryParse(lChild.Attributes["minInclusive"]?.Value, out min))
WriteFail(ref iFailPart, "MinInclusive of {0} cannot be converted to a number, value is '{1}'", iMessage, lChild.Attributes["minInclusive"]?.Value ?? "empty");
if(!int.TryParse(lChild.Attributes["maxInclusive"]?.Value, out max))
WriteFail(ref iFailPart, "MaxInclusive of {0} cannot be converted to a number, value is '{1}'", iMessage, lChild.Attributes["minInclusive"]?.Value ?? "empty");
switch(lChild.Attributes["Type"]?.Value) {
case "unsignedInt":
if(min < 0)
WriteFail(ref iFailPart, "MinInclusive of {0} cannot be smaller than 0, value is '{1}'", iMessage, min);
if(max >= maxSize)
WriteFail(ref iFailPart, "MaxInclusive of {0} cannot be greater than {1}, value is '{2}'", iMessage, maxSize, max);
break;
case "signedInt":
if(min < ((maxSize/2)*(-1)))
WriteFail(ref iFailPart, "MinInclusive of {0} cannot be smaller than {1}, value is '{2}'", iMessage, ((maxSize/2)*(-1)), min);
if(max > ((maxSize/2)-1))
WriteFail(ref iFailPart, "MinInclusive of {0} cannot be greater than {1}, value is '{2}'", iMessage, ((maxSize/2)-1), max);
break;
}
//TODO check value
break;
case "TypeFloat":
float lDummyFloat;
lSuccess = float.TryParse(iValue, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out lDummyFloat);
if (!lSuccess || iValue.Contains(",")) {
WriteFail(ref iFailPart, "Value of {0} cannot be converted to a float, value is '{1}'", iMessage, iValue);
}
//TODO check value
break;
case "TypeRestriction":
lSuccess = false;
int maxEnumValue = -1;
foreach (XmlNode lEnumeration in lChild.ChildNodes) {
if (lEnumeration.Name == "Enumeration") {
if (lEnumeration.NodeAttr("Value") == iValue) {
lSuccess = true;
}
int enumValue = 0;
if(!int.TryParse(lEnumeration.Attributes["Value"]?.Value, out enumValue))
WriteFail(ref iFailPart, "Enum Value of {2} in {0} cannot be converted to an int, value is '{1}'", iMessage, iValue, lParameterType);
else {
if(enumValue > maxEnumValue)
maxEnumValue = enumValue;
}
}
}
if (!lSuccess) {
WriteFail(ref iFailPart, "Value of {0} is not contained in enumeration {2}, value is '{1}'", iMessage, iValue, lParameterType);
}
if(maxEnumValue >= maxSize)
WriteFail(ref iFailPart, "Max Enum Value of {0} can not be greater than {2}, value is '{1}'", iMessage, maxEnumValue, maxSize);
break;
case "TypeText":
//TODO add string length validation
if(iValue.Length > maxSize)
WriteFail(ref iFailPart, "String Length of {0} can not be greater than {2}, length is '{1}'", iMessage, maxSize, iValue.Length);
break;
default:
break;
}
}
}
return iFailPart;
}
#region Reflection
private static object InvokeMethod(Type type, string methodName, object[] args) {
var mi = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic);
return mi.Invoke(null, args);
}
private static void SetProperty(Type type, string propertyName, object value) {
PropertyInfo prop = type.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static);
prop.SetValue(null, value, null);
}
#endregion
// private static void ExportXsd(string iXsdFileName) {
// using (var fileStream = new FileStream("knx.xsd", FileMode.Create))
// using (var stream = DocumentSet.GetXmlSchemaDocumentAsStream(KnxXmlSchemaVersion.Version14)) {
// while (true) {
// var buffer = new byte[4096];
// var count = stream.Read(buffer, 0, 4096);
// if (count == 0)
// break;
// fileStream.Write(buffer, 0, count);
// }
// }
// }
private static void ExportKnxprod(string iPathETS, string iXml, string iKnxprodFileName, bool iIsDebug) {
if (iPathETS == "") return;
try {
XDocument xdoc = XDocument.Parse(iXml);
string ns = xdoc.Root.Name.NamespaceName;
XElement xmanu = xdoc.Root.Element(XName.Get("ManufacturerData", ns)).Element(XName.Get("Manufacturer", ns));
string manuId = xmanu.Attribute("RefId").Value;
string localPath = AppDomain.CurrentDomain.BaseDirectory;
if(Directory.Exists(Path.Combine(localPath, "Temp")))
Directory.Delete(Path.Combine(localPath, "Temp"), true);
Directory.CreateDirectory(Path.Combine(localPath, "Temp"));
Directory.CreateDirectory(Path.Combine(localPath, "Temp", manuId)); //Get real Manu
XElement xcata = xmanu.Element(XName.Get("Catalog", ns));
XElement xhard = xmanu.Element(XName.Get("Hardware", ns));
XElement xappl = xmanu.Element(XName.Get("ApplicationPrograms", ns));
//Save Catalog
xhard.Remove();
xappl.Remove();
xdoc.Save(Path.Combine(localPath, "Temp", manuId, "Catalog.xml"));
xcata.Remove();
xmanu.Add(xhard);
xdoc.Save(Path.Combine(localPath, "Temp", manuId, "Hardware.xml"));
xhard.Remove();
xmanu.Add(xappl);
string appId = xappl.Elements(XName.Get("ApplicationProgram", ns)).First().Attribute("Id").Value;
xdoc.Save(Path.Combine(localPath, "Temp", manuId, $"{appId}.xml"));
IDictionary<string, string> applProgIdMappings = new Dictionary<string, string>();
IDictionary<string, string> applProgHashes = new Dictionary<string, string>();
IDictionary<string, string> mapBaggageIdToFileIntegrity = new Dictionary<string, string>(50);
FileInfo hwFileInfo = new FileInfo(Path.Combine(localPath, "Temp", manuId, "Hardware.xml"));
FileInfo catalogFileInfo = new FileInfo(Path.Combine(localPath, "Temp", manuId, "Catalog.xml"));
FileInfo appInfo = new FileInfo(Path.Combine(localPath, "Temp", manuId, $"{appId}.xml"));
int nsVersion = int.Parse(ns.Substring(ns.LastIndexOf('/')+1));
ApplicationProgramHasher aph = new ApplicationProgramHasher(appInfo, mapBaggageIdToFileIntegrity, iPathETS, nsVersion, true);
aph.Hash(); //ETS6 benutzt ApplicationProgramStoreHasher und die Funktion HashStore!
applProgIdMappings.Add(aph.OldApplProgId, aph.NewApplProgId);
if (!applProgHashes.ContainsKey(aph.NewApplProgId))
applProgHashes.Add(aph.NewApplProgId, aph.GeneratedHashString);
HardwareSigner hws = new HardwareSigner(hwFileInfo, applProgIdMappings, applProgHashes, iPathETS, nsVersion, true);
hws.SignFile();
IDictionary<string, string> hardware2ProgramIdMapping = hws.OldNewIdMappings;
CatalogIdPatcher cip = new CatalogIdPatcher(catalogFileInfo, hardware2ProgramIdMapping, iPathETS, nsVersion);
cip.Patch();
XmlSigning.SignDirectory(Path.Combine(localPath, "Temp", manuId), iPathETS);
Directory.CreateDirectory(Path.Combine(localPath, "Masters"));
ns = ns.Substring(ns.LastIndexOf("/")+1);
if(!File.Exists(Path.Combine(localPath, "Masters", $"project-{ns}.xml"))) {
var client = new System.Net.WebClient();
client.DownloadFile($"https://update.knx.org/data/XML/project-{ns}/knx_master.xml", Path.Combine(localPath, "Masters", $"project-{ns}.xml"));
}
File.Copy(Path.Combine(localPath, "Masters", $"project-{ns}.xml"), Path.Combine(localPath, "Temp", $"knx_master.xml"));
if(File.Exists(iKnxprodFileName)) File.Delete(iKnxprodFileName);
System.IO.Compression.ZipFile.CreateFromDirectory(Path.Combine(localPath, "Temp"), iKnxprodFileName);
if(!iIsDebug)
System.IO.Directory.Delete(Path.Combine(localPath, "Temp"), true);
Console.WriteLine("Output of {0} successful", iKnxprodFileName);
}
catch (Exception ex) {
Console.WriteLine("Error during knxprod creation:");
Console.WriteLine(ex.ToString());
}
}
class EtsOptions {
private string mXmlFileName;
[Value(0, MetaName = "xml file name", Required = true, HelpText = "Xml file name", MetaValue = "FILE")]
public string XmlFileName {
get { return mXmlFileName; }
set { mXmlFileName = Path.ChangeExtension(value, "xml"); }
}
}
[Verb("new", HelpText = "Create new xml file with a fully commented and working mini exaple")]
class NewOptions : CreateOptions {
[Option('x', "ProductName", Required = true, HelpText = "Product name - appears in catalog and in property dialog", MetaValue = "STRING")]
public string ProductName { get; set; }
[Option('n', "AppName", Required = false, HelpText = "(Default: Product name) Application name - appears in catalog and necessary for application upgrades", MetaValue = "STRING")]
public string ApplicationName { get; set; } = "";
[Option('a', "AppNumber", Required = true, HelpText = "Application number - has to be unique per manufacturer", MetaValue = "INT")]
public int? ApplicationNumber { get; set; }
[Option('y', "AppVersion", Required = false, Default = 1, HelpText = "Application version - necessary for application upgrades", MetaValue = "INT")]
public int? ApplicationVersion { get; set; } = 1;
[Option('w', "HardwareName", Required = false, HelpText = "(Default: Product name) Hardware name - not visible in ETS", MetaValue = "STRING")]
public string HardwareName { get; set; } = "";
[Option('v', "HardwareVersion", Required = false, Default = 1, HelpText = "Hardware version - not visible in ETS, required for registration", MetaValue = "INT")]
public int? HardwareVersion { get; set; } = 1;
[Option('s', "SerialNumber", Required = false, HelpText = "(Default: Application number) Hardware serial number - not visible in ETS, requered for hardware-id", MetaValue = "STRING")]
public string SerialNumber { get; set; } = "";
[Option('m', "MediumType", Required = false, Default = "TP", HelpText = "Medium type", MetaValue = "TP,IP,both")]
public string MediumType { get; set; } = "TP";
[Option('#', "OrderNumber", Required = false, HelpText = "(Default: Application number) Order number - appears in catalog and in property info tab", MetaValue = "STRING")]
public string OrderNumber { get; set; } = "";
public string MediumTypes {
get {
string lResult = "MT-0";
if (MediumType == "IP") {
lResult = "MT-5";
} else if (MediumType == "both") {
lResult = "MT-0 MT-5";
}
return lResult;
}
}
public string MaskVersion {
get {
string lResult = "MV-07B0";
if (MediumType == "IP") lResult = "MV-57B0";
return lResult;
}
}
}
[Verb("knxprod", HelpText = "Create knxprod file from given xml file")]
class KnxprodOptions : EtsOptions {
[Option('o', "Output", Required = false, HelpText = "Output file name", MetaValue = "FILE")]
public string OutputFile { get; set; } = "";
}
[Verb("create", HelpText = "Process given xml file with all includes and create knxprod")]
class CreateOptions : KnxprodOptions {
[Option('h', "HeaderFileName", Required = false, HelpText = "Header file name", MetaValue = "FILE")]
public string HeaderFileName { get; set; } = "";
[Option('p', "Prefix", Required = false, HelpText = "Prefix for generated contant names in header file", MetaValue = "STRING")]
public string Prefix { get; set; } = "";
[Option('d', "Debug", Required = false, HelpText = "Additional output of <xmlfile>.debug.xml, this file is the input file for knxprod converter")]
public bool Debug { get; set; } = false;
}
[Verb("check", HelpText = "execute sanity checks on given xml file")]
class CheckOptions : EtsOptions {
}
static int Main(string[] args) {
return CommandLine.Parser.Default.ParseArguments<CreateOptions, CheckOptions, KnxprodOptions, NewOptions>(args)
.MapResult(
(NewOptions opts) => VerbNew(opts),
(CreateOptions opts) => VerbCreate(opts),
(KnxprodOptions opts) => VerbKnxprod(opts),
(CheckOptions opts) => VerbCheck(opts),
errs => 1);
}
static private void WriteVersion() {
Console.WriteLine("{0} {1}", typeof(Program).Assembly.GetName().Name, typeof(Program).Assembly.GetName().Version);
}
static private int VerbNew(NewOptions opts) {
WriteVersion();
// Handle defaults
if (opts.ApplicationName == "") opts.ApplicationName = opts.ProductName;
if (opts.HardwareName == "") opts.HardwareName = opts.ProductName;
if (opts.SerialNumber == "") opts.SerialNumber = opts.ApplicationNumber.ToString();
if (opts.OrderNumber == "") opts.OrderNumber = opts.ApplicationNumber.ToString();
// checks
bool lFail = false;
if (opts.ApplicationNumber > 65535) {
Console.WriteLine("ApplicationNumber has to be less than 65536!");
lFail = true;
}
if (opts.SerialNumber.Contains("-")) {
Console.WriteLine("SerialNumber must not contain a dash (-) character!");
lFail = true;
}
if (opts.OrderNumber.Contains("-")) {
Console.WriteLine("OrderNumber must not contain a dash (-) character!");
lFail = true;
}
if (lFail) return 1;
// create initial xml file
string lXmlFile = "";
var assembly = Assembly.GetEntryAssembly();
var resourceStream = assembly.GetManifestResourceStream("MultiplyChannels.NewDevice.xml");
using (var reader = new StreamReader(resourceStream, Encoding.UTF8)) {
lXmlFile = reader.ReadToEnd();
}
lXmlFile = lXmlFile.Replace("%ApplicationName%", opts.ApplicationName);
lXmlFile = lXmlFile.Replace("%ApplicationNumber%", opts.ApplicationNumber.ToString());
lXmlFile = lXmlFile.Replace("%ApplicationVersion%", opts.ApplicationVersion.ToString());
lXmlFile = lXmlFile.Replace("%HardwareName%", opts.HardwareName);
lXmlFile = lXmlFile.Replace("%HardwareVersion%", opts.HardwareVersion.ToString());
lXmlFile = lXmlFile.Replace("%SerialNumber%", opts.SerialNumber);
lXmlFile = lXmlFile.Replace("%OrderNumber%", opts.OrderNumber);
lXmlFile = lXmlFile.Replace("%ProductName%", opts.ProductName);
lXmlFile = lXmlFile.Replace("%MaskVersion%", opts.MaskVersion);
lXmlFile = lXmlFile.Replace("%MediumTypes%", opts.MediumTypes);
Console.WriteLine("Creating xml file {0}", opts.XmlFileName);
File.WriteAllText(opts.XmlFileName, lXmlFile);
return VerbCreate(opts);
}
static private int VerbCreate(CreateOptions opts) {
WriteVersion();
string lHeaderFileName = Path.ChangeExtension(opts.XmlFileName, "h");
if (opts.HeaderFileName != "") lHeaderFileName = opts.HeaderFileName;
Console.WriteLine("Processing xml file {0}", opts.XmlFileName);
ProcessInclude lResult = ProcessInclude.Factory(opts.XmlFileName, lHeaderFileName, opts.Prefix);
lResult.Expand();
// We restore the original namespace in File
lResult.SetNamespace();
XmlDocument lXml = lResult.GetDocument();
bool lSuccess = ProcessSanityChecks(lXml);
string lTempXmlFileName = Path.GetTempFileName();
File.Delete(lTempXmlFileName);
if (opts.Debug) lTempXmlFileName = opts.XmlFileName;
lTempXmlFileName = Path.ChangeExtension(lTempXmlFileName, "debug.xml");
if (opts.Debug) Console.WriteLine("Writing debug file to {0}", lTempXmlFileName);
lXml.Save(lTempXmlFileName);
Console.WriteLine("Writing header file to {0}", lHeaderFileName);
File.WriteAllText(lHeaderFileName, lResult.HeaderGenerated);
string lOutputFileName = Path.ChangeExtension(opts.OutputFile, "knxprod");
if (opts.OutputFile == "") lOutputFileName = Path.ChangeExtension(opts.XmlFileName, "knxprod");
if (lSuccess) {
string lEtsPath = FindEtsPath(lResult.GetNamespace());
ExportKnxprod(lEtsPath, lXml.OuterXml, lOutputFileName, opts.Debug);
} else {
Console.WriteLine("--> Skipping creation of {0} due to check errors! <--", lOutputFileName);
}
return 0;
}
static private int VerbCheck(CheckOptions opts) {
WriteVersion();
string lFileName = Path.ChangeExtension(opts.XmlFileName, "xml");
Console.WriteLine("Reading and resolving xml file {0}", lFileName);
ProcessInclude lResult = ProcessInclude.Factory(opts.XmlFileName, "", "");
lResult.LoadAdvanced(lFileName);
return ProcessSanityChecks(lResult.GetDocument()) ? 0 : 1;
}
static private int VerbKnxprod(KnxprodOptions opts) {
WriteVersion();
string lOutputFileName = Path.ChangeExtension(opts.OutputFile, "knxprod");
if (opts.OutputFile == "") lOutputFileName = Path.ChangeExtension(opts.XmlFileName, "knxprod");
Console.WriteLine("Reading xml file {0} writing to {1}", opts.XmlFileName, lOutputFileName);
string xml = File.ReadAllText(opts.XmlFileName);
System.Text.RegularExpressions.Regex rs = new System.Text.RegularExpressions.Regex("xmlns=\"(http:\\/\\/knx\\.org\\/xml\\/project\\/[0-9]{1,2})\"");
System.Text.RegularExpressions.Match match = rs.Match(xml);
string lEtsPath = FindEtsPath(match.Groups[1].Value);
ExportKnxprod(lEtsPath, xml, lOutputFileName, false);
return 0;
}
}
}