File: Command.pm

package info (click to toggle)
libhipi-perl 0.93-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 20,048 kB
  • sloc: perl: 471,917; ansic: 22; makefile: 10
file content (1777 lines) | stat: -rw-r--r-- 58,048 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
#########################################################################################
# Package        HiPi::Energenie::Command
# Description  : Energenie Command Wrapper
# Copyright    : Copyright (c) 2017-2020 Mark Dootson
# License      : This is free software; you can redistribute it and/or modify it under
#                the same terms as the Perl 5 programming language system itself.
#########################################################################################

package HiPi::Energenie::Command;

#########################################################################################

use strict;
use warnings;
use feature 'say';
use parent qw( HiPi::Class );
use HiPi qw( :openthings :energenie :rpi );
use HiPi::Energenie;
use HiPi::Utils::Config;
use Getopt::Long qw( GetOptionsFromArray );
use JSON;
use Try::Tiny;
use HiPi::RF::OpenThings::Message;

our $VERSION ='0.82';

__PACKAGE__->create_accessors( qw( config result mode display options pretty user
                                   console_display_message ) );

use constant {
    ERROR_SUCCESS     => 'ERROR_SUCCESS',
    ERROR_UNKNOWN     => 'ERROR_UNKNOWN',
    ERROR_MISSING_COMMAND => 'ERROR_MISSING_COMMAND',
    ERROR_BAD_COMMAND => 'ERROR_BAD_COMMAND',
    ERROR_BAD_OPTIONS => 'ERROR_BAD_OPTIONS',
    
    ERROR_SYSTEM => 'ERROR_SYSTEM',
    
    ERROR_CONFIG_INVALID_BOARD  => 'ERROR_CONFIG_INVALID_BOARD',
    ERROR_CONFIG_INVALID_DEVICE => 'ERROR_CONFIG_INVALID_DEVICE',
    ERROR_CONFIG_INVALID_GPIO  => 'ERROR_CONFIG_INVALID_GPIO',
    
    ERROR_GROUP_INVALID_OPTIONS => 'ERROR_GROUP_INVALID_OPTIONS',
    ERROR_GROUP_EXISTING_GROUP => 'ERROR_GROUP_EXISTING_GROUP',
    ERROR_GROUP_EXISTING_NAME => 'ERROR_GROUP_EXISTING_NAME',
    ERROR_GROUP_NAME_NOT_FOUND => 'ERROR_GROUP_NAME_NOT_FOUND',
    ERROR_GROUP_ID_NOT_FOUND => 'ERROR_GROUP_ID_NOT_FOUND',
    
    ERROR_PAIR_INVALID_OPTIONS => 'ERROR_PAIR_INVALID_OPTIONS',
    ERROR_PAIR_GROUP_NOT_FOUND => 'ERROR_PAIR_GROUP_NOT_FOUND',
    ERROR_PAIR_INVALID_SWITCH => 'ERROR_PAIR_INVALID_SWITCH',
    ERROR_PAIR_NAME_NOT_FOUND => 'ERROR_PAIR_NAME_NOT_FOUND',
    ERROR_PAIR_EXISTING_SWITCH => 'ERROR_PAIR_EXISTING_SWITCH',
    
    ERROR_SWITCH_INVALID_OPTIONS => 'ERROR_SWITCH_INVALID_OPTIONS',
    ERROR_SWITCH_GROUP_NOT_FOUND => 'ERROR_SWITCH_GROUP_NOT_FOUND',
    ERROR_SWITCH_INVALID_SWITCH => 'ERROR_SWITCH_INVALID_SWITCH',
    ERROR_SWITCH_NAME_NOT_FOUND => 'ERROR_SWITCH_NAME_NOT_FOUND',
    
    ERROR_ALIAS_INVALID_OPTIONS => 'ERROR_ALIAS_INVALID_OPTIONS',
    ERROR_ALIAS_GROUP_NOT_FOUND => 'ERROR_ALIAS_GROUP_NOT_FOUND',
    ERROR_ALIAS_INVALID_SWITCH => 'ERROR_ALIAS_INVALID_SWITCH',
    
    ERROR_USUPPORTED_RX_COMMAND  => 'ERROR_USUPPORTED_RX_COMMAND',
    
    ERROR_JOIN_INVALID_OPTIONS  => 'ERROR_JOIN_INVALID_OPTIONS',
    ERROR_JOIN_EXISTING_ADAPTER => 'ERROR_JOIN_EXISTING_ADAPTER',
    ERROR_JOIN_EXISTING_MONITOR => 'ERROR_JOIN_EXISTING_MONITOR',
    ERROR_JOIN_DEVICE_NOT_FOUND => 'ERROR_JOIN_DEVICE_NOT_FOUND',
    ERROR_JOIN_FAILED           => 'ERROR_JOIN_FAILED',
    
    ERROR_ADAPTER_INVALID_OPTIONS => 'ERROR_ADAPTER_INVALID_OPTIONS',
    ERROR_ADAPTER_NAME_NOT_FOUND  => 'ERROR_ADAPTER_NAME_NOT_FOUND',
    ERROR_ADAPTER_FAILED          => 'ERROR_ADAPTER_FAILED',
    
    ERROR_MONITOR_INVALID_OPTIONS => 'ERROR_MONITOR_INVALID_OPTIONS',
    ERROR_MONITOR_NAME_NOT_FOUND  => 'ERROR_MONITOR_NAME_NOT_FOUND',
    ERROR_MONITOR_FAILED          => 'ERROR_MONITOR_FAILED',
    
};

my $commandopts = {
    help     => {
        template => undef,
        defaults => {},
    },
    version  => {
        template => undef,
        defaults => {},
    },
    config  => {
        template => [ 'help|h!', 'list|l!', 'device|d:s', 'board|b:s', 'reset|r:s' ],
        defaults => { help => 0, list => 0, device => undef, board => undef, reset => undef },
    },
    group   => {
        template => [ 'help|h!', 'create|c:s', 'delete|d:s', 'rename|r:s', 'group|g:o', 'newname|n:s', 'list|l!',],
        defaults => { },
    },
    pair    => {
        template => [ 'help|h!', 'list|l', 'groupname|g:s', 'switch|s:i', 'name|n:s', ],
        defaults => { groupname => undef, switch => 0, },
    },
    switch  => {
        template => [ 'help|h!', 'list|l!', 'groupname|g:s', 'switch|s:i', 'name|n:s', 'on|1!', 'off|0!', 'all!' ],
        defaults => { help => 0, list => 0, groupname => undef, switch => undef, on => 0, off => 0, all => 0, } ,
    },
    alias  => {
        template => [ 'help|h!', 'list|l!', 'groupname|g:s', 'switch|s:i', 'name|n:s', ],
        defaults => { help => 0, list => 0, } ,
    },
    join    => {
        template => [ 'help|h!', 'list|l!', 'name|n:s', 'delete|d:s', 'rename|r:s', 'timeout|t:i' ],
        defaults => { help => 0, list => 0, name => '', delete  => '', rename => '', timeout => 60 },
    },
    adapter => {
        template => [ 'help|h!', 'list|l!', 'name|n:s', 'query|q!', 'on|1!', 'off|0!', 'timeout|t:i' ],
        defaults => { name => undef, query => 0, on => 0, off => 0, list => 0, help => 0, timeout => 60 },
    },
    monitor => {
        template => [ 'help|h!', 'list|l!', 'name|n:s', 'timeout|t:i' ],
        defaults => { name => undef, list => 0, help => 0,  timeout => 60 } ,
    },
};


