-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
rtl_433_mqtt_hass.py
executable file
·1127 lines (977 loc) · 34.5 KB
/
rtl_433_mqtt_hass.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 python
# coding=utf-8
from __future__ import print_function
from __future__ import with_statement
AP_DESCRIPTION="""
Publish Home Assistant MQTT auto discovery topics for rtl_433 devices.
rtl_433_mqtt_hass.py connects to MQTT and subscribes to the rtl_433
event stream that is published to MQTT by rtl_433. The script publishes
additional MQTT topics that can be used by Home Assistant to automatically
discover and minimally configure new devices.
The configuration topics published by this script tell Home Assistant
what MQTT topics to subscribe to in order to receive the data published
as device topics by MQTT.
"""
AP_EPILOG="""
It is strongly recommended to run rtl_433 with "-C si".
This script requires rtl_433 to publish both event messages and device
messages. If you've changed the device topic in rtl_433, use the same device
topic with the "-T" parameter.
MQTT Username and Password can be set via the cmdline or passed in the
environment: MQTT_USERNAME and MQTT_PASSWORD.
Prerequisites:
1. rtl_433 running separately publishing events and devices messages to MQTT.
2. Python installation
* Python 3.x preferred.
* Needs Paho-MQTT https://pypi.python.org/pypi/paho-mqtt
Debian/raspbian: apt install python3-paho-mqtt
Or
pip install paho-mqtt
* Optional for running as a daemon see PEP 3143 - Standard daemon process library
(use Python 3.x or pip install python-daemon)
Running:
This script can run continually as a daemon, where it will publish
a configuration topic for the device events sent to MQTT by rtl_433
every 10 minutes.
Alternatively if the rtl_433 devices in your environment change infrequently
this script can use the MQTT retain flag to make the configuration topics
persistent. The script will only need to be run when things change or if
the MQTT server loses its retained messages.
Getting rtl_433 devices back after Home Assistant restarts will happen
more quickly if MQTT retain is enabled. Note however that definitions
for any transitient devices/false positives will retained indefinitely.
If your sensor values change infrequently and you prefer to write the most
recent value even if not changed set -f to append "force_update = true" to
all configs. This is useful if you're graphing the sensor data or want to
alert on missing data.
If you have changed the topic structure from the default topics in the rtl433
configuration use the -T parameter to set the same topic structure here.
Suggestions:
Running this script will cause a number of Home Assistant entities (sensors
and binary sensors) to be created. These entities can linger for a while unless
the topic is republished with an empty config string. To avoid having to
do a lot of clean up When running this initially or debugging, set this
script to publish to a topic other than the one Home Assistant users (homeassistant).
MQTT Explorer (http://mqtt-explorer.com/) is a very nice GUI for
working with MQTT. It is free, cross platform, and OSS. The structured
hierarchical view makes it easier to understand what rtl_433 is publishing
and how this script works with Home Assistant.
MQTT Explorer also makes it easy to publish an empty config topic to delete an
entity from Home Assistant.
As of 2020-10, Home Assistant MQTT auto discovery doesn't currently support
supplying "friendly name", and "area" key, so some configuration must be
done in Home Assistant.
There is a single global set of field mappings to Home Assistant meta data.
"""
# import daemon
import os
import argparse
import logging
import time
import json
import paho.mqtt.client as mqtt
import re
discovery_timeouts = {}
# Fields that get ignored when publishing to Home Assistant
# (reduces noise to help spot missing field mappings)
SKIP_KEYS = [ "type", "model", "subtype", "channel", "id", "mic", "mod",
"freq", "sequence_num", "message_type", "exception", "raw_msg" ]
# Global mapping of rtl_433 field names to Home Assistant metadata.
# @todo - should probably externalize to a config file
# @todo - Model specific definitions might be needed
mappings = {
"temperature_C": {
"device_type": "sensor",
"object_suffix": "T",
"config": {
"device_class": "temperature",
"name": "Temperature",
"unit_of_measurement": "°C",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"temperature_1_C": {
"device_type": "sensor",
"object_suffix": "T1",
"config": {
"device_class": "temperature",
"name": "Temperature 1",
"unit_of_measurement": "°C",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"temperature_2_C": {
"device_type": "sensor",
"object_suffix": "T2",
"config": {
"device_class": "temperature",
"name": "Temperature 2",
"unit_of_measurement": "°C",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"temperature_3_C": {
"device_type": "sensor",
"object_suffix": "T3",
"config": {
"device_class": "temperature",
"name": "Temperature 3",
"unit_of_measurement": "°C",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"temperature_4_C": {
"device_type": "sensor",
"object_suffix": "T4",
"config": {
"device_class": "temperature",
"name": "Temperature 4",
"unit_of_measurement": "°C",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"temperature_F": {
"device_type": "sensor",
"object_suffix": "F",
"config": {
"device_class": "temperature",
"name": "Temperature",
"unit_of_measurement": "°F",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
# This diagnostic sensor is useful to see when a device last sent a value,
# even if the value didn't change.
# https://community.home-assistant.io/t/send-metrics-to-influxdb-at-regular-intervals/9096
# https://github.com/home-assistant/frontend/discussions/13687
"time": {
"device_type": "sensor",
"object_suffix": "UTC",
"config": {
"device_class": "timestamp",
"name": "Timestamp",
"entity_category": "diagnostic",
"enabled_by_default": False,
"icon": "mdi:clock-in"
}
},
"battery_ok": {
"device_type": "sensor",
"object_suffix": "B",
"config": {
"device_class": "battery",
"name": "Battery",
"unit_of_measurement": "%",
"value_template": "{{ ((float(value) * 99)|round(0)) + 1 }}",
"state_class": "measurement",
"entity_category": "diagnostic"
}
},
"battery_mV": {
"device_type": "sensor",
"object_suffix": "mV",
"config": {
"device_class": "voltage",
"name": "Battery mV",
"unit_of_measurement": "mV",
"value_template": "{{ float(value) }}",
"state_class": "measurement",
"entity_category": "diagnostic"
}
},
"supercap_V": {
"device_type": "sensor",
"object_suffix": "V",
"config": {
"device_class": "voltage",
"name": "Supercap V",
"unit_of_measurement": "V",
"value_template": "{{ float(value) }}",
"state_class": "measurement",
"entity_category": "diagnostic"
}
},
"humidity": {
"device_type": "sensor",
"object_suffix": "H",
"config": {
"device_class": "humidity",
"name": "Humidity",
"unit_of_measurement": "%",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"humidity_1": {
"device_type": "sensor",
"object_suffix": "H1",
"config": {
"device_class": "humidity",
"name": "Humidity 1",
"unit_of_measurement": "%",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"humidity_2": {
"device_type": "sensor",
"object_suffix": "H2",
"config": {
"device_class": "humidity",
"name": "Humidity 2",
"unit_of_measurement": "%",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"moisture": {
"device_type": "sensor",
"object_suffix": "M",
"config": {
"device_class": "moisture",
"name": "Moisture",
"unit_of_measurement": "%",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"detect_wet": {
"device_type": "binary_sensor",
"object_suffix": "moisture",
"config": {
"name": "Water Sensor",
"device_class": "moisture",
"force_update": "true",
"payload_on": "1",
"payload_off": "0"
}
},
"pressure_hPa": {
"device_type": "sensor",
"object_suffix": "P",
"config": {
"device_class": "pressure",
"name": "Pressure",
"unit_of_measurement": "hPa",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"pressure_kPa": {
"device_type": "sensor",
"object_suffix": "P",
"config": {
"device_class": "pressure",
"name": "Pressure",
"unit_of_measurement": "kPa",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"wind_speed_km_h": {
"device_type": "sensor",
"object_suffix": "WS",
"config": {
"device_class": "wind_speed",
"name": "Wind Speed",
"unit_of_measurement": "km/h",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"wind_avg_km_h": {
"device_type": "sensor",
"object_suffix": "WS",
"config": {
"device_class": "wind_speed",
"name": "Wind Speed",
"unit_of_measurement": "km/h",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"wind_avg_mi_h": {
"device_type": "sensor",
"object_suffix": "WS",
"config": {
"device_class": "wind_speed",
"name": "Wind Speed",
"unit_of_measurement": "mi/h",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"wind_avg_m_s": {
"device_type": "sensor",
"object_suffix": "WS",
"config": {
"device_class": "wind_speed",
"name": "Wind Average",
"unit_of_measurement": "km/h",
"value_template": "{{ (float(value|float) * 3.6) | round(2) }}",
"state_class": "measurement"
}
},
"wind_speed_m_s": {
"device_type": "sensor",
"object_suffix": "WS",
"config": {
"device_class": "wind_speed",
"name": "Wind Speed",
"unit_of_measurement": "km/h",
"value_template": "{{ float(value|float) * 3.6 }}",
"state_class": "measurement"
}
},
"gust_speed_km_h": {
"device_type": "sensor",
"object_suffix": "GS",
"config": {
"device_class": "wind_speed",
"name": "Gust Speed",
"unit_of_measurement": "km/h",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"wind_max_km_h": {
"device_type": "sensor",
"object_suffix": "GS",
"config": {
"device_class": "wind_speed",
"name": "Wind max speed",
"unit_of_measurement": "km/h",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"wind_max_m_s": {
"device_type": "sensor",
"object_suffix": "GS",
"config": {
"device_class": "wind_speed",
"name": "Wind max",
"unit_of_measurement": "km/h",
"value_template": "{{ (float(value|float) * 3.6) | round(2) }}",
"state_class": "measurement"
}
},
"gust_speed_m_s": {
"device_type": "sensor",
"object_suffix": "GS",
"config": {
"device_class": "wind_speed",
"name": "Gust Speed",
"unit_of_measurement": "km/h",
"value_template": "{{ float(value|float) * 3.6 }}",
"state_class": "measurement"
}
},
"wind_dir_deg": {
"device_type": "sensor",
"object_suffix": "WD",
"config": {
"name": "Wind Direction",
"unit_of_measurement": "°",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"rain_mm": {
"device_type": "sensor",
"object_suffix": "RT",
"config": {
"device_class": "precipitation",
"name": "Rain Total",
"unit_of_measurement": "mm",
"value_template": "{{ value|float|round(2) }}",
"state_class": "total_increasing"
}
},
"rain_rate_mm_h": {
"device_type": "sensor",
"object_suffix": "RR",
"config": {
"device_class": "precipitation_intensity",
"name": "Rain Rate",
"unit_of_measurement": "mm/h",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"rain_in": {
"device_type": "sensor",
"object_suffix": "RT",
"config": {
"device_class": "precipitation",
"name": "Rain Total",
"unit_of_measurement": "in",
"value_template": "{{ value|float|round(2) }}",
"state_class": "total_increasing"
}
},
"rain_rate_in_h": {
"device_type": "sensor",
"object_suffix": "RR",
"config": {
"device_class": "precipitation_intensity",
"name": "Rain Rate",
"unit_of_measurement": "in/h",
"value_template": "{{ value|float|round(2) }}",
"state_class": "measurement"
}
},
"reed_open": {
"device_type": "binary_sensor",
"object_suffix": "reed_open",
"config": {
"device_class": "safety",
"force_update": "true",
"payload_on": "1",
"payload_off": "0",
"entity_category": "diagnostic"
}
},
"contact_open": {
"device_type": "binary_sensor",
"object_suffix": "contact_open",
"config": {
"device_class": "safety",
"force_update": "true",
"payload_on": "1",
"payload_off": "0",
"entity_category": "diagnostic"
}
},
"tamper": {
"device_type": "binary_sensor",
"object_suffix": "tamper",
"config": {
"device_class": "safety",
"force_update": "true",
"payload_on": "1",
"payload_off": "0",
"entity_category": "diagnostic"
}
},
"alarm": {
"device_type": "binary_sensor",
"object_suffix": "alarm",
"config": {
"device_class": "safety",
"force_update": "true",
"payload_on": "1",
"payload_off": "0",
"entity_category": "diagnostic"
}
},
"rssi": {
"device_type": "sensor",
"object_suffix": "rssi",
"config": {
"device_class": "signal_strength",
"unit_of_measurement": "dB",
"value_template": "{{ value|float|round(2) }}",
"state_class": "measurement",
"entity_category": "diagnostic"
}
},
"snr": {
"device_type": "sensor",
"object_suffix": "snr",
"config": {
"device_class": "signal_strength",
"unit_of_measurement": "dB",
"value_template": "{{ value|float|round(2) }}",
"state_class": "measurement",
"entity_category": "diagnostic"
}
},
"noise": {
"device_type": "sensor",
"object_suffix": "noise",
"config": {
"device_class": "signal_strength",
"unit_of_measurement": "dB",
"value_template": "{{ value|float|round(2) }}",
"state_class": "measurement",
"entity_category": "diagnostic"
}
},
"depth_cm": {
"device_type": "sensor",
"object_suffix": "D",
"config": {
"name": "Depth",
"unit_of_measurement": "cm",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"power_W": {
"device_type": "sensor",
"object_suffix": "watts",
"config": {
"device_class": "power",
"name": "Power",
"unit_of_measurement": "W",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"energy_kWh": {
"device_type": "sensor",
"object_suffix": "kwh",
"config": {
"device_class": "energy",
"name": "Energy",
"unit_of_measurement": "kWh",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"current_A": {
"device_type": "sensor",
"object_suffix": "A",
"config": {
"device_class": "current",
"name": "Current",
"unit_of_measurement": "A",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"voltage_V": {
"device_type": "sensor",
"object_suffix": "V",
"config": {
"device_class": "voltage",
"name": "Voltage",
"unit_of_measurement": "V",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
"light_lux": {
"device_type": "sensor",
"object_suffix": "lux",
"config": {
"device_class": "illuminance",
"name": "Outside Luminance",
"unit_of_measurement": "lx",
"value_template": "{{ value|int }}",
"state_class": "measurement"
}
},
"lux": {
"device_type": "sensor",
"object_suffix": "lux",
"config": {
"device_class": "illuminance",
"name": "Outside Luminance",
"unit_of_measurement": "lx",
"value_template": "{{ value|int }}",
"state_class": "measurement"
}
},
"uv": {
"device_type": "sensor",
"object_suffix": "uv",
"config": {
"name": "UV Index",
"unit_of_measurement": "UV Index",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"uvi": {
"device_type": "sensor",
"object_suffix": "uvi",
"config": {
"name": "UV Index",
"unit_of_measurement": "UV Index",
"value_template": "{{ value|float|round(1) }}",
"state_class": "measurement"
}
},
"storm_dist_km": {
"device_type": "sensor",
"object_suffix": "stdist",
"config": {
"name": "Lightning Distance",
"unit_of_measurement": "km",
"value_template": "{{ value|int }}",
"state_class": "measurement"
}
},
"storm_dist": {
"device_type": "sensor",
"object_suffix": "stdist",
"config": {
"name": "Lightning Distance",
"unit_of_measurement": "mi",
"value_template": "{{ value|int }}",
"state_class": "measurement"
}
},
"strike_distance": {
"device_type": "sensor",
"object_suffix": "stdist",
"config": {
"name": "Lightning Distance",
"unit_of_measurement": "mi",
"value_template": "{{ value|int }}",
"state_class": "measurement"
}
},
"strike_count": {
"device_type": "sensor",
"object_suffix": "strcnt",
"config": {
"name": "Lightning Strike Count",
"value_template": "{{ value|int }}",
"state_class": "total_increasing"
}
},
"consumption_data": {
"device_type": "sensor",
"object_suffix": "consumption",
"config": {
"name": "SCM Consumption Value",
"value_template": "{{ value|int }}",
"state_class": "total_increasing",
}
},
"consumption": {
"device_type": "sensor",
"object_suffix": "consumption",
"config": {
"name": "SCMplus Consumption Value",
"value_template": "{{ value|int }}",
"state_class": "total_increasing",
}
},
"channel": {
"device_type": "device_automation",
"object_suffix": "CH",
"config": {
"automation_type": "trigger",
"type": "button_short_release",
"subtype": "button_1",
}
},
"button": {
"device_type": "device_automation",
"object_suffix": "BTN",
"config": {
"automation_type": "trigger",
"type": "button_short_release",
"subtype": "button_2",
}
},
# WH45, WH290
"pm2_5_ug_m3": {
"device_type": "sensor",
"object_suffix": "PM25",
"config": {
"device_class": "pm25",
"name": "PM 2.5 Concentration",
"unit_of_measurement": "µg/m³",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
# WH45
"pm10_ug_m3": {
"device_type": "sensor",
"object_suffix": "PM10",
"config": {
"device_class": "pm10",
"name": "PM 10 Concentration",
"unit_of_measurement": "µg/m³",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
# WH290
"estimated_pm10_0_ug_m3": {
"device_type": "sensor",
"object_suffix": "PM10",
"config": {
"device_class": "pm10",
"name": "Estimated PM 10 Concentration",
"unit_of_measurement": "µg/m³",
"value_template": "{{ value|float }}",
"state_class": "measurement"
}
},
# WH45
"co2_ppm": {
"device_type": "sensor",
"object_suffix": "CO2",
"config": {
"device_class": "carbon_dioxide",
"name": "CO2 Concentration",
"unit_of_measurement": "ppm",
"value_template": "{{ value|int }}",
"state_class": "measurement"
}
},
"ext_power": {
"device_type": "binary_sensor",
"object_suffix": "extpwr",
"config": {
"device_class": "power",
"name": "External Power",
"payload_on": "1",
"payload_off": "0",
"entity_category": "diagnostic"
}
},
}
# Use secret_knock to trigger device automations for Honeywell ActivLink
# doorbells. We have this outside of mappings as we need to configure two
# different configuration topics.
secret_knock_mappings = [
{
"device_type": "device_automation",
"object_suffix": "Knock",
"config": {
"automation_type": "trigger",
"type": "button_short_release",
"subtype": "button_1",
"payload": 0,
}
},
{
"device_type": "device_automation",
"object_suffix": "Secret-Knock",
"config": {
"automation_type": "trigger",
"type": "button_triple_press",
"subtype": "button_1",
"payload": 1,
}
},
]
TOPIC_PARSE_RE = re.compile(r'\[(?P<slash>/?)(?P<token>[^\]:]+):?(?P<default>[^\]:]*)\]')
def mqtt_connect(client, userdata, flags, rc):
"""Callback for MQTT connects."""
logging.info("MQTT connected: " + mqtt.connack_string(rc))
if rc != 0:
logging.error("Could not connect. Error: " + str(rc))
else:
logging.info("Subscribing to: " + args.rtl_topic)
client.subscribe(args.rtl_topic)
def mqtt_disconnect(client, userdata, rc):
"""Callback for MQTT disconnects."""
logging.info("MQTT disconnected: " + mqtt.connack_string(rc))
def mqtt_message(client, userdata, msg):
"""Callback for MQTT message PUBLISH."""
logging.debug("MQTT message: " + json.dumps(msg.payload.decode()))
try:
# Decode JSON payload
data = json.loads(msg.payload.decode())
except json.decoder.JSONDecodeError:
logging.error("JSON decode error: " + msg.payload.decode())
return
topicprefix = "/".join(msg.topic.split("/", 2)[:2])
bridge_event_to_hass(client, topicprefix, data)
def sanitize(text):
"""Sanitize a name for Graphite/MQTT use."""
return (text
.replace(" ", "_")
.replace("/", "_")
.replace(".", "_")
.replace("&", ""))
def rtl_433_device_info(data, topic_prefix):
"""Return rtl_433 device topic to subscribe to for a data element, based on the
rtl_433 device topic argument, as well as the device identifier"""
path_elements = []
id_elements = []
last_match_end = 0
# The default for args.device_topic_suffix is the same topic structure
# as set by default in rtl433 config
for match in re.finditer(TOPIC_PARSE_RE, args.device_topic_suffix):
path_elements.append(args.device_topic_suffix[last_match_end:match.start()])
key = match.group(2)
if key in data:
# If we have this key, prepend a slash if needed
if match.group(1):
path_elements.append('/')
element = sanitize(str(data[key]))
path_elements.append(element)
id_elements.append(element)
elif match.group(3):
path_elements.append(match.group(3))
last_match_end = match.end()
path = ''.join(list(filter(lambda item: item, path_elements)))
id = '-'.join(id_elements)
return (f"{topic_prefix}/{path}", id)
def publish_config(mqttc, topic, model, object_id, mapping, key=None):
"""Publish Home Assistant auto discovery data."""
global discovery_timeouts
device_type = mapping["device_type"]
object_suffix = mapping["object_suffix"]
object_name = "-".join([object_id, object_suffix])
path = "/".join([args.discovery_prefix, device_type, object_id, object_name, "config"])
# check timeout
now = time.time()
if path in discovery_timeouts:
if discovery_timeouts[path] > now:
logging.debug("Discovery timeout in the future for: " + path)
return False
discovery_timeouts[path] = now + args.discovery_interval
config = mapping["config"].copy()
# Device Automation configuration is in a different structure compared to
# all other mqtt discovery types.
# https://www.home-assistant.io/integrations/device_trigger.mqtt/
if device_type == 'device_automation':
config["topic"] = topic
config["platform"] = 'mqtt'
else:
readable_name = mapping["config"]["name"] if "name" in mapping["config"] else key
config["state_topic"] = topic
config["unique_id"] = object_name
config["name"] = readable_name
config["device"] = { "identifiers": [object_id], "name": object_id, "model": model, "manufacturer": "rtl_433" }
if args.force_update:
config["force_update"] = "true"
if args.expire_after:
config["expire_after"] = args.expire_after
logging.debug(path + ":" + json.dumps(config))
mqttc.publish(path, json.dumps(config), retain=args.retain)
return True
def bridge_event_to_hass(mqttc, topic_prefix, data):
"""Translate some rtl_433 sensor data to Home Assistant auto discovery."""
if "model" not in data:
# not a device event
logging.debug("Model is not defined. Not sending event to Home Assistant.")
return
model = sanitize(data["model"])
skipped_keys = []
published_keys = []
base_topic, device_id = rtl_433_device_info(data, topic_prefix)
if not device_id:
# no unique device identifier
logging.warning("No suitable identifier found for model: %s", model)
return
if args.ids and "id" in data and data.get("id") not in args.ids:
# not in the safe list
logging.debug("Device (%s) is not in the desired list of device ids: [%s]" % (data["id"], ids))
return
# detect known attributes
for key in data.keys():
if key in mappings:
# topic = "/".join([topicprefix,"devices",model,instance,key])
topic = "/".join([base_topic, key])
if publish_config(mqttc, topic, model, device_id, mappings[key], key):