forked from nbeguier/rfxcmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rfxcmd.py
executable file
·1818 lines (1493 loc) · 59.3 KB
/
rfxcmd.py
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
#!/usr/bin/env python3
# coding=UTF-8
"""
RFXCMD.PY
Based on Sebastian Sjoholm work https://github.com/ssjoholm/rfxcmd_gc
Copyright 2012-2014 Sebastian Sjoholm, sebastian.sjoholm@gmail.com
Licensed under the GNU General Public License, Version 3.0
Copyright 2018-2021 by Nicolas BEGUIER, nicolas_beguier@hotmail.com
#
# NOTES
#
# RFXCOM is a Trademark of RFSmartLink.
#
# ------------------------------------------------------------------------------
#
# Protocol License Agreement
#
# The RFXtrx protocols are owned by RFXCOM, and are protected under applicable
# copyright laws.
#
# ==============================================================================
# It is only allowed to use this protocol or any part of it for RFXCOM products
# ==============================================================================
#
# The above Protocol License Agreement and the permission notice shall be
# included in all software using the RFXtrx protocols.
#
# Any use in violation of the foregoing restrictions may subject the user to
# criminal sanctions under applicable laws, as well as to civil liability for
# the breach of the terms and conditions of this license.
#
# ------------------------------------------------------------------------------
"""
from __future__ import absolute_import
__author__ = "Sebastian Sjoholm"
__copyright__ = "Copyright 2012-2014, Sebastian Sjoholm"
__license__ = "GPL"
__version__ = "2.0.1"
__maintainer__ = "Nicolas Béguier"
__date__ = "$Date: 2019-06-12 08:05:33 +0100 (Thu, 12 Jun 2019) $"
# Standard library
from codecs import decode as codecs_decode
from inspect import currentframe, getframeinfo
from json import dumps
from logging import Formatter, StreamHandler, getLogger, getLevelName, FileHandler
from argparse import ArgumentParser
import os
from time import strftime, sleep
from traceback import format_exc
from re import match
from signal import signal, SIGINT, SIGTERM
from string import whitespace
import sys
import xml.dom.minidom as minidom
# ------------------------------------------------------------------------------
# ADDED FOR MQTT - Requires paho MQTT (pip install paho-mqtt)
# ------------------------------------------------------------------------------
import paho.mqtt.client as mqtt
# 3rd party library
# These might not be needed, depended on usage
from serial import Serial, VERSION, SerialException
# Debug
# from pdb import set_trace as st
# RFXCMD library
from lib.rfx_socket import MESSAGEQUEUE, RFXcmdSocketAdapter
from lib.rfx_utils import stripped, ByteToHex
import lib.rfx_sensors
import lib.rfx_decode_0x0 as rfxdecode0x0
import lib.rfx_decode_0x1 as rfxdecode0x1
import lib.rfx_decode_0x2 as rfxdecode0x2
import lib.rfx_decode_0x3 as rfxdecode0x3
import lib.rfx_decode_0x4 as rfxdecode0x4
import lib.rfx_decode_0x5 as rfxdecode0x5
import lib.rfx_decode_0x7 as rfxdecode0x7
import lib.rfx_protocols as protocol
# ------------------------------------------------------------------------------
# VARIABLE CLASSS
# ------------------------------------------------------------------------------
class ConfigData:
"""
Configuration Data
"""
def __init__(
self,
barometric=0,
daemon_active=False,
daemon_pidfile="rfxcmd.pid",
device=None,
log_msg=False,
log_msgfile="",
logfile="rfxcmd.log",
loglevel="info",
MQTThost="",
MQTTport=1883,
MQTTtopic="sensor/oregon/",
MQTTqos=2,
MQTTretain=True,
MQTTsenddata=["Temperature", "Humidity"],
MQTTunits="imperial",
outputfile="./log/output.log",
process_rfxmsg=True,
program_path="",
protocol_file="protocol.xml",
protocol_startup=False,
sendMQTT=False,
serial_active=True,
serial_device=None,
serial_rate=38400,
serial_timeout=9,
sockethost="",
socketport="",
socketserver=False,
whitelist_active=False,
whitelist_file="",
):
self.barometric = barometric
self.daemon_active = daemon_active
self.daemon_pidfile = daemon_pidfile
self.device = device
self.log_msg = log_msg
self.log_msgfile = log_msgfile
self.logfile = logfile
self.loglevel = loglevel
self.MQTThost = MQTThost
self.MQTTport = MQTTport
self.MQTTtopic = MQTTtopic
self.MQTTqos = MQTTqos
self.MQTTretain = MQTTretain
self.MQTTsenddata = MQTTsenddata
self.MQTTunits = MQTTunits
self.outputfile = outputfile
self.process_rfxmsg = process_rfxmsg
self.program_path = program_path
self.protocol_file = protocol_file
self.protocol_startup = protocol_startup
self.serial_active = serial_active
self.sendMQTT = sendMQTT
self.serial_device = serial_device
self.serial_rate = serial_rate
self.serial_timeout = serial_timeout
self.sockethost = sockethost
self.socketport = socketport
self.socketserver = socketserver
self.whitelist_active = whitelist_active
self.whitelist_file = whitelist_file
class CmdArgData:
"""
Command Argument Data
"""
def __init__(
self,
action="",
configfile="",
createpid=False,
device="",
pidfile="",
printout_complete=False,
printout_csv=False,
printout_debug=False,
rawcmd="",
):
self.action = action
self.configfile = configfile
self.createpid = createpid
self.device = device
self.pidfile = pidfile
self.printout_complete = printout_complete
self.printout_csv = printout_csv
self.printout_debug = printout_debug
self.rawcmd = rawcmd
class RfxCmdData:
"""
RFX Command Data
"""
def __init__(
self,
reset="0d00000000000000000000000000",
save="0d00000006000000000000000000",
status="0d00000002000000000000000000",
):
self.reset = reset
self.save = save
self.status = status
class SerialData:
"""
Serial Data
"""
def __init__(
self,
port=None,
rate=38400,
timeout=9
):
self.port = port
self.rate = rate
self.timeout = timeout
class WhitelistData:
"""
Store the whitelist data from xml file
"""
def __init__(
self,
data=""
):
self.data = data
# ----------------------------------------------------------------------------
# DEAMONIZE
# Credit: George Henze
# ----------------------------------------------------------------------------
def shutdown():
"""
Shutdown function
"""
# clean up PID file after us
log_me("debug", "Shutdown")
if CMDARG.createpid:
log_me("debug", "Removing PID file " + str(CMDARG.pidfile))
os.remove(CMDARG.pidfile)
if SERIAL_PARAM.port is not None:
log_me("debug", "Close serial port")
SERIAL_PARAM.port.close()
SERIAL_PARAM.port = None
log_me("debug", "Exit 0")
sys.stdout.flush()
# pylint: disable=protected-access
os._exit(0)
# pylint: disable=unused-argument
def handler(signum=None, frame=None):
"""
Handler, signum & frame are used
"""
if not isinstance(signum, type(None)):
log_me("debug", "Signal %i caught, exiting..." % int(signum))
shutdown()
def daemonize():
"""
Daemonize
"""
try:
pid = os.fork()
if pid != 0:
sys.exit(0)
except OSError as err:
raise RuntimeError("1st fork failed: %s [%d]" % (err.strerror, err.errno)) from err
os.setsid()
prev = os.umask(0)
os.umask(prev and int('077', 8))
try:
pid = os.fork()
if pid != 0:
sys.exit(0)
except OSError as err:
raise RuntimeError("2nd fork failed: %s [%d]" % (err.strerror, err.errno)) from err
if CMDARG.createpid:
pid = str(os.getpid())
log_me("debug", "Writing PID " + pid + " to " + str(CMDARG.pidfile))
pid_file = open(CMDARG.pidfile, "w")
pid_file.write("%s\n" % pid)
pid_file.close()
# ----------------------------------------------------------------------------
# C __LINE__ equivalent in Python by Elf Sternberg
# http://www.elfsternberg.com/2008/09/23/c-__line__-equivalent-in-python/
# ----------------------------------------------------------------------------
def _line():
info = getframeinfo(currentframe().f_back)[0:3]
return '[%s:%d]' % (info[2], info[1])
# ----------------------------------------------------------------------------
def readbytes(number):
"""
Read x amount of bytes from serial port.
Credit: Boris Smus http://smus.com
"""
buf = bytes()
for _ in range(number):
try:
byte = SERIAL_PARAM.port.read()
except (IOError, OSError) as err:
log_me("error", err)
buf += byte
return buf
# ----------------------------------------------------------------------------
def decode_packet(message):
"""
Decode incoming RFXtrx message.
"""
timestamp = strftime('%Y-%m-%d %H:%M:%S')
decoded = False
# Verify incoming message
log_me("debug", "Verify incoming packet")
if not test_rfx(ByteToHex(message)):
log_me("error", "The incoming message is invalid (" +
ByteToHex(message) + ") Line: " + _line())
return
log_me("debug", "Verified OK")
raw_message = ByteToHex(message)
raw_message = raw_message.replace(' ', '')
packettype = ByteToHex(message[1])
log_me("debug", "PacketType: %s" % str(packettype))
subtype = None
if len(message) > 2:
subtype = ByteToHex(message[2])
log_me("debug", "SubType: %s" % str(subtype))
seqnbr = None
if len(message) > 3:
seqnbr = ByteToHex(message[3])
log_me("debug", "SeqNbr: %s" % str(seqnbr))
id1 = None
if len(message) > 4:
id1 = ByteToHex(message[4])
log_me("debug", "Id1: %s" % str(id1))
id2 = None
if len(message) > 5:
id2 = ByteToHex(message[5])
log_me("debug", "Id2: %s" % str(id2))
log_me("info", "Packettype\t\t\t= " + RFX.rfx_packettype[packettype])
# ---------------------------------------
# Verify correct length on packets
# ---------------------------------------
log_me("debug", "Verify correct packet length")
if packettype == '00' and len(message) != 14:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '01' and len(message) != 14 and len(message) != 21:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '02' and len(message) != 5:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '10' and len(message) != 8:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '11' and len(message) != 12:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '12' and len(message) != 9:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '13' and len(message) != 10:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '14' and len(message) != 11:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '15' and len(message) != 12:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '16' and len(message) != 8:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '17' and len(message) != 8:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '18' and len(message) != 8:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '19' and len(message) != 10:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '1A' and len(message) != 13:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '20' and len(message) != 9:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '28' and len(message) != 7:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '30' and len(message) != 8:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '40' and len(message) != 10:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '41' and len(message) != 7:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '42' and len(message) != 9:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '4E' and len(message) != 11:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '4F' and len(message) != 11:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '50' and len(message) != 9:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '51' and len(message) != 9:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '52' and len(message) != 11:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '53' and len(message) != 10:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '54' and len(message) != 14:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '55' and len(message) != 12:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '56' and len(message) != 17:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '57' and len(message) != 10:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '58' and len(message) != 14:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '59' and len(message) != 14:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '5A' and len(message) != 18:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '5B' and len(message) != 20:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '5C' and len(message) != 16:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '5D' and len(message) != 9:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '70' and len(message) != 8:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '71' and len(message) != 11:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
if packettype == '72' and len(message) != 10:
log_me("error", "Packet has wrong length, discarding")
decoded = True
packettype = None
# ---------------------------------------
# If packet is OK and the log_msg is active
# then save the packet to log_msgfile designated
# file on disk
# ---------------------------------------
if not decoded and CONFIG.log_msg:
log_me("debug", "Save packet to log_msgfile")
try:
data = str(ByteToHex(message))
data = data.replace(' ', '')
config_file = open(CONFIG.log_msgfile, "a+")
config_file.write(data + "\n")
config_file.close()
except Exception as err:
log_me("error", "Error when trying to write message log")
log_me("error", err)
metadata = list()
output_extra = list()
# 0x0 - Interface Control
if packettype == '00':
log_me("debug", "Decode packetType 0x" + str(packettype) + " - Start")
decoded = True
# 0x01 - Interface Message
if packettype == '01':
decoded = True
metadata, output_extra = rfxdecode0x0.decode_0x01(message)
# 0x02 - Receiver/Transmitter Message
if packettype == '02':
decoded = True
metadata, output_extra = rfxdecode0x0.decode_0x02(subtype, seqnbr, id1)
# 0x03 - Undecoded Message
if packettype == '03':
decoded = True
metadata, output_extra = rfxdecode0x0.decode_0x03(message, subtype, seqnbr)
# 0x10 Lighting1
if packettype == '10':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x10(message, subtype, seqnbr)
# 0x11 Lighting2
if packettype == '11':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x11(message, subtype, seqnbr)
# 0x12 Lighting3
if packettype == '12':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x12(message, subtype, seqnbr)
# 0x13 Lighting4
if packettype == '13':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x13(message, subtype, seqnbr)
# 0x14 Lighting5
if packettype == '14':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x14(message, subtype, seqnbr, id1, id2)
# 0x15 Lighting6
if packettype == '15':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x15(message, subtype, seqnbr, id1, id2)
# 0x16 Chime
if packettype == "16":
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x16(message, subtype, seqnbr, id1, id2)
# 0x17 Fan (Transmitter only)
if packettype == '17':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x17(subtype, seqnbr)
# 0x18 Curtain1 (Transmitter only)
if packettype == '18':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x18(subtype, seqnbr)
# 0x19 Blinds1
if packettype == '19':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x19(subtype, seqnbr)
# 0x1A RTS
if packettype == '1A':
decoded = True
metadata, output_extra = rfxdecode0x1.decode_0x1a(message, subtype, seqnbr, id1, id2)
# 0x20 Security1
if packettype == '20':
decoded = True
metadata, output_extra = rfxdecode0x2.decode_0x20(message, subtype, seqnbr, id1, id2)
# 0x28 Camera1
if packettype == '28':
decoded = True
metadata, output_extra = rfxdecode0x2.decode_0x28(subtype, seqnbr)
# 0x30 Remote control and IR
if packettype == '30':
decoded = True
metadata, output_extra = rfxdecode0x3.decode_0x30(message, subtype, seqnbr, id1)
# 0x40 Thermostat1
if packettype == '40':
decoded = True
metadata, output_extra = rfxdecode0x4.decode_0x40(message, subtype, seqnbr, id1, id2)
# 0x41 Thermostat2
if packettype == '41':
decoded = True
metadata, output_extra = rfxdecode0x4.decode_0x41(subtype, seqnbr)
# 0x42 Thermostat3
if packettype == '42':
decoded = True
metadata, output_extra = rfxdecode0x4.decode_0x42(message, subtype, seqnbr, id1, id2)
# 0x50 Temperature sensors
if packettype == '50':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x50(message, subtype, seqnbr, id1, id2)
# 0x51 Humidity sensors
if packettype == '51':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x51(message, subtype, seqnbr, id1, id2)
# 0x52 Temperature and humidity sensors
if packettype == '52':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x52(message, subtype, seqnbr, id1, id2)
# 0x53 Barometric
if packettype == '53':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x53(subtype, seqnbr)
# 0x54 Temperature, humidity and barometric sensors
if packettype == '54':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x54(message, subtype, seqnbr, id1, id2, \
CONFIG.barometric)
# 0x55 Rain sensors
if packettype == '55':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x55(message, subtype, seqnbr, id1, id2)
# 0x56 Wind sensors
if packettype == '56':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x56(message, subtype, seqnbr, id1, id2)
# 0x57 UV Sensor
if packettype == '57':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x57(message, subtype, seqnbr, id1, id2)
# 0x58 Date/Time sensor
if packettype == '58':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x58(message, subtype, seqnbr, id1, id2)
# 0x59 Current Sensor
if packettype == '59':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x59(message, subtype, seqnbr, id1, id2)
# 0x5A Energy sensor
if packettype == '5A':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x5a(message, subtype, seqnbr, id1, id2)
# 0x5B Current Sensor
if packettype == '5B':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x5b(message, subtype, seqnbr, id1, id2)
# 0x5C Power Sensors
if packettype == '5C':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x5c(message, subtype, seqnbr, id1, id2)
# 0x5D
if packettype == '5D':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x5d(subtype, seqnbr)
# 0x5E Gas Usage Sensor
if packettype == '5E':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x5e(subtype, seqnbr)
# 0x5F Water Usage Sensor
if packettype == '5F':
decoded = True
metadata, output_extra = rfxdecode0x5.decode_0x5f(subtype, seqnbr)
# 0x70 RFXsensor
if packettype == '70':
decoded = True
metadata, output_extra = rfxdecode0x7.decode_0x70(message, subtype, seqnbr, id1)
# 0x71 RFXmeter
if packettype == '71':
decoded = True
metadata, output_extra = rfxdecode0x7.decode_0x71(message, subtype, seqnbr, id1, id2)
# 0x72 FS20
if packettype == '72':
decoded = True
metadata, output_extra = rfxdecode0x7.decode_0x72(subtype, seqnbr)
# Not decoded message
# The packet is not decoded, then log_me("info", it on the screen)
if not decoded:
log_me("error", "Message not decoded. Line: " + _line())
log_me("error", "Message: " + ByteToHex(message))
log_me("info", timestamp + " " + ByteToHex(message))
log_me("info", "RFXCMD cannot decode message, see http://code.google.com/p/rfxcmd/wiki/")
# Print result
print_decoded(metadata)
# output_me(timestamp, message, packettype, subtype, seqnbr, output_extra)
# MQTT Send
if CONFIG.sendMQTT:
sendMQTT(packettype, metadata)
# decodePackage END
return
# ----------------------------------------------------------------------------
def sendMQTT(packettype, metadata):
if packettype >= '50' and packettype <= '57' :
log_me("debug","SENDING MQTT")
log_me("debug","packettype=" + packettype )
log_me("debug","MQTTunits=" + CONFIG.MQTTunits )
log_me("debug","MQTTsenddata=" + CONFIG.MQTTsenddata )
outputList = CONFIG.MQTTsenddata.lower().split(",")
for x in metadata:
if x["key"].lower() == "id":
deviceId = x["value"]
for y in outputList:
if y == x["key"].lower() :
# Parse and send this item
topic = CONFIG.MQTTtopic + deviceId + "/" + x["key"].lower()
payload = str( x["value"] )
# Special case for units
if x["key"].lower() == "temperature" and CONFIG.MQTTunits.lower() == "imperial":
payload = str( float(payload) * 9 / 5 + 32 )
log_me("info","MQTT SENT: " + topic + " " + payload )
client = mqtt.Client("rfxcomClient")
client.connect(CONFIG.MQTThost, int(CONFIG.MQTTport), 60)
client.publish(topic, payload )
# ----------------------------------------------------------------------------
def read_socket():
"""
Check socket for messages
Credit: Olivier Djian
"""
if not MESSAGEQUEUE.empty():
log_me("debug", "Message received in socket MESSAGEQUEUE")
message = MESSAGEQUEUE.get().decode("UTF-8")
if test_rfx(message):
if CONFIG.serial_active:
# Flush buffer
SERIAL_PARAM.port.flushOutput()
log_me("debug", "SerialPort flush output")
SERIAL_PARAM.port.flushInput()
log_me("debug", "SerialPort flush input")
timestamp = strftime('%Y-%m-%d %H:%M:%S')
log_me("info", "------------------------------------------------")
log_me("info", "Incoming message from socket")
log_me("info", "Send\t\t\t= " + ByteToHex(codecs_decode(message, "hex")))
log_me("info", "Date/Time\t\t\t= " + timestamp)
log_me("info", "Packet Length\t\t= " + ByteToHex(codecs_decode(message, "hex")[0]))
try:
log_me("debug", "Decode message")
decode_packet(codecs_decode(message, "hex"))
except KeyError:
log_me("error", "Unrecognizable packet. Line: " + _line())
if CONFIG.serial_active:
log_me("debug", "Write message to serial port")
SERIAL_PARAM.port.write(codecs_decode(message, "hex"))
else:
log_me("error", "Invalid message from socket. Line: " + _line())
# ----------------------------------------------------------------------------
def test_rfx(message):
"""
Test, filter and verify that the incoming message is valid
Return true if valid, False if not
"""
log_me("debug", "Test message: " + message)
# Remove all invalid characters
message = stripped(message)
return_statement = True
# Remove any whitespaces
try:
message = message.replace(' ', '')
except Exception:
log_me("error", "Removing white spaces")
return False
# Test the string if it is hex format
if message == '':
log_me("error", "Packet empty")
return_statement = False
# Check that length is even
elif len(message) % 2:
log_me("error", "Packet length not even")
return_statement = False
# Check that first byte is not 00
elif ByteToHex(codecs_decode(message, "hex")[0]) == "00":
log_me("error", "Packet first byte is 00")
return_statement = False
# Length more than one byte
elif not len(codecs_decode(message, "hex")) > 1:
log_me("error", "Packet is not longer than one byte")
return_statement = False
# Check if string is the length that it reports to be
elif not len(codecs_decode(message, "hex")) == (codecs_decode(message, "hex")[0] + 1):
log_me("error", "Packet length is not valid")
return_statement = False
else:
log_me("debug", "Message OK")
return return_statement
# ----------------------------------------------------------------------------
def send_rfx(message):
"""
Decode and send raw message to RFX device
"""
timestamp = strftime("%Y-%m-%d %H:%M:%S")
log_me("info", "------------------------------------------------")
log_me("info", "Send\t\t\t= " + ByteToHex(message))
log_me("info", "Date/Time\t\t\t= " + timestamp)
log_me("info", "Packet Length\t\t= " + ByteToHex(message[0]))
try:
decode_packet(message)
except KeyError as err:
log_me("error", "unrecognizable packet %s" % err)
SERIAL_PARAM.port.write(message)
sleep(1)
# ----------------------------------------------------------------------------
def read_rfx():
"""
Read message from RFXtrx and decode the decode the message
"""
message = None
byte = None
try:
try:
if SERIAL_PARAM.port.inWaiting() != 0:
timestamp = strftime("%Y-%m-%d %H:%M:%S")
log_me("debug", "Timestamp: " + timestamp)
log_me("debug", "SerWaiting: " + str(SERIAL_PARAM.port.inWaiting()))
byte = SERIAL_PARAM.port.read()
log_me("debug", "Byte: " + str(ByteToHex(byte)))
except IOError as err:
log_me("error", err)
log_me("error", "Serial read %s, Line: %s" % (str(err), _line()))
if byte:
message = byte + readbytes(ord(byte))
log_me("debug", "Message: " + str(ByteToHex(message)))
# First byte indicate length of message, must be other than 00
if ByteToHex(message[0]) != "00":
# Verify length
log_me("debug", "Verify length")
if (len(message) - 1) == message[0]:
log_me("debug", "Length OK")
# Whitelist
if CONFIG.whitelist_active:
log_me("debug", "Check whitelist")
whitelist_match = False
for sensor in WHITELIST.data:
sensor = sensor.childNodes[0].nodeValue
log_me("debug", "Tag: " + sensor)
rawcmd = ByteToHex(message)
rawcmd = rawcmd.replace(' ', '')
if match(sensor, rawcmd):
log_me("debug", "Whitelist match")
whitelist_match = True
if not whitelist_match:
log_me("info", "Sensor not included in whitelist")
return rawcmd
log_me("info", "------------------------------------------------")
log_me("info", "Received\t\t\t= " + ByteToHex(message))
log_me("info", "Date/Time\t\t\t= " + timestamp)
log_me("info", "Packet Length\t\t= " + ByteToHex(message[0]))
log_me("debug", 'Decode packet')