sub new {
    my($class, %userparams ) = @_;
    
    my %params = (
        display => 'usage',
        mode    => 'console',
        pretty  => 0,
        user    => getpwuid($>),
        console_display_message => '',
        result  => {
            success   => 0,
            command   => 'unknown',
            option    => '',
            error     => 'unknown error',
            errorcode => ERROR_UNKNOWN,
            data      => {},
        },
    );
    
    foreach my $key (sort keys(%userparams)) {
        $params{$key} = $userparams{$key};
    }
    
    $params{config} = HiPi::Utils::Config->new(
        configclass => 'scripts/energenie',
        default     => {
            version    => $VERSION,
            board      => 'ENER314_RT',
            spi_device => '/dev/spidev0.1',
            reset_gpio => RPI_PIN_22,
            led_red_gpio => 0,
            led_green_gpio => 0,
            groups     => {},
            adapters   => {},
            monitors   => {},
            switches   => {},
        },
    );
    
    my $self = $class->SUPER::new( %params );
    return $self;
}

sub conf { $_[0]->config->config(); }

sub valid_command {
    my( $self, $command) = @_;
    return 0 if( length($command) > 40 || $command !~ /^[a-z]+$/ );
    return ( exists($commandopts->{$command}) ) ? 1 : 0;
}
    
sub handle_command {
    my $self = shift;
    my @commandargs = @ARGV;
    
    $self->handle_command_arguments( @commandargs );
}

