-
Notifications
You must be signed in to change notification settings - Fork 4
/
entity-builder.py
533 lines (490 loc) · 17.2 KB
/
entity-builder.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
from meshtastic.serial_interface import SerialInterface
from meshtastic.tcp_interface import TCPInterface
from meshtastic.ble_interface import BLEInterface
import argparse
import sys
### Add arguments to parse
parser = argparse.ArgumentParser(
add_help=False,
epilog="If no connection arguments are specified, we attempt a serial connection and then a TCP connection to localhost.")
helpGroup = parser.add_argument_group("Help")
helpGroup.add_argument("-h", "--help", action="help", help="Show this help message and exit.")
connOuter = parser.add_argument_group('Connection', 'Optional arguments to specify a device to connect to and how.')
conn = connOuter.add_mutually_exclusive_group()
conn.add_argument(
"--port",
help="The port to connect to via serial, e.g. `/dev/ttyUSB0`.",
default=None,
)
conn.add_argument(
"--host",
help="The hostname or IP address to connect to using TCP.",
default=None,
)
conn.add_argument(
"--ble",
help="The BLE device MAC address or name to connect to.",
default=None,
)
mqtt = parser.add_argument_group("MQTT", "Arguments to specify the gateway node and root MQTT topics")
mqtt.add_argument(
"--gateway",
help="The ID of the MQTT gateway node, e.g. !12345678. If not provided, will use the ID of the locally connected node.",
default=None,
)
# it would be nice to have this request settings if the gateway isn't the remote node
mqtt.add_argument(
"--root-topic",
help="The root topic to use in MQTT for the generated files. If not provided, will attempt to get the root path from the local node and use all channels. Wildcard: `+`. Example: to include all channels with the root topic `msh/`, use `msh/2/json/+`. To include just LongFast, use `msh/2/json/LongFast`",
default=None,
)
includes = parser.add_argument_group("Includes", "Arguments to specify what sensors to generate for each node.")
includes.add_argument(
"--no-messages",
help="Don't include a sensor for messages from the node.",
action='store_true',
)
includes.add_argument(
"--fahrenheit",
help="Use Fahrenheit instead of Celsius.",
action='store_true',
)
includes.add_argument(
"--no-temperature",
help="Don't include a temperature sensor.",
action='store_true',
)
includes.add_argument(
"--no-humidity",
help="Don't include a humidity sensor.",
action='store_true',
)
includes.add_argument(
"--no-pressure",
help="Don't include a barometric pressure sensor.",
action='store_true',
)
includes.add_argument(
"--gas-resistance",
help="Include a gas resistance sensor.",
action='store_true',
)
includes.add_argument(
"--power-ch1",
help="Include current & voltage channel 1 sensor.",
action='store_true',
)
includes.add_argument(
"--power-ch2",
help="Include current & voltage channel 2 sensor.",
action='store_true',
)
includes.add_argument(
"--power-ch3",
help="Include current & voltage channel 3 sensor.",
action='store_true',
)
parser.add_argument(
"--nodes",
help="Only generate sensors for these nodes. If not provided, all nodes in the NodeDB will be included. Example: `\"!XXXXXXXX\", \"!YYYYYYYY\"`.",
nargs='*',
action='store',
)
args = parser.parse_args()
### Create an interface
if args.ble:
iface = BLEInterface(args.ble)
elif args.host:
iface = TCPInterface(args.host)
else:
try:
iface = SerialInterface(args.port)
except PermissionError as ex:
print("You probably need to add yourself to the `dialout` group to use a serial connection.")
if iface.devPath is None:
iface = TCPInterface("localhost")
if args.gateway:
gateway_id = args.gateway
else:
gateway_id = f"!{iface.localNode.nodeNum:08x}"
if args.root_topic:
root_topic = args.root_topic
else:
mqttRoot = iface.localNode.moduleConfig.mqtt.root
if mqttRoot != "":
root_topic = mqttRoot + '/2/json/+'
print(f"Using a gateway ID of {gateway_id} and a root topic of {root_topic}")
node_list = []
use_node_list = False # only use nodes from the node list. If False, create for all nodes in db.
if args.nodes and len(args.nodes) > 0:
use_node_list = True
node_list = args.nodes
print(f"Using node list: {node_list}")
fahrenheit = args.fahrenheit
include_messages = not args.no_messages
include_temperature = not args.no_temperature
include_humidity = not args.no_humidity
include_pressure = not args.no_pressure
include_gas_resistance = args.gas_resistance
include_power_ch1 = args.power_ch1
include_power_ch2 = args.power_ch2
include_power_ch3 = args.power_ch3
# initialize the file with the 'sensor' header
with open("mqtt.yaml", "w", encoding="utf-8") as file:
file.write('sensor:\n')
# initialize the file as empty so we have something to append to
with open("automations.yaml", "w", encoding="utf-8") as file:
file.write('')
for node_num, node in iface.nodes.items():
node_short_name = f"{node['user']['shortName']}"
node_long_name = f"{node['user']['longName']}"
node_id = f"{node['user']['id']}"
node_num = f"{node['num']}"
hardware_model = f"{node['user']['hwModel']}"
automation_config = f"""
- id: 'update_location_{node_num}'
alias: update {node_id} location
trigger:
- platform: mqtt
topic: "{root_topic}/{gateway_id}"
payload: 'on'
value_template: >-
{{%- if value_json.from == {node_num} and
value_json.payload.latitude_i is defined and
value_json.payload.longitude_i is defined -%}}
on
{{%- endif -%}}
condition: []
action:
- service: device_tracker.see
metadata: {{}}
data:
dev_id: "{int(node_num):08x}"
gps:
- '{{{{ (trigger.payload | from_json).payload.latitude_i | int * 1e-7 }}}}'
- '{{{{ (trigger.payload | from_json).payload.longitude_i | int * 1e-7 }}}}'
mode: single
"""
config = f'''
- name: "{node_short_name} Last Heard"
unique_id: "{int(node_num):08x}_last_heard"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
device_class: timestamp
value_template: >-
{{% if value_json.from == {node_num} and
value_json.timestamp is defined %}}
{{{{ as_datetime(value_json.timestamp) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
device:
name: "{node_long_name}"
model: "{hardware_model}"
identifiers:
- "meshtastic_{node_num}"
- name: "{node_short_name} SNR"
unique_id: "{int(node_num):08x}_snr"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
device_class: signal_strength
value_template: >-
{{% if value_json.from == {node_num} and value_json.snr is defined %}}
{{{{ value_json.snr}}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
icon: "mdi:signal"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} RSSI"
unique_id: "{int(node_num):08x}_rssi"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
device_class: signal_strength
value_template: >-
{{% if value_json.from == {node_num} and value_json.rssi is defined %}}
{{{{ value_json.rssi | int}}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
icon: "mdi:signal-variant"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Hops Away"
unique_id: "{int(node_num):08x}_hops_away"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
device_class: distance
value_template: >-
{{% if value_json.from == {node_num} and value_json.hops_away is defined %}}
{{{{ value_json.hops_away | int }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
icon: "mdi:rabbit"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Battery Voltage"
unique_id: "{int(node_num):08x}_battery_voltage"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and
value_json.payload.voltage is defined and
value_json.payload.temperature is not defined %}}
{{{{ (value_json.payload.voltage | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "V"
icon: "mdi:lightning-bolt"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Battery Percent"
unique_id: "{int(node_num):08x}_battery_percent"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.battery_level is defined %}}
{{{{ (value_json.payload.battery_level | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
device_class: battery
unit_of_measurement: "%"
icon: "mdi:battery-high"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Uptime"
unique_id: "{int(node_num):08x}_uptime"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
device_class: duration
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.uptime_seconds is defined %}}
{{{{ value_json.payload.uptime_seconds | int }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "s"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} ChUtil"
unique_id: "{int(node_num):08x}_chutil"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.channel_utilization is defined %}}
{{{{ (value_json.payload.channel_utilization | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "%"
icon: "mdi:signal-distance-variant"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} AirUtilTX"
unique_id: "{int(node_num):08x}_airutiltx"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.air_util_tx is defined %}}
{{{{ (value_json.payload.air_util_tx | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "%"
icon: "mdi:percent-box-outline"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_messages:
config += f'''
- name: "{node_short_name} Messages"
unique_id: "{int(node_num):08x}_messages"
state_topic: "{root_topic}/{gateway_id}"
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.text is defined %}}
{{{{ value_json.payload.text }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
device:
identifiers: "meshtastic_{node_num}"
icon: "mdi:chat"
'''
if include_temperature:
if fahrenheit:
temp_mod = "* 1.8) +32"
temp_unit = "F"
else:
temp_mod = ")"
temp_unit = "C"
config += f'''
- name: "{node_short_name} Temperature"
unique_id: "{int(node_num):08x}_temperature"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.temperature is defined %}}
{{{{ (((value_json.payload.temperature | float) {temp_mod}) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "{temp_unit}"
icon: "mdi:sun-thermometer"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_humidity:
config += f'''
- name: "{node_short_name} Humidity"
unique_id: "{int(node_num):08x}_humidity"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.relative_humidity is defined %}}
{{{{ (value_json.payload.relative_humidity | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "%"
icon: "mdi:water-percent"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_pressure:
config += f'''
- name: "{node_short_name} Barometric Pressure"
unique_id: "{int(node_num):08x}_pressure"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.barometric_pressure is defined %}}
{{{{ (value_json.payload.barometric_pressure | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "hPa"
icon: "mdi:chevron-double-down"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_gas_resistance:
config += f'''
- name: "{node_short_name} Gas Resistance"
unique_id: "{int(node_num):08x}_gas_resistance"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.gas_resistance is defined %}}
{{{{ (value_json.payload.gas_resistance | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "MOhms"
icon: "mdi:dots-hexagon"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_power_ch1:
config += f'''
# {node_long_name}
- name: "{node_short_name} Voltage Sensor Ch1"
unique_id: "{int(node_num):08x}_voltage_sensor_ch1"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.voltage_ch1 is defined %}}
{{{{ (value_json.payload.voltage_ch1 | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "V"
icon: "mdi:lightning-bolt"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Current Sensor Ch1"
unique_id: "{int(node_num):08x}_current_sensor_ch1"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.current_ch1 is defined %}}
{{{{ (value_json.payload.current_ch1 | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "mA"
icon: "mdi:waves"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_power_ch2:
config += f'''
- name: "{node_short_name} Voltage Sensor Ch2"
unique_id: "{int(node_num):08x}_voltage_sensor_ch2"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.voltage_ch2 is defined %}}
{{{{ (value_json.payload.voltage_ch2 | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "V"
icon: "mdi:lightning-bolt"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Current Sensor Ch2"
unique_id: "{int(node_num):08x}_current_sensor_ch2"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.current_ch2 is defined %}}
{{{{ (value_json.payload.current_ch2 | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "mA"
icon: "mdi:waves"
device:
identifiers: "meshtastic_{node_num}"
'''
if include_power_ch3:
config += f'''
- name: "{node_short_name} Voltage Sensor Ch3"
unique_id: "{int(node_num):08x}_voltage_sensor_ch3"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.voltage_ch3 is defined %}}
{{{{ (value_json.payload.voltage_ch3 | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "V"
icon: "mdi:lightning-bolt"
device:
identifiers: "meshtastic_{node_num}"
- name: "{node_short_name} Current Sensor Ch3"
unique_id: "{int(node_num):08x}_current_sensor_ch3"
state_topic: "{root_topic}/{gateway_id}"
state_class: measurement
value_template: >-
{{% if value_json.from == {node_num} and value_json.payload.current_ch3 is defined %}}
{{{{ (value_json.payload.current_ch3 | float) | round(2) }}}}
{{% else %}}
{{{{ this.state }}}}
{{% endif %}}
unit_of_measurement: "mA"
icon: "mdi:waves"
device:
identifiers: "meshtastic_{node_num}"
'''
if node_id in node_list or (not use_node_list):
with open("mqtt.yaml", "a", encoding="utf-8") as file:
file.write(config + '\n')
with open("automations.yaml", "a", encoding="utf-8") as file:
file.write(automation_config)
iface.close()