-
Notifications
You must be signed in to change notification settings - Fork 47
/
Program.cs
627 lines (558 loc) · 28.3 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
using Mono.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ZigbeeNet.Hardware.ConBee;
using ZigBeeNet.App.Basic;
using ZigBeeNet.App.Discovery;
using ZigBeeNet.App.IasClient;
using ZigBeeNet.Database;
using ZigBeeNet.DataStore.Json;
using ZigBeeNet.DataStore.MongoDb;
using ZigBeeNet.Hardware.Digi.XBee;
using ZigBeeNet.Hardware.Ember;
using ZigBeeNet.Hardware.TI.CC2531;
using ZigBeeNet.Security;
using ZigBeeNet.Tranport.SerialPort;
using ZigBeeNet.Transaction;
using ZigBeeNet.Transport;
using ZigBeeNet.Util;
using ZigBeeNet.ZCL;
using ZigBeeNet.ZCL.Clusters;
using ZigBeeNet.ZCL.Clusters.ColorControl;
using ZigBeeNet.ZCL.Clusters.General;
using ZigBeeNet.ZCL.Clusters.LevelControl;
using ZigBeeNet.ZCL.Clusters.OnOff;
using ZigBeeNet.ZDO.Command;
using ZigBeeNet.ZDO.Field;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Debug;
#if USE_SERILOG
using Serilog;
using Serilog.Extensions.Logging;
#else
using Microsoft.Extensions.Logging.Console;
#endif
namespace ZigBeeNet.PlayGround
{
class Program
{
static Microsoft.Extensions.Logging.ILogger _logger;
static async Task Main(string[] args)
{
#if USE_SERILOG
// Configure Serilog
var seriLogger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console()
// if you want to get the SourceContext (name of the class in most case) replace above line by line below
//.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj} [{SourceContext}]{NewLine}{Exception}" )
.CreateLogger();
#endif
ILoggerFactory _factory = LoggerFactory.Create(builder =>
{
builder
.SetMinimumLevel(LogLevel.Debug)
.AddDebug()
#if USE_SERILOG
.AddSerilog(seriLogger)
#else
.AddSimpleConsole( c =>
{
c.ColorBehavior = LoggerColorBehavior.Enabled ;
c.SingleLine=true;
c.TimestampFormat ="[HH:mm:ss] ";
})
#endif
;
});
LogManager.SetFactory(_factory);
_logger=_factory.CreateLogger<Program>();
bool showHelp = false;
ZigBeeDongle zigBeeDongle = ZigBeeDongle.TiCc2531;
string port = "";
int baudrate = 115200;
string flow = "";
FlowControl flowControl = FlowControl.FLOWCONTROL_OUT_NONE;
bool resetNetwork = false;
string store = "json";
string database = "devices";
string connection = "";
string collection = "";
OptionSet options = new OptionSet
{
{ "h|help", "show this message and exit", h => showHelp = h != null },
{ "zbd|zigbeeDongle=", "the zigbee dongle to use. 0 = TiCc2531 | 1 = DigiXBee | 2 = Conbee | 3 = Ember ", (ZigBeeDongle zbd) => zigBeeDongle = zbd },
{ "p|port=", "the COM port to use", p => port = p},
{ "b|baud=", $"the port baud rate to use. default is {baudrate}", b => int.TryParse(b, out baudrate)},
{ "f|flow=", $"the flow control (none | hardware | software)", f => flow = f },
{ "r|reset", $"Reset the Zigbee network", r => resetNetwork = r != null },
{ "s|store=", $"The store for network state", s => store = s },
{ "c|connection=", $"The mongoDb connection string", c => connection = c },
{ "d|database=", $"The mongoDb database or json directory", d => database = d },
{ "mc|mongoCollection=", $"The mongoDb collection", mc => collection = mc },
};
try
{
IList<string> extraArgs = options.Parse(args);
foreach (string extraArg in extraArgs)
{
Console.WriteLine($"Error: Unknown option: {extraArg}");
showHelp = true;
}
if (showHelp)
{
ShowHelp(options);
return;
}
if (string.IsNullOrEmpty(port))
{
Console.Write("Enter COM Port: ");
port = Console.ReadLine();
}
if (string.IsNullOrEmpty(flow))
{
// Default the flow control based on the dongle
switch (zigBeeDongle)
{
case ZigBeeDongle.Ember:
flowControl = FlowControl.FLOWCONTROL_OUT_XONOFF;
break;
default:
flowControl = FlowControl.FLOWCONTROL_OUT_NONE;
break;
}
}
else
{
switch (flow)
{
case "software":
flowControl = FlowControl.FLOWCONTROL_OUT_XONOFF;
break;
case "hardware":
flowControl = FlowControl.FLOWCONTROL_OUT_RTSCTS;
break;
case "none":
flowControl = FlowControl.FLOWCONTROL_OUT_NONE;
break;
default:
Console.WriteLine($"Unknown flow control option used: {flow}");
break;
}
}
ZigBeeSerialPort zigbeePort = new ZigBeeSerialPort(port, baudrate, flowControl);
IZigBeeTransportTransmit dongle;
switch (zigBeeDongle)
{
case ZigBeeDongle.TiCc2531:
{
dongle = new ZigBeeDongleTiCc2531(zigbeePort);
}
break;
case ZigBeeDongle.DigiXbee:
{
dongle = new ZigBeeDongleXBee(zigbeePort);
}
break;
case ZigBeeDongle.ConBee:
{
dongle = new ZigbeeDongleConBee(zigbeePort);
}
break;
case ZigBeeDongle.Ember:
{
dongle = new ZigBeeDongleEzsp(zigbeePort);
((ZigBeeDongleEzsp)dongle).SetPollRate(0);
}
break;
default:
{
dongle = new ZigBeeDongleTiCc2531(zigbeePort);
}
break;
}
ZigBeeNetworkManager networkManager = new ZigBeeNetworkManager(dongle);
if (store == "json")
{
JsonNetworkDataStore dataStore = new JsonNetworkDataStore(database);
networkManager.SetNetworkDataStore(dataStore);
}
else if (store == "mongo")
{
MongoDbDatabaseSettings settings = new MongoDbDatabaseSettings()
{
ConnectionString = connection,
DatabaseName = database,
NodesCollectionName = collection
};
MongoDbDataStore mongoStore = new MongoDbDataStore(settings);
networkManager.SetNetworkDataStore(mongoStore);
}
ZigBeeDiscoveryExtension discoveryExtension = new ZigBeeDiscoveryExtension();
discoveryExtension.SetUpdatePeriod(60);
networkManager.AddExtension(discoveryExtension);
// Initialise the network
networkManager.Initialize();
/* Network (de)serialization */
//networkManager.AddCommandListener(new ZigBeeNetworkDiscoverer(networkManager));
//networkManager.AddCommandListener(new ZigBeeNodeServiceDiscoverer(networkManager));
networkManager.AddCommandListener(new ZigBeeTransaction(networkManager));
networkManager.AddCommandListener(new ConsoleCommandListener());
networkManager.AddNetworkNodeListener(new ConsoleNetworkNodeListener());
networkManager.AddSupportedClientCluster(ZclOnOffCluster.CLUSTER_ID);
networkManager.AddSupportedClientCluster(ZclColorControlCluster.CLUSTER_ID);
networkManager.AddExtension(new ZigBeeBasicServerExtension());
networkManager.AddExtension(new ZigBeeIasCieExtension());
if (zigBeeDongle == ZigBeeDongle.TiCc2531)
{
((ZigBeeDongleTiCc2531)dongle).SetLedMode(1, false); // green led
((ZigBeeDongleTiCc2531)dongle).SetLedMode(2, false); // red led
}
Console.WriteLine($"PAN ID = {networkManager.ZigBeePanId}");
Console.WriteLine($"Extended PAN ID = {networkManager.ZigBeeExtendedPanId}");
Console.WriteLine($"Channel = {networkManager.ZigbeeChannel}");
if (zigBeeDongle != ZigBeeDongle.ConBee)
{
Console.WriteLine($"Network Key = {networkManager.ZigBeeNetworkKey}");
Console.WriteLine($"Link Key = {networkManager.ZigBeeLinkKey}");
}
if (resetNetwork)
{
//TODO: make the network parameters configurable
ushort panId = 1;
ExtendedPanId extendedPanId = new ExtendedPanId();
ZigBeeChannel channel = ZigBeeChannel.CHANNEL_11;
ZigBeeKey networkKey = ZigBeeKey.CreateRandom();
ZigBeeKey linkKey = new ZigBeeKey(new byte[] { 0x5A, 0x69, 0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61, 0x6E, 0x63, 0x65, 0x30, 0x39 });
Console.WriteLine($"*** Resetting network");
Console.WriteLine($" * PAN ID = {panId}");
Console.WriteLine($" * Extended PAN ID = {extendedPanId}");
Console.WriteLine($" * Channel = {channel}");
Console.WriteLine($" * Network Key = {networkKey}");
Console.WriteLine($" * Link Key = {linkKey}");
networkManager.SetZigBeeChannel(channel);
networkManager.SetZigBeePanId(panId);
networkManager.SetZigBeeExtendedPanId(extendedPanId);
networkManager.SetZigBeeNetworkKey(networkKey);
networkManager.SetZigBeeLinkKey(linkKey);
}
ZigBeeStatus startupSucceded = networkManager.Startup(resetNetwork);
if (startupSucceded == ZigBeeStatus.SUCCESS)
{
_logger.LogInformation("ZigBee console starting up ... [OK]");
}
else
{
_logger.LogInformation("ZigBee console starting up ... [FAIL]");
_logger.LogInformation("Press any key to exit...");
Console.ReadKey();
return;
}
ZigBeeNode coord = networkManager.GetNode(0);
Console.WriteLine("Joining enabled...");
string cmd = string.Empty;
while (cmd != "exit")
{
if (cmd == "join")
{
coord.PermitJoin(true);
}
else if (cmd == "unjoin")
{
coord.PermitJoin(false);
}
else if (cmd == "endpoints")
{
var tmp = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("Destination Address: ");
Console.ForegroundColor = tmp;
string nwkAddr = Console.ReadLine();
if (ushort.TryParse(nwkAddr, out ushort addr))
{
var node = networkManager.Nodes.FirstOrDefault(n => n.NetworkAddress == addr);
if (node != null)
{
Console.WriteLine(new string('-', 20));
foreach (var endpoint in node.GetEndpoints())
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Input Cluster [{0:X}]:",endpoint.EndpointId);
Console.ForegroundColor = tmp;
foreach (var inputClusterId in endpoint.GetInputClusterIds())
{
var cluster = endpoint.GetInputCluster(inputClusterId);
var clusterName = cluster.GetClusterName();
Console.WriteLine($"{clusterName}");
}
Console.WriteLine();
}
Console.WriteLine();
foreach (var endpoint in node.GetEndpoints())
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine("Output Cluster [{0:X}]:",endpoint.EndpointId);
Console.ForegroundColor = tmp;
foreach (var outputClusterIds in endpoint.GetOutputClusterIds())
{
var cluster = endpoint.GetOutputCluster(outputClusterIds);
var clusterName = cluster.GetClusterName();
Console.WriteLine($"{clusterName}");
}
Console.WriteLine();
}
Console.WriteLine(new string('-', 20));
}
}
}
else if (cmd == "add")
{
var tmp = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("Destination Address: ");
Console.ForegroundColor = tmp;
string nwkAddr = Console.ReadLine();
if (ushort.TryParse(nwkAddr, out ushort addr))
{
Console.Write("IeeeAddress: ");
Console.ForegroundColor = tmp;
string ieeeAddr = Console.ReadLine();
networkManager.UpdateNode(new ZigBeeNode() { NetworkAddress = addr, IeeeAddress = new IeeeAddress(ieeeAddr) });
}
}
else if (!string.IsNullOrEmpty(cmd))
{
var tmp = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("Destination Address: ");
Console.ForegroundColor = tmp;
string nwkAddr = Console.ReadLine();
if (ushort.TryParse(nwkAddr, out ushort addr))
{
var node = networkManager.GetNode(addr);
if (node != null)
{
var endpoint = node.GetEndpoints().FirstOrDefault();
if (endpoint is null)
{
Console.WriteLine("No endpoint found");
continue;
}
ZigBeeEndpointAddress endpointAddress = endpoint.GetEndpointAddress();
try
{
if (cmd == "leave")
{
await networkManager.Leave(node.NetworkAddress, node.IeeeAddress);
}
else if (cmd == "toggle")
{
await networkManager.Send(endpointAddress, new ToggleCommand());
}
else if (cmd == "level")
{
Console.WriteLine("Level between 0 and 255: ");
string level = Console.ReadLine();
Console.WriteLine("time between 0 and 65535: ");
string time = Console.ReadLine();
var command = new MoveToLevelWithOnOffCommand()
{
Level = byte.Parse(level),
TransitionTime = ushort.Parse(time)
};
await networkManager.Send(endpointAddress, command);
}
else if (cmd == "move")
{
await networkManager.Send(endpointAddress, new MoveCommand() { MoveMode = 1, Rate = 100 });
}
else if (cmd == "on")
{
await networkManager.Send(endpointAddress, new OnCommand());
}
else if (cmd == "off")
{
await networkManager.Send(endpointAddress, new OffCommand());
}
else if (cmd == "effect")
{
await networkManager.Send(endpointAddress, new OffCommand());
bool state = false;
for (int i = 0; i < 10; i++)
{
if (state)
{
await networkManager.Send(endpointAddress, new OffCommand());
}
else
{
await networkManager.Send(endpointAddress, new OnCommand());
}
state = !state;
await Task.Delay(1000);
}
}
else if (cmd == "stress")
{
await networkManager.Send(endpointAddress, new OffCommand());
bool state = false;
for (int i = 0; i < 100; i++)
{
if (state)
{
await networkManager.Send(endpointAddress, new OffCommand());
}
else
{
await networkManager.Send(endpointAddress, new OnCommand());
}
state = !state;
await Task.Delay(1);
}
}
else if (cmd == "desc")
{
NodeDescriptorRequest nodeDescriptorRequest = new NodeDescriptorRequest()
{
DestinationAddress = endpointAddress,
NwkAddrOfInterest = addr
};
networkManager.SendTransaction(nodeDescriptorRequest);
}
else if (cmd == "color")
{
Console.WriteLine("Red between 0 and 255: ");
string r = Console.ReadLine();
Console.WriteLine("Green between 0 and 255: ");
string g = Console.ReadLine();
Console.WriteLine("Blue between 0 and 255: ");
string b = Console.ReadLine();
if (int.TryParse(r, out int _r) && int.TryParse(g, out int _g) && int.TryParse(b, out int _b))
{
CieColor xyY = ColorConverter.RgbToCie(_r, _g, _b);
MoveToColorCommand command = new MoveToColorCommand()
{
ColorX = xyY.X,
ColorY = xyY.Y,
TransitionTime = 10
};
await networkManager.Send(endpointAddress, command);
}
}
else if (cmd == "hue")
{
Console.WriteLine("Red between 0 and 255: ");
string hue = Console.ReadLine();
if (byte.TryParse(hue, out byte _hue))
{
MoveToHueCommand command = new MoveToHueCommand()
{
Hue = _hue,
Direction = 0,
TransitionTime = 10
};
await networkManager.Send(endpointAddress, command);
}
}
else if (cmd == "read")
{
var cluster = endpoint.GetInputCluster(ZclBasicCluster.CLUSTER_ID);
if (cluster != null)
{
string manufacturerName = (string)(await cluster.ReadAttributeValue(ZclBasicCluster.ATTR_MANUFACTURERNAME));
string model = (string)(await cluster.ReadAttributeValue(ZclBasicCluster.ATTR_MODELIDENTIFIER));
Console.WriteLine($"Manufacturer Name = {manufacturerName}");
Console.WriteLine($"Model identifier = {model}");
}
}
else if (cmd == "discover attributes")
{
foreach (int clusterId in endpoint.GetInputClusterIds())
{
ZclCluster cluster = endpoint.GetInputCluster(clusterId);
if (!await cluster.DiscoverAttributes(true))
Console.WriteLine("Error while discovering attributes for cluster {0}", cluster.GetClusterName());
}
}
else if (cmd == "update binding table")
{
ZigBeeStatus statusCode = await node.UpdateBindingTable();
if (statusCode != ZigBeeStatus.SUCCESS)
{
Console.WriteLine("Error while reading binding table: " + statusCode);
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error while executing cmd {Command}", cmd);
}
}
else
{
Console.WriteLine($"Node {addr} not found");
}
}
}
await Task.Delay(100);
Console.WriteLine(Environment.NewLine + networkManager.Nodes.Count + " node(s)" + Environment.NewLine);
for (int i = 0; i < networkManager.Nodes.Count; i++)
{
var node = networkManager.Nodes[i];
Console.WriteLine($"{i}. {node.LogicalType}: {node.NetworkAddress}");
}
Console.WriteLine();
var currentForeGroundColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.Write("cmd> ");
Console.ForegroundColor = currentForeGroundColor;
cmd = Console.ReadLine();
}
networkManager.Shutdown();
}
catch (OptionException e)
{
Console.WriteLine(e.Message);
ShowHelp(options);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
static void ShowHelp(OptionSet options)
{
Console.WriteLine("Options:");
options.WriteOptionDescriptions(Console.Out);
}
}
public class ConsoleCommandListener : IZigBeeCommandListener
{
public void CommandReceived(ZigBeeCommand command)
{
//Console.WriteLine(command);
}
}
public class ConsoleNetworkNodeListener : IZigBeeNetworkNodeListener
{
public void NodeAdded(ZigBeeNode node)
{
Console.WriteLine("Node " + node.IeeeAddress + " added " + node);
if (node.NetworkAddress != 0)
{
}
}
public void NodeRemoved(ZigBeeNode node)
{
Console.WriteLine("Node removed " + node);
}
public void NodeUpdated(ZigBeeNode node)
{
Console.WriteLine("Node updated " + node);
}
}
}