sub handle_command_arguments {
    my ($self, @inputargs) = @_;
    
    my @commandargs = ();
    
    my $result = try {
    
        for my $arg ( @inputargs ) {
            if( lc($arg) eq '--json' ) {
                $self->mode('json');
            } elsif( lc($arg) eq '--pretty' ) {
                $self->mode('json');
                $self->pretty(1);
            } else {
                push @commandargs, $arg;
            }
        }
        
        $commandargs[0] = 'missing' unless @commandargs;
        
        my $command = shift @commandargs;
    
        if ( $self->valid_command($command) ) {
            $self->result->{command} = $command;
            my $opt = $commandopts->{$command}->{defaults};
            my $opttemplate = $commandopts->{$command}->{template};
            if( $opttemplate ) {
                GetOptionsFromArray(\@commandargs, $opt, @$opttemplate )
            }
            $self->options( $opt );
            my $commandsub = qq(command_$command);
            $self->$commandsub();
        } else {
            $self->result->{command} = $command;
            my $errorcode = ( $command eq 'missing' ) ? ERROR_MISSING_COMMAND : ERROR_BAD_COMMAND;
            $self->set_result_error( $errorcode, qq(bad or missing command provided : $command ))
        }
    
        $self->return_result();
    } catch {
        my $error = $_;
        $error =~ s/["\n]/ /g;
        return qq({"success":0,"errorcode":"ERROR_SYSTEM","error":"$error"});
    };
    
    return $result;
}

sub return_result {
    my $self = shift;
    
    if($self->mode eq 'json') {
        if( exists( $self->result->{data}) && ref($self->result->{data})->isa('HiPi::RF::OpenThings::Message') ) {
            $self->result->{data} = $self->result->{data}->value_hash;
        }
        my $j = JSON->new;
        my $output = ( $self->pretty ) ? $j->pretty->canonical->encode( $self->result ) : $j->encode( $self->result );
        return $output;
    }
    
    if( $self->display eq 'usage' ) {
        
        my $output = '';
        if( $self->result->{errorcode} ne 'ERROR_SUCCESS' ) {
            $output .= sprintf(qq(\nERROR : %s : %s\n), $self->result->{errorcode}, $self->result->{error});
        }
        $output .= $self->get_command_usage($self->result->{command});
        
        return $output;
    }
    
    # display the command result
    if( $self->result->{errorcode} ne 'ERROR_SUCCESS' || !$self->result->{success} ) {
        return sprintf(qq(Command : %s : ERROR : %s : %s), $self->result->{command}, $self->result->{errorcode}, $self->result->{error});
    
    # CONFIG
    
    } elsif( $self->result->{command} eq 'config') {
        
        my $output = qq(\nCONFIGURATION\n);
        $output .= qq(-----------------------------------------\n);
        
        if( my $data = $self->result->{data} ) {
            
            my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime( $data->{epoch} );
            my $timestamp = sprintf('%u-%02u-%02u %02u:%02u:%02u',
                $year + 1900, $mon + 1, $mday, $hour, $min, $sec      
            );
                
            $output .= qq(  Config Version   :  $data->{version}\n) if $data->{version};
            $output .= qq(  Energenie Board  :  $data->{board}\n) if $data->{board};
            $output .= qq(  Receiver         :  $data->{can_rx}\n) if $data->{can_rx};
            $output .= qq(  Uses SPI         :  $data->{uses_spi}\n) if $data->{uses_spi};
            $output .= qq(  SPI Device       :  $data->{spi_device}\n) if $data->{spi_device} && $data->{can_rx} eq 'YES';
            $output .= qq(  Reset GPIO       :  $data->{reset_gpio}\n) if $data->{spi_device} && $data->{can_rx} eq 'YES';
            $output .= qq(  Config Saved     :  $timestamp\n);
        }
        return $output;
        
    # VERSION
    
    } elsif( $self->result->{command} eq 'version') {
        return $self->result->{data}->{versiontext};
    
    # GROUP
    
    } elsif( $self->result->{command} eq 'group') {
        my $output = qq(\nGROUPS\n);
        $output .= qq(-----------------------------------------\n);
        # $output .= qq(NAME                           ID\n);
        for my $gname ( sort keys %{ $self->result->{data}->{groups} } ) {
            my $gid = $self->result->{data}->{groups}->{$gname};
            $output .= sprintf(qq(  %-30s %s\n), $gname, $gid);
        }
        return $output;
        
    # SWITCH LIST
    
    } elsif( $self->result->{command} =~ /^pair|alias$/
            || ( $self->result->{command} eq 'switch' && $self->result->{option} eq 'list') ) {
       
        my $output = qq(\nSWITCHES & SOCKETS\n);
        $output .= qq(------------------------------------------\n);
        $output .= qq(  NAME               GROUP          SWITCH\n);
        for my $switch( sort keys %{ $self->result->{data}->{switches} } ) {
            my $group = $self->result->{data}->{switches}->{$switch}->{group};
            my $sno = $self->result->{data}->{switches}->{$switch}->{switch};
            $output .= sprintf(qq(  %-18s %-18s  %s\n), $switch, $group, $sno);
        }
        return $output;    
    
    # SWITCH BROADCAST
    
    
    } elsif( $self->result->{command} eq 'switch' && $self->result->{option} ne 'list' ) {
    
       
        my $output = sprintf(qq(\nSWITCH BROADCAST STATUS - %s\n), $self->result->{data}->{status});
        $output .= qq(-------------------------------\n);
        
        my @snums = ( $self->result->{data}->{switch} ) ? ( $self->result->{data}->{switch} ) : (1,2,3,4);
        my $group = $self->result->{data}->{groupname};
        $output .= qq(  GROUP                  SWITCH\n);
        for my $switch( @snums ) {
            $output .= sprintf(qq(  %-25s %s\n), $group, $switch);
        }
        
        return $output;    
    
    } elsif( $self->result->{command} eq 'join' || ( $self->result->{command} =~ /^adapter|monitor$/  && $self->result->{option} eq 'list' ) ) {
    
        my $output = qq(\nMONITORS AND ADAPTERS\n);
        $output .= qq(---------------------------------------------------------------------\n);
        $output .= (qq(  NAME                 PRODUCT                      SENSORID   SWITCH\n));
        
        my $listname = ( $self->result->{command} eq 'adapter' ) ? 'adapters' : 'monitors';
        
        for my $monitor ( sort keys %{ $self->result->{data}->{$listname} } ) {
            my $data = $self->result->{data}->{$listname}->{$monitor};
            my $switch = HiPi::RF::OpenThings->product_can_switch( $data->{manufacturer_id}, $data->{product_id} ) ? 'YES' : ' NO';
            # my $switch = ( exists( $self->result->{data}->{adapters}->{$monitor}) ) ? 'YES' : ' NO';
            $output .= sprintf(qq(  %-20s %-28s 0x%06X      %s\n),
                $monitor, $data->{product_name}, $data->{sensor_id}, $switch
            );
        }
        
    
        return $output;
        
    } elsif( $self->result->{command} =~ /^adapter|monitor$/  && $self->result->{option} ne 'list' ) {
                
        my $data = $self->result->{data}->value_hash;
       
        my $output = sprintf(qq(\n%s STATUS REPORT FOR "%s"\n), uc($self->result->{command}), $data->{'configured_name'});
        $output .= qq(---------------------------------------------\n);
        $output .= qq(  Sensor Type           $data->{product_name}\n);
        $output .= qq(  Sensor Key            $data->{sensor_key}\n);
        $output .= qq(  Timestamp             $data->{timestamp}\n);
        $output .= qq(  -------------------------------------------\n);
        for my $record ( @{ $data->{records} } ) {
            my $value = $record->{value};
            if( $record->{id} == OPENTHINGS_PARAM_SWITCH_STATE ) {
                $value = ( $value ) ? 'ON' : 'OFF';
            }
            my $unitpart = ($record->{units}) ? qq( $record->{units}) : '';
            $output .= sprintf(qq(  %-20s  %s%s\n), $record->{name}, $value, $unitpart);
            
        }
        
        return $output;
    # other ?
    } else {
        if( exists( $self->result->{data}) && ref($self->result->{data})->isa('HiPi::RF::OpenThings::Message') ) {
            $self->result->{data} = $self->result->{data}->value_hash;
        }
        my $j = JSON->new;
        my $output = $j->pretty->canonical->encode( $self->result );
        return $output;
    }
}

sub set_result_success {
    my( $self, $data, $option ) = @_;
    if( $data ) {
        $self->display('data');
        $self->result->{data} = $data;
    } 
    $self->result->{success} = 1;
    $self->result->{error}   = '';
    $self->result->{errorcode} = ERROR_SUCCESS;
    $self->result->{option} = $option if $option;
    return;
}

sub set_result_error {
    my ($self, $errorcode, $error, $option) = @_;
    $error //= $errorcode;
    $self->display('error'); 
    $self->result->{success} = 0;
    $self->result->{error}   = $error;
    $self->result->{errorcode} = $errorcode;
    $self->result->{option} = $option if $option;
    return;
}

sub set_result_options_error {
    my ($self, $errorcode, $error, $option) = @_;
    $error //= $errorcode;
    $self->display('options'); 
    $self->result->{success} = 0;
    $self->result->{error}   = $error;
    $self->result->{errorcode} = $errorcode;
    $self->result->{option} = $option if $option;
    return;
}

sub command_help {
    my $self = shift;
    $self->set_result_success();
    return;
}

sub command_version {
    my $self = shift;
    $self->set_result_success(
        {
            version     => $VERSION,
            versiontext => qq(HiPi Energenie Version $VERSION),
        }
    );
    return;
}

sub command_config {
    my( $self ) = @_;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    } elsif( $self->options->{list} ) {
        $self->list_configuration('list');
        return;
    } else {
        my( $newdevice, $newboard, $newreset );
    
        if ( $self->options->{device} ) {
            if( my ($devicename) = ( $self->options->{device} =~ /^(\/dev\/spidev\d\.\d)$/i ) ) {
                $newdevice = $devicename;
            } else {
                $self->set_result_error(
                    ERROR_CONFIG_INVALID_DEVICE,
                    sprintf(q(Invalid device %s specified), $self->options->{device}),
                    'update',
                );
                return;
            }
        }
    
        if( $self->options->{board} ) {
            if( my ($board) = ( $self->options->{board} =~ /^(ENER314|ENER314_RT|RF69HW)$/i ) ) {
                $newboard = uc($board);
            } else {
                $self->set_result_error(
                    ERROR_CONFIG_INVALID_BOARD,
                    sprintf(q(Invalid board %s specified), $self->options->{board}),
                    'update',
                );
                return;
            }
        }
        
        if( defined($self->options->{reset}) ) {
            # reset should be a number greater than 0
            if( $self->options->{reset} && $self->options->{reset} =~ /^\d+$/ ) {
                $newreset = $self->options->{reset};
            } else {
                $self->set_result_error(
                    ERROR_CONFIG_INVALID_GPIO,
                    sprintf(q(Invalid Reset GPIO %s specified), $self->options->{reset}),
                    'update',
                );
                return;
            }
        }
                
        my $coption = 'update';
        
        if( $newdevice ) {
            $self->conf->{spi_device} = $newdevice;
            $coption = 'refresh';
        }
        
        if( $newboard ) {
            $self->conf->{board} = $newboard;
            $coption = 'refresh';
        }
        
        if( $newreset ) {
            $self->conf->{reset_gpio} = $newreset;
            $coption = 'refresh';
        }
        
        # so put config info in data
        $self->list_configuration($coption);
    }
    return;
}

sub command_group {
    my $self = shift;
    
    my $create = $self->options->{create};
    my $delete = $self->options->{delete};
    my $rename = $self->options->{rename};
        
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    } elsif( $self->options->{list} ) {
        $self->list_groups('list');
        return;
    } elsif ( $create ) {
        
        if( $delete || $rename ) {
            $self->set_result_options_error(
                ERROR_GROUP_INVALID_OPTIONS,
                'You must specify only one of --create, --delete, --rename, --list, or --help',
                'missing',
            );
            return;
        }
        
        for my $existing( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$existing}) eq lc($create) ) {
                $self->set_result_error(
                    ERROR_GROUP_EXISTING_NAME,
                    sprintf('The name %s is already in use for group 0x%05x', $create, $existing),
                    'create'
                );
                return;
            }
        }
        
        my $group = $self->options->{group};
               
        if( $group ) {
            if(exists($self->conf->{groups}->{$group})) {
                $self->set_result_error(
                    ERROR_GROUP_EXISTING_GROUP,
                    sprintf('The group id 0x%05x already exists', $group),
                    'create'
                );
                return;
            }
        }
        
        my $newgroup = $group;
        
        while(! $newgroup ) {
            $group = $self->generate_switch_group();
            unless(exists($self->conf->{groups}->{$group})) {
                $newgroup = $group;
            }
        }
        
        $self->conf->{groups}->{$newgroup} = $create;
        $self->list_groups('create');
        return;
    } elsif ( $delete ) {

        if( $create || $rename ) {
            $self->set_result_options_error(
                ERROR_GROUP_INVALID_OPTIONS,
                'You must specify only one of --create, --delete, --rename, --list, or --help',
                'missing',
            );
            return;
        }
                   
        for my $group( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$group}) eq lc($delete) ) {
                # delete any grouped switches first
                for my $switchname ( keys %{ $self->conf->{switches} } ) {
                    if( $self->conf->{switches}->{$switchname}->{group} == $group ) {
                        delete($self->conf->{switches}->{$switchname});
                    }
                }
                delete($self->conf->{groups}->{$group});
                $self->list_groups('delete');
                return;
            }
        }
        
        $self->set_result_error(
            ERROR_GROUP_NAME_NOT_FOUND,
            qq(A group with name $delete was not found),
            'delete'
        );
        return;
        
    } elsif( $rename ) {
        
        if( $delete || $create ) {
            $self->set_result_options_error(
                ERROR_GROUP_INVALID_OPTIONS,
                'You must specify only one of --create, --delete, --rename, --list, or --help',
                'missing',
            );
            return;
        }            
        
        my $newname = $self->options->{newname};
        unless( $newname ) {
            $self->set_result_options_error(
                ERROR_GROUP_INVALID_OPTIONS,
                'You must provide both options --rename and --newname to rename an existing group',
                'rename'
            );
            return;
        }
        
        for my $existing( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$existing}) eq lc($newname) ) {
                $self->set_result_error(
                    ERROR_GROUP_EXISTING_NAME,
                    sprintf('The name %s is already in use for group 0x%05x', $newname, $existing),
                    'rename'
                );
                return;
            }
        }
                
        for my $existing( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$existing}) eq lc($rename) ) {
                $self->conf->{groups}->{$existing} = $newname;
                $self->list_groups('rename');
                return;
            }
        }
        
        $self->set_result_error(
            ERROR_GROUP_NAME_NOT_FOUND,
            qq(A group with name $rename was not found),
            'delete'
        );
        
        return;
    }
    
    $self->set_result_options_error(
        ERROR_GROUP_INVALID_OPTIONS,
        'You must specify one of --create --delete --rename --list --help',
        'missing',
    );
        return;
}

sub command_pair {
    my $self = shift;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    }
    
    if( $self->options->{list} ) {
        $self->list_switches('list');
        return;
    }
    
    my $group     = 0;
    my $groupname = $self->options->{groupname};
    my $name      = $self->options->{name};
    
    if( $self->receiver ) {
        # we care about group name
        unless($groupname) {
            $self->set_result_options_error(
                ERROR_PAIR_INVALID_OPTIONS,
                'You must provide a --groupname to pair a socket or switch when using tx/rx board ENER314_RT or RF69HW',
                'pair'
            );
            return;
        }
        
        # get the group
        for my $checkgroup( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$checkgroup}) eq lc($groupname) ) {
                $group = $checkgroup;
                last;
            }
        }
        
        unless( $group ) {
             $self->set_result_error(
                ERROR_PAIR_GROUP_NOT_FOUND,
                qq(Could not find a configured group named $groupname),
                'pair'
            );
            return;
        }
    } else {
        $group = ENERGENIE_ENER314_DUMMY_GROUP;
        $groupname = 'energenie_single_group';
    }

    my $switch = $self->options->{switch};
    
    unless( $switch && $switch =~ /^1|2|3|4$/) {
         $self->set_result_error(
            ERROR_PAIR_INVALID_SWITCH,
            q(You must provide a valid switch number --switch 1|2|3|4),
            'pair'
        );
        return;
    }
        
    # pair the switch
    
    my $error =  try {
        my $handler = HiPi::Energenie->new(
            backend    => $self->conf->{board},
            devicename => $self->conf->{spi_device},
            reset_gpio => $self->conf->{reset_gpio},
        );
        
        $handler->pair_socket( $group, $switch, 5 );
        return '';
    } catch {
        my $err = $_;
        $err =~ s/\n/ /g;
        return $err;
    };
    
    if( $error ) {
        $self->set_result_error( ERROR_SYSTEM, $error, 'pair' );
        return;
    }
    
    $name ||= qq(${groupname}_switch_${switch});
    
    $self->conf->{switches}->{$name} = { group => $group, switch => $switch };
    
    $self->list_switches('pair');
}

sub command_switch {
    my $self = shift;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    }
    
    if( $self->options->{list} ) {
        $self->list_switches('list');
        return;
    }
    
    my $group = 0;
    my $groupname = $self->options->{groupname};
    my $switch = ( $self->options->{all}  ) ? 0 : $self->options->{switch};
    
    my $name = $self->options->{name};
    
    if($name) {
        if(exists($self->conf->{switches}->{$name})) {
            $group  = $self->conf->{switches}->{$name}->{group};
            $switch = $self->conf->{switches}->{$name}->{switch};
            $groupname = $self->conf->{groups}->{$group};
        } else {
            $self->set_result_error(
                ERROR_SWITCH_NAME_NOT_FOUND,
                qq(Could not find a configured switch named $name),
                'switch'
            );
            return;
        }
    }
    
    
    if( $self->receiver && !$group ) {
        # we care about group name
        unless($groupname) {
            $self->set_result_options_error(
                ERROR_SWITCH_INVALID_OPTIONS,
                'You must provide a --groupname to turn on/off a socket or switch',
                'switch'
            );
            return;
        }
        
        # get the group
        for my $checkgroup( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$checkgroup}) eq lc($groupname) ) {
                $group = $checkgroup;
                last;
            }
        }
        
        unless( $group ) {
            $self->set_result_error(
                ERROR_SWITCH_GROUP_NOT_FOUND,
                qq(Could not find a configured group named $groupname),
                'switch'
            );
            return;
        }
    } elsif( !$self->receiver ) {
        $group = ENERGENIE_ENER314_DUMMY_GROUP;
        $groupname = 'energenie_single_group';
    }
    
    unless( defined($switch) && $switch =~ /^0|1|2|3|4$/) {
        $self->set_result_error(
            ERROR_SWITCH_INVALID_SWITCH,
            q(You must provide a valid switch number --switch 0|1|2|3|4 ( 0 switches all switches in the group )),
            'switch'
        );
        return;
    }
     
    if(!$self->options->{on} && !$self->options->{off}) {
        $self->set_result_options_error(
            ERROR_SWITCH_INVALID_OPTIONS,
            'You must specify either --on or --off',
            'switch'
        );
        return;
    }
    
    if($self->options->{on} && $self->options->{off}) {
        $self->set_result_options_error(
            ERROR_SWITCH_INVALID_OPTIONS,
            'You must specify either --on or --off - not both',
            'switch'
        );
        return;
    }
    
    my $state = ( $self->options->{on} ) ? 1 : 0;
    
    # Set the switch on / off
    
    my $error =  try {
        my $handler = HiPi::Energenie->new(
            backend    => $self->conf->{board},
            devicename => $self->conf->{spi_device},
            reset_gpio => $self->conf->{reset_gpio},
        );
        
        $handler->switch_socket( $group, $switch, $state );
        return '';
    } catch {
        my $err = $_;
        $err =~ s/\n/ /g;
        return $err;
    };
    
    if( $error ) {
        $self->set_result_error( ERROR_SYSTEM, $error, 'switch' );
        return;
    } 
    
    my $groupid = ( $self->receiver ) ? $self->format_group($group) : '';
    
    my $statename = ( $state ) ? 'ON' : 'OFF';
    
    my $resultdata = { switch => $switch, status => $statename };
    
    $resultdata->{group}     = $self->format_group($group);
    $resultdata->{groupname} = $groupname;
    
    $self->set_result_success( $resultdata, 'switch' );
    
}

sub command_alias {
    my $self = shift;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    }
    
    if( $self->options->{list} ) {
        $self->list_switches('list');
        return;
    }
    
    my $groupname = $self->options->{groupname};
    my $switch    = $self->options->{switch};
    my $name      = $self->options->{name};
    my $group     = 0;
    
    unless( $switch && $switch =~ /^|1|2|3|4$/) {
        $self->set_result_error(
            ERROR_ALIAS_INVALID_SWITCH,
            q(You must provide a valid switch number --switch 0|1|2|3|4 ( 0 switches all switches in the group )),
            'alias'
        );
        return;
    }
    
    unless( $name ) {
        $self->set_result_error(
            ERROR_ALIAS_INVALID_OPTIONS,
            q(You must provide at least --switch and --name to alias a switch),
            'alias'
        );
        return;
    }
    
    if( $self->receiver ) {
        # we care about group name
        unless($groupname) {
            $self->set_result_options_error(
                ERROR_ALIAS_INVALID_OPTIONS,
                'You must provide --groupname, --switch and --name to alias a switch when using the txrx ENER314_RT or RF69HW boards',
                'alias'
            );
            return;
        }
        
        # get the group
        for my $checkgroup( keys %{ $self->conf->{groups} } ) {
            if(lc($self->conf->{groups}->{$checkgroup}) eq lc($groupname) ) {
                $group = $checkgroup;
                last;
            }
        }
        
        unless( $group ) {
            $self->set_result_error(
                ERROR_ALIAS_GROUP_NOT_FOUND,
                qq(Could not find a configured group named $groupname),
                'alias'
            );
            return;
        }
    } else {
        $group = ENERGENIE_ENER314_DUMMY_GROUP;
        $groupname = 'energenie_single_group';
    }
    
    # do we have an alias for this group already
    
    for my $switchname ( keys %{ $self->conf->{switches} } ) {
        if(   $self->conf->{switches}->{$switchname}->{switch} == $switch
           && $self->conf->{switches}->{$switchname}->{group} == $group )
        {
            delete($self->conf->{switches}->{$switchname});
        }
    }
    
    $self->conf->{switches}->{$name} = { group => $group, switch => $switch };
    $self->list_switches('alias');
    return;
}


sub command_join {
    my $self = shift;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    }
    
    if( $self->options->{list} ) {
        $self->list_adapters_monitors('list', 'both');
        return;
    }
    
    unless( $self->receiver ) {
        $self->set_result_error(
            ERROR_USUPPORTED_RX_COMMAND,
            q(You must be using board ENER314_RT or RF69HW to use join command),
            'join'
        );
        return;
    }
    
    my $name   = $self->options->{name};
    my $delete = $self->options->{delete};
    my $rename = $self->options->{rename};
    
    if( $delete ) {
        my $deleted;
        if(exists($self->conf->{adapters}->{$delete})) {
            delete($self->conf->{adapters}->{$delete});
            $deleted = 1;
        }
        if(exists($self->conf->{monitors}->{$delete})) {
            delete($self->conf->{monitors}->{$delete});
            $deleted = 1;
        }
        if( $deleted ) {
            $self->list_adapters_monitors('delete', 'both' );
            return;
        } else {
            $self->set_result_error(
                ERROR_JOIN_DEVICE_NOT_FOUND,
                qq(The adaptor or monitor named $delete was not found in configuration),
                'delete'
            );
            return;
        }
    } elsif( $rename ) {
        unless( $name ) {
            $self->set_result_options_error(
                ERROR_JOIN_INVALID_OPTIONS,
                q(You must provide a --name option together with iption --rename),
                'rename'
            );
            return;
        }
        
        # does name already exist
        if(exists($self->conf->{monitors}->{$name})) {
            $self->set_result_error(
                ERROR_JOIN_EXISTING_ADAPTER,
                qq(An adapter or monitor named $name already exists in your configuration ),
                'rename'
            );
            return;
        }
        # does rename exist
                
        unless(exists($self->conf->{monitors}->{$rename})) {
            $self->set_result_error(
                ERROR_JOIN_DEVICE_NOT_FOUND,
                qq(The adaptor or monitor named $rename was not found in configuration),
                'rename'
            );
            return;
        }
        
        $self->conf->{monitors}->{$name} = $self->conf->{monitors}->{$rename};
        delete( $self->conf->{monitors}->{$rename} );
        
        if(exists($self->conf->{adapters}->{$rename})) {
            $self->conf->{adapters}->{$name} = $self->conf->{adapters}->{$rename};
            delete( $self->conf->{adapters}->{$rename} );
        }
        
        $self->list_adapters_monitors('rename', 'both');
        return;
    }
    
    # does name already exist
    if(exists($self->conf->{adapters}->{$name})) {
        $self->set_result_error(
            ERROR_JOIN_EXISTING_ADAPTER,
            qq(An adapter or monitor named $name already exists in your configuration),
            'rename'
        );
        return;
    }
    
    # only show on console
    print STDERR qq(\nListening for join messages from adapters and monitors. Set your device mode to join ....\n\n);
    
    my $timeout = $self->options->{timeout};
    unless( $timeout =~ /^[1-9][0-9]*$/) {
        $self->set_result_options_error(
            ERROR_JOIN_INVALID_OPTIONS,
            qq(Invalid value for timeout $timeout),
        );
        return;
    }
    
    my $result =  try {
        my $handler = HiPi::Energenie->new(
            backend    => $self->conf->{board},
            devicename => $self->conf->{spi_device},
            reset_gpio => $self->conf->{reset_gpio},
        );
        
        return $handler->process_request(
            command  => 'join',
            timeout  => $timeout,
        );
    } catch {
        return { success => 0, error => $_ , catch_errorcode => ERROR_SYSTEM };
    };
    
    if( $result->{success} ) {
        
        my $joinmsg = $result->{data};
        
        # check if we know this sensor key
        if(my $registered_name = $self->registered_sensor( $joinmsg->sensor_key ) ) {
            my $sensorkey = $joinmsg->sensor_key;
            $self->set_result_error( ERROR_JOIN_FAILED, qq(Device $sensorkey is already registered as $registered_name), 'join' );
            return;
        }
        
        $self->conf->{monitors}->{$name} = {
            manufacturer_id => $joinmsg->manufacturer_id,
            product_id      => $joinmsg->product_id,
            product_name    => $joinmsg->product_name,
            sensor_id       => $joinmsg->sensor_id,
            sensor_key      => $joinmsg->sensor_key,
        };
        
        if( HiPi::RF::OpenThings->product_can_switch( $joinmsg->manufacturer_id, $joinmsg->product_id ) ) {
            $self->conf->{adapters}->{$name} = {
                manufacturer_id => $joinmsg->manufacturer_id,
                product_id      => $joinmsg->product_id,
                product_name    => $joinmsg->product_name,
                sensor_id       => $joinmsg->sensor_id,
                sensor_key      => $joinmsg->sensor_key,
            };
        }
        
        $self->list_adapters_monitors('join', 'both' );
    } else {
        my $error = $result->{error};
        $error =~ s/\n/ /g;
        my $errorcode = $result->{catch_errorcode} || ERROR_JOIN_FAILED;
        $self->set_result_error( $errorcode, $error, 'join' );
    }
}

sub command_adapter {
    my $self = shift;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    }
    
    if( $self->options->{list} ) {
        $self->list_adapters_monitors('list', 'adapters');
        return;
    }
    
    unless( $self->receiver ) {
        $self->set_result_error(
            ERROR_USUPPORTED_RX_COMMAND,
            q(You must be using board ENER314_RT or RF69HW to use the adapter command),
            'switch'
        );
        return;
    }
    
    my $name = $self->options->{name};
    
    unless($name) {
        $self->set_result_options_error(
            ERROR_ADAPTER_INVALID_OPTIONS,
            q(You must provide an adapter --name for the adapter command),

        );
        return;
    }
    
    my $nameconfig;
    
    # get the name
    for my $checkname( keys %{ $self->conf->{adapters} } ) {
        if(lc($checkname) eq lc($name) ) {
            $nameconfig = $self->conf->{adapters}->{$checkname};
            last;
        }
    }
    
    unless( $nameconfig ) {
        $self->set_result_error(
            ERROR_ADAPTER_NAME_NOT_FOUND,
            qq(Could not find a configured adapter named $name)
        );
        return;
    }
    
    my $timeout = $self->options->{timeout};

    if( $self->options->{query} ) {
        unless( $timeout =~ /^[1-9][0-9]*$/) {
            $self->set_result_options_error(
                ERROR_ADAPTER_INVALID_OPTIONS,
                qq(Invalid value for timeout $timeout),
                'query',
            );
            return;
        }
        $self->do_monitor_query( $nameconfig, 'adapter', $name, $timeout );
        return;
    }
    
    # in switch mode
    
    if(!$self->options->{on} && !$self->options->{off}) {
        $self->set_result_options_error(
            ERROR_ADAPTER_INVALID_OPTIONS,
            q(You must specify either --on or --off to switch an adapter),
            'switch',
        );
        return;
    }
    
    if($self->options->{on} && $self->options->{off}) {
        $self->set_result_options_error(
            ERROR_ADAPTER_INVALID_OPTIONS,
            q(You must specify either --on or --off - not both to switch an adapter),
            'switch',
        );
        return;
    }
    
    unless( $timeout =~ /^[1-9][0-9]*$/) {
        $self->set_result_options_error(
            ERROR_ADAPTER_INVALID_OPTIONS,
            qq(Invalid value for timeout $timeout),
            'switch',
        );
        return;
    }
    
    my $state = ( $self->options->{on} ) ? 1 : 0;
    
    # do switch
    
    my $result = try {
        my $handler = HiPi::Energenie->new(
            backend    => $self->conf->{board},
            devicename => $self->conf->{spi_device},
            reset_gpio => $self->conf->{reset_gpio},
        );
    
        my $val = $handler->process_request(
            command         => 'switch',
            sensor_key      => $nameconfig->{sensor_key},
            switch_state    => $state,
            timeout         => $timeout,
        );
        
        return $val;
    } catch {
        return { success => 0, error => $_ , catch_errorcode => ERROR_SYSTEM };
    };
    
    if( !$result->{success} ) {
        my $error = $result->{error};
        $error =~ s/\n/ /g;
        my $errorcode = $result->{catch_errorcode} || ERROR_ADAPTER_FAILED;
        $self->set_result_error( $errorcode, $error, 'switch' );
        return;
    }
    
    my $data = $result->{data};
    $data->configured_name( $name );
    
    $self->set_result_success($data, 'switch');
}

sub command_monitor {
    my $self = shift;
    
    if( $self->options->{help} ) {
        $self->set_result_success(undef, 'help');
        return;
    }
    
    if( $self->options->{list} ) {
        $self->list_adapters_monitors('list', 'monitors');
        return;
    }
    
    unless( $self->receiver ) {
        $self->set_result_error(
            ERROR_USUPPORTED_RX_COMMAND,
            q(You must be using board ENER314_RT or RF69HW to use the monitor command),
            'switch'
        );
        return;
    }
    
    my $name = $self->options->{name};
    
        unless($name) {
        $self->set_result_options_error(
            ERROR_MONITOR_INVALID_OPTIONS,
            q(You must provide a monitor --name for the monitor command),

        );
        return;
    }
    
    
    my $nameconfig;
    
    # get the name
    for my $checkname( keys %{ $self->conf->{monitors} } ) {
        if(lc($checkname) eq lc($name) ) {
            $nameconfig = $self->conf->{monitors}->{$checkname};
            last;
        }
    }
    
    unless( $nameconfig ) {
        $self->set_result_error(
            ERROR_MONITOR_NAME_NOT_FOUND,
            qq(Could not find a configured monitor named $name)
        );
        return;
    }
    
    my $timeout = $self->options->{timeout};
    unless( $timeout =~ /^[1-9][0-9]*$/) {
        $self->set_result_options_error(
            ERROR_MONITOR_INVALID_OPTIONS,
            qq(Invalid value for timeout $timeout),
        );
        return;
    }
    
    $self->do_monitor_query( $nameconfig, 'monitor', $name, $timeout );
}

sub do_monitor_query {
    my ( $self, $nameconfig, $type, $configname, $timeout ) = @_;
    
    my $result = try {
        my $handler = HiPi::Energenie->new(
            backend    => $self->conf->{board},
            devicename => $self->conf->{spi_device},
            reset_gpio => $self->conf->{reset_gpio},
        );
    
        my $val = $handler->process_request(
            command         => 'query',
            sensor_key      => $nameconfig->{sensor_key},
            timeout         => $timeout,
        );
        
        return $val;
    } catch {
        return { success => 0, error => $_ , catch_errorcode => ERROR_SYSTEM };
    };
    
    if( !$result->{success} ) {
        my $error = $result->{error};
        $error =~ s/\n/ /g;
        my $alterror = ( $type eq 'adapter ') ? ERROR_ADAPTER_FAILED : ERROR_MONITOR_FAILED;
        my $errorcode = $result->{catch_errorcode} || $alterror;
        $self->set_result_error( $errorcode, $error, 'query' );
        return;
    }
    
    my $data = $result->{data};
    
    $data->configured_name( $configname );
    
    $self->set_result_success($data, 'query');
    
    return;
}

sub list_configuration {
    my ($self, $option )  = @_;
    $self->config->write_config;
    $self->set_result_success( {
        'version'    => $self->conf->{version},
        'board'      => $self->conf->{board},
        'spi_device' => $self->conf->{spi_device},
        'reset_gpio' => $self->conf->{reset_gpio},
        'uses_spi'   => ( $self->receiver ) ? 'YES' : 'NO',
        'can_rx'     => ( $self->receiver ) ? 'YES' : 'NO',
        'epoch'      => $self->conf->{epoch} || 1,
    }, $option );
    return;
}

sub list_groups {
    my ($self, $option )  = @_;
    
    my $groups = {};
    
    for my $group ( keys %{ $self->conf->{groups} } ) {
        my $groupname = $self->conf->{groups}->{$group};
        $groups->{$groupname} = $self->format_group( $group );
    }
    
    $self->set_result_success( { groups => $groups }, $option );
    return;
}

sub list_adapters_monitors {
    my ($self, $option, $type) = @_;
    
    my @todolist = ( $type eq 'both' ) ? ( qw( adapters monitors )  ) : ( $type );
    
    my $resdata = {};
    
    for my $item ( @todolist ) {
        my $data = {};
        my $conf = $self->conf->{$item};
        for my $member ( keys %$conf ) {
            for my $element ( keys %{ $conf->{$member} } ) {
                $data->{$member}->{$element} = $conf->{$member}->{$element};
            }
        }
        $resdata->{$item} = $data;
    }
    
    $self->set_result_success( $resdata, $option );
    
    return;
}

sub list_switches {
    my ($self, $option) = @_;
        
    my $data = {};
    my $conf = $self->conf->{switches};
    for my $member ( keys %$conf ) {
        
        $data->{switches}->{$member}->{switch} = $conf->{$member}->{switch};
        $data->{switches}->{$member}->{group} = $self->conf->{groups}->{$conf->{$member}->{group}};
    }
    
    $self->set_result_success( $data, $option );
    
    return;
}

sub registered_sensor {
    my( $self, $sensorkey ) = @_;
    $sensorkey = lc($sensorkey);
    for my $item ( qw( adapters monitors ) ) {
        my $conf = $self->conf->{$item};
        for my $member ( keys %$conf ) {
            if( lc($conf->{$member}->{sensor_key})  eq  $sensorkey ) {
                return $member;
            }
        }
    }
    return undef;
}

sub generate_switch_group {
    my $self = shift;
    # a number between 0x1 and 0xFFFFF
    my $group = 1 + int(rand(0xFFFFE));
    return $group;
}

sub format_group {
    my ($self, $id) = @_;
    return sprintf('0x%06X', $id);
}

sub receiver {
    my $self = shift;
    return ( $self->conf->{board} =~ /^ENER314_RT|RF69HW$/ ) ? 1 : 0;
}

sub get_command_usage {
    my($self, $command) = @_;
    
    my $usagetext = {
        
    #### GENERAL USAGE ################################
    
        unknown => q(
  usage : hipi-energenie <command> [options]
  
  command :
    help        Print this message
    version     Print the version
    config      Configure the board type ( ENER314_RT, ENER314 or RF69HW )
    group       Manage groups for use with sockets
    pair        Pair a socket or switch
    alias       Rename or name a socket or switch
    switch      Switch a socket or switch on or off
    join        Configure a monitor or adaptor
    adapter     Switch an adapter device on or off
    monitor     Query a monitoring device for values

  For help on each command use:
    hipi-energenie <command> -h
),

    #### CONFIG USAGE ################################
    
       config => q(
  usage : hipi-energenie config <options>
  
  options :

    --help        -h  Display this message

    --list        -l  List the current config

    --board       -b  < ENER314 | ENER314_RT | RF69HW > Set the board type that
                      you have connected to the Raspberry Pi.
                      Default is 'ENER314_RT'

    --device      -d  < devicename > Set the SPI device used by the
                      ENER314_RT or RF69HW board. Default is '/dev/spidev0.1'
    
    --reset       -r  < gpio > Specify the GPIO pin connected to
                      the reset pin on the ENER314_RT or RF69HW board.
                      Default is 25 ( RPI_PIN_22 )
    
    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),
    #### GROUP USAGE ################################

        group => q(
  usage : hipi-energenie group <options>

  description: Set up groups for use with ENER314_RT or RF69HW board to
               control multiple sets of simple switches or sockets.

  options :

    --help        -h  Display this message

    --list        -l  List the currently configured groups

    --create      -c  <name> Create a new group. The system will create a new
                      unused group id and associate the supplied name with it.
                      e.g. hipi-energenie group -c newname
                      Provide option --groupid to name an existing group.                       
                      
    --delete      -d  <name> Delete an existing group.
                      e.g. hipi-energenie group -d 'my group 1'
                      
    --rename      -r  <name> Rename an existing group. Must be accompanied
                      by option for --newname.
                      e.g. hipi-energenie group -r oldname -n newname
    
    --newname     -n  <name> The new name for a group. (used with --rename)

    --groupid         <groupid> The group id identifier that is used
                      to control a group of four switches or sockets,
                      or one 4 way gang extension. This is a number
                      between 0x01 and 0xFFFFF. The parameter can be
                      passed in decimal, hexadecimal or binary
                      notation. It is parsed by the Perl 'oct'
                      function.

    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),

    #### PAIR USAGE ################################
    
        pair => q(
  usage : hipi-energenie pair <options>
  
  description: pair with a simple socket or switch such as an ENER002 switch
               socket; an ENER010 4 way extension; a Mi|Home MIHO002 adapter.
               Set the adapter to pairing mode and run this command.

  options :

    --help        -h  Display this message

    --list        -l  list paired switches
    
    --groupname   -g  <groupname> A groupname you have configured using the
                      group command. If you are using the transmit
                      only ENER314 board, this option is ignored.

    --switch      -s  < 1 | 2 | 3 | 4 > The number of the switch or socket
                      you want to pair. Each groupname can control a
                      maximum of 4 switches. If you are pairing an
                      ENER010 4 gang extension, use '1'
                      
    --name        -n  <switchname> A name for the paired switch
                      that you may use in the future to command the switch
                      rather than specifying both group and switch
                      number.

    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.
                      
    ( to rename a switch / group pair use the 'alias' command )

),        
    #### SWITCH USAGE ################################
    
        switch => q(
  usage : hipi-energenie switch <options>
  
  description: Turn a paired socket or switch on or off

  options :
    --help        -h  Display this message

    --list        -l  List the currently configured switches

    --name        -n  <switchname> An alias for the groupname / switch pair
    
    --groupname   -g  <groupname> If you don't provide a name you can specify
                      groupname and switch number instead. This is the
                      groupname you paired the switch with.
                      If you are using the transmit only ENER314 board,
                      this option is ignored.

    --switch      -s  < 0 | 1 | 2 | 3 | 4 > If you don't provide a name you can
                      specify groupname and switch number instead. This is the
                      number of the switch or socket you want to switch.
                      Specifying 0 switches all members of the group.
                      
    --on          -1  Switch the socket on

    --off         -0  Switch the socket off
    
    --all             Switch all sockets in the group. The same as specifying
                      --switch 0

    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),

#### ALAIS USAGE ################################
    
        alias => q(
  usage : hipi-energenie alias <options>
  
  description: Give a name to a groupname / switch number pair

  options :
    --help        -h  Display this message
    
    --list        -l  List configured aliases
    
    --name        -n  <switchname> The alias you want to use
    
    --groupname   -g  <groupname>  The group for the alias

    --switch      -s  < 1 | 2 | 3 | 4 > The switch number for the alias
                      
    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),        
    #### JOIN USAGE ################################
    
        join => q(
  usage : hipi-energenie join <options>
  
  description: Join a Mi|Home monitor or adapter. Run this command first and
               then switch your adapter or monitor to join mode.

  options :
  
    --help        -h  Display this message
    
    --list        -l  List the adapters and monitors already joined

    --name        -n  <name> A name for the adapter or monitor. This
                      is required.

    --rename      -r  <name> You can rename an adapter. If --rename is specified
                      then --rename contains the existing name and --name contains the
                      new name.
                      
    --delete      -d  <name> Remove the named monitor or adapter from configuration
    
    --timeout     -t <timeout> Timeout in seconds to wait for a join request.
                      The default is 60.

    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),
    #### ADAPTER USAGE ################################
      
        adapter => q(
  usage : hipi-energenie adapter <options>
  
  description: Switch a Mi|Home Adapter Plus on and off or query its switch state

  options :
  
    --help        -h  Display this message
    
    --list        -l  List all the adapters registered

    --name        -n  <name> The name registered for the adapter. This
                      is required.

    --query       -q  Get the switch state for the adapter
    
    --on          -1  Switch the adapter on
    
    --off         -0  Switch the adapter off
    
    --timeout     -t <timeout> Timeout in seconds to wait for a confirmation.
                      The default is 60.

    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),    
    #### MONITOR USAGE ################################
    
        monitor => q(
  usage : hipi-energenie monitor <options>
  
  description: Query status from a Mi|Home adapter or monitor

  options :
  
    --help        -h  Display this message
    
    --list        -l  List all the monitors registered

    --name        -n  <name> The name registered for the montitor. This
                      is required.
                      
    --timeout     -t <timeout> Timeout in seconds to wait for a response.
                      The default is 60.

    --json            The command results will be output as a JSON
                      string. This can be used when you want to parse
                      the command output from external code.

    --pretty          The command results will be output as formatted JSON
                      with line breaks and indentation.

),    
    };
    
    
    if(exists($usagetext->{$command})) {
        return $usagetext->{$command};
    } else {
        return $usagetext->{unknown};
    }
}

1;

__END__