forked from ironsheep/RPi-Reporter-MQTT2HA-Daemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ISP-RPi-mqtt-daemon.py
executable file
·1492 lines (1277 loc) · 53.3 KB
/
ISP-RPi-mqtt-daemon.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 -*-
import _thread
from datetime import datetime, timedelta
from tzlocal import get_localzone
import threading
import socket
import os
import subprocess
import uuid
import ssl
import sys
import re
import json
import os.path
import argparse
from time import time, sleep, localtime, strftime
from collections import OrderedDict
from colorama import init as colorama_init
from colorama import Fore, Back, Style
from configparser import ConfigParser
from unidecode import unidecode
import paho.mqtt.client as mqtt
import sdnotify
from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE, SIG_DFL)
script_version = "1.6.1"
script_name = 'ISP-RPi-mqtt-daemon.py'
script_info = '{} v{}'.format(script_name, script_version)
project_name = 'RPi Reporter MQTT2HA Daemon'
project_url = 'https://github.com/ironsheep/RPi-Reporter-MQTT2HA-Daemon'
# we'll use this throughout
local_tz = get_localzone()
# TODO:
# - add announcement of free-space and temperatore endpoints
if False:
# will be caught by python 2.7 to be illegal syntax
print_line(
'Sorry, this script requires a python3 runtime environment.', file=sys.stderr)
os._exit(1)
# Argparse
opt_debug = False
opt_verbose = False
# Systemd Service Notifications - https://github.com/bb4242/sdnotify
sd_notifier = sdnotify.SystemdNotifier()
# Logging function
def print_line(text, error=False, warning=False, info=False, verbose=False, debug=False, console=True, sd_notify=False):
timestamp = strftime('%Y-%m-%d %H:%M:%S', localtime())
if console:
if error:
print(Fore.RED + Style.BRIGHT + '[{}] '.format(
timestamp) + Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL, file=sys.stderr)
elif warning:
print(Fore.YELLOW + '[{}] '.format(timestamp) +
Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL)
elif info or verbose:
if opt_verbose:
print(Fore.GREEN + '[{}] '.format(timestamp) +
Fore.YELLOW + '- ' + '{}'.format(text) + Style.RESET_ALL)
elif debug:
if opt_debug:
print(Fore.CYAN + '[{}] '.format(timestamp) +
'- (DBG): ' + '{}'.format(text) + Style.RESET_ALL)
else:
print(Fore.GREEN + '[{}] '.format(timestamp) +
Style.RESET_ALL + '{}'.format(text) + Style.RESET_ALL)
timestamp_sd = strftime('%b %d %H:%M:%S', localtime())
if sd_notify:
sd_notifier.notify(
'STATUS={} - {}.'.format(timestamp_sd, unidecode(text)))
# Identifier cleanup
def clean_identifier(name):
clean = name.strip()
for this, that in [[' ', '-'], ['ä', 'ae'], ['Ä', 'Ae'], ['ö', 'oe'], ['Ö', 'Oe'], ['ü', 'ue'], ['Ü', 'Ue'], ['ß', 'ss']]:
clean = clean.replace(this, that)
clean = unidecode(clean)
return clean
# Argparse
parser = argparse.ArgumentParser(
description=project_name, epilog='For further details see: ' + project_url)
parser.add_argument("-v", "--verbose",
help="increase output verbosity", action="store_true")
parser.add_argument(
"-d", "--debug", help="show debug output", action="store_true")
parser.add_argument(
"-s", "--stall", help="TEST: report only the first time", action="store_true")
parser.add_argument("-c", '--config_dir',
help='set directory where config.ini is located', default=sys.path[0])
parse_args = parser.parse_args()
config_dir = parse_args.config_dir
opt_debug = parse_args.debug
opt_verbose = parse_args.verbose
opt_stall = parse_args.stall
print_line(script_info, info=True)
if opt_verbose:
print_line('Verbose enabled', info=True)
if opt_debug:
print_line('Debug enabled', debug=True)
if opt_stall:
print_line('TEST: Stall (no-re-reporting) enabled', debug=True)
# -----------------------------------------------------------------------------
# MQTT handlers
# -----------------------------------------------------------------------------
# Eclipse Paho callbacks - http://www.eclipse.org/paho/clients/python/docs/#callbacks
mqtt_client_connected = False
print_line(
'* init mqtt_client_connected=[{}]'.format(mqtt_client_connected), debug=True)
mqtt_client_should_attempt_reconnect = True
def on_connect(client, userdata, flags, rc):
global mqtt_client_connected
if rc == 0:
print_line('* MQTT connection established',
console=True, sd_notify=True)
print_line('') # blank line?!
#_thread.start_new_thread(afterMQTTConnect, ())
mqtt_client_connected = True
print_line('on_connect() mqtt_client_connected=[{}]'.format(
mqtt_client_connected), debug=True)
else:
print_line('! Connection error with result code {} - {}'.format(str(rc),
mqtt.connack_string(rc)), error=True)
print_line('MQTT Connection error with result code {} - {}'.format(str(rc),
mqtt.connack_string(rc)), error=True, sd_notify=True)
# technically NOT useful but readying possible new shape...
mqtt_client_connected = False
print_line('on_connect() mqtt_client_connected=[{}]'.format(
mqtt_client_connected), debug=True, error=True)
# kill main thread
os._exit(1)
def on_publish(client, userdata, mid):
#print_line('* Data successfully published.')
pass
# Load configuration file
config = ConfigParser(delimiters=(
'=', ), inline_comment_prefixes=('#'), interpolation=None)
config.optionxform = str
try:
with open(os.path.join(config_dir, 'config.ini')) as config_file:
config.read_file(config_file)
except IOError:
print_line('No configuration file "config.ini"',
error=True, sd_notify=True)
sys.exit(1)
daemon_enabled = config['Daemon'].getboolean('enabled', True)
# This script uses a flag file containing a date/timestamp of when the system was last updated
default_update_flag_filespec = '/home/pi/bin/lastupd.date'
update_flag_filespec = config['Daemon'].get(
'update_flag_filespec', default_update_flag_filespec)
default_base_topic = 'home/nodes'
base_topic = config['MQTT'].get('base_topic', default_base_topic).lower()
default_sensor_name = 'rpi-reporter'
sensor_name = config['MQTT'].get('sensor_name', default_sensor_name).lower()
# by default Home Assistant listens to the /homeassistant but it can be changed for a given installation
default_discovery_prefix = 'homeassistant'
discovery_prefix = config['MQTT'].get(
'discovery_prefix', default_discovery_prefix).lower()
# report our RPi values every 5min
min_interval_in_minutes = 1
max_interval_in_minutes = 30
default_interval_in_minutes = 5
interval_in_minutes = config['Daemon'].getint(
'interval_in_minutes', default_interval_in_minutes)
# default domain when hostname -f doesn't return it
default_domain = ''
fallback_domain = config['Daemon'].get(
'fallback_domain', default_domain).lower()
# Check configuration
#
if (interval_in_minutes < min_interval_in_minutes) or (interval_in_minutes > max_interval_in_minutes):
print_line('ERROR: Invalid "interval_in_minutes" found in configuration file: "config.ini"! Must be [{}-{}] Fix and try again... Aborting'.format(
min_interval_in_minutes, max_interval_in_minutes), error=True, sd_notify=True)
sys.exit(1)
# Ensure required values within sections of our config are present
if not config['MQTT']:
print_line('ERROR: No MQTT settings found in configuration file "config.ini"! Fix and try again... Aborting',
error=True, sd_notify=True)
sys.exit(1)
print_line('Configuration accepted', console=False, sd_notify=True)
# -----------------------------------------------------------------------------
# RPi variables monitored
# -----------------------------------------------------------------------------
rpi_mac = ''
rpi_model_raw = ''
rpi_model = ''
rpi_connections = ''
rpi_hostname = ''
rpi_fqdn = ''
rpi_linux_release = ''
rpi_linux_version = ''
rpi_uptime_raw = ''
rpi_uptime = ''
rpi_last_update_date = datetime.min
#rpi_last_update_date_v2 = datetime.min
rpi_filesystem_space_raw = ''
rpi_filesystem_space = ''
rpi_filesystem_percent = ''
rpi_system_temp = ''
rpi_gpu_temp = ''
rpi_cpu_temp = ''
rpi_mqtt_script = script_info
rpi_interfaces = []
rpi_filesystem = []
# Tuple (Total, Free, Avail.)
rpi_memory_tuple = ''
# Tuple (Hardware, Model Name, NbrCores, BogoMIPS, Serial)
rpi_cpu_tuple = ''
# for thermal status reporting
rpi_throttle_status = []
# new cpu loads
rpi_cpuload1 = ''
rpi_cpuload5 = ''
rpi_cpuload15 = ''
# -----------------------------------------------------------------------------
# monitor variable fetch routines
#
def getDeviceCpuInfo():
global rpi_cpu_tuple
# cat /proc/cpuinfo | /bin/egrep -i "processor|model|bogo|hardware|serial"
# MULTI-CORE
# processor : 0
# model name : ARMv7 Processor rev 4 (v7l)
# BogoMIPS : 38.40
# processor : 1
# model name : ARMv7 Processor rev 4 (v7l)
# BogoMIPS : 38.40
# processor : 2
# model name : ARMv7 Processor rev 4 (v7l)
# BogoMIPS : 38.40
# processor : 3
# model name : ARMv7 Processor rev 4 (v7l)
# BogoMIPS : 38.40
# Hardware : BCM2835
# Serial : 00000000a8d11642
#
# SINGLE CORE
# processor : 0
# model name : ARMv6-compatible processor rev 7 (v6l)
# BogoMIPS : 697.95
# Hardware : BCM2835
# Serial : 00000000131030c0
# Model : Raspberry Pi Zero W Rev 1.1
out = subprocess.Popen("cat /proc/cpuinfo | /bin/egrep -i 'processor|model|bogo|hardware|serial'",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
trimmedLines = []
for currLine in lines:
trimmedLine = currLine.lstrip().rstrip()
trimmedLines.append(trimmedLine)
cpu_hardware = '' # 'hardware'
cpu_cores = 0 # count of 'processor' lines
cpu_model = '' # 'model name'
cpu_bogoMIPS = 0.0 # sum of 'BogoMIPS' lines
cpu_serial = '' # 'serial'
for currLine in trimmedLines:
lineParts = currLine.split(':')
currValue = '{?unk?}'
if len(lineParts) >= 2:
currValue = lineParts[1].lstrip().rstrip()
if 'Hardware' in currLine:
cpu_hardware = currValue
if 'model name' in currLine:
cpu_model = currValue
if 'BogoMIPS' in currLine:
cpu_bogoMIPS += float(currValue)
if 'processor' in currLine:
cpu_cores += 1
if 'Serial' in currLine:
cpu_serial = currValue
out = subprocess.Popen("/bin/cat /proc/loadavg",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
cpu_loads_raw = stdout.decode('utf-8').split()
print_line('cpu_loads_raw=[{}]'.format(cpu_loads_raw), debug=True)
cpu_load1 = round(float(float(cpu_loads_raw[0]) / int(cpu_cores) * 100), 1)
cpu_load5 = round(float(float(cpu_loads_raw[1]) / int(cpu_cores) * 100), 1)
cpu_load15 = round(float(float(cpu_loads_raw[2]) / int(cpu_cores) * 100), 1)
# Tuple (Hardware, Model Name, NbrCores, BogoMIPS, Serial)
rpi_cpu_tuple = (cpu_hardware, cpu_model, cpu_cores,
cpu_bogoMIPS, cpu_serial, cpu_load1, cpu_load5, cpu_load15)
print_line('rpi_cpu_tuple=[{}]'.format(rpi_cpu_tuple), debug=True)
def getDeviceMemory():
global rpi_memory_tuple
# $ cat /proc/meminfo | /bin/egrep -i "mem[TFA]"
# MemTotal: 948304 kB
# MemFree: 40632 kB
# MemAvailable: 513332 kB
out = subprocess.Popen("cat /proc/meminfo | /bin/egrep -i 'mem[tfa]'",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
trimmedLines = []
for currLine in lines:
trimmedLine = currLine.lstrip().rstrip()
trimmedLines.append(trimmedLine)
mem_total = ''
mem_free = ''
mem_avail = ''
for currLine in trimmedLines:
lineParts = currLine.split()
if 'MemTotal' in currLine:
mem_total = float(lineParts[1]) / 1024
if 'MemFree' in currLine:
mem_free = float(lineParts[1]) / 1024
if 'MemAvail' in currLine:
mem_avail = float(lineParts[1]) / 1024
# Tuple (Total, Free, Avail.)
rpi_memory_tuple = (mem_total, mem_free, mem_avail)
print_line('rpi_memory_tuple=[{}]'.format(rpi_memory_tuple), debug=True)
def getDeviceModel():
global rpi_model
global rpi_model_raw
global rpi_connections
out = subprocess.Popen("/bin/cat /proc/device-tree/model | /bin/sed -e 's/\\x0//g'",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_model_raw = stdout.decode('utf-8')
# now reduce string length (just more compact, same info)
rpi_model = rpi_model_raw.replace('Raspberry ', 'R').replace(
'i Model ', 'i 1 Model').replace('Rev ', 'r').replace(' Plus ', '+')
# now decode interfaces
rpi_connections = 'e,w,b' # default
if 'Pi 3 ' in rpi_model:
if ' A ' in rpi_model:
rpi_connections = 'w,b'
else:
rpi_connections = 'e,w,b'
elif 'Pi 2 ' in rpi_model:
rpi_connections = 'e'
elif 'Pi 1 ' in rpi_model:
if ' A ' in rpi_model:
rpi_connections = ''
else:
rpi_connections = 'e'
print_line('rpi_model_raw=[{}]'.format(rpi_model_raw), debug=True)
print_line('rpi_model=[{}]'.format(rpi_model), debug=True)
print_line('rpi_connections=[{}]'.format(rpi_connections), debug=True)
def getLinuxRelease():
global rpi_linux_release
out = subprocess.Popen("/bin/cat /etc/os-release | /bin/egrep 'PRETTY_NAME' | /bin/sed -e 's/PRETTY_NAME=\"//'",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_linux_release = stdout.decode('utf-8').rstrip()[:-1]
print_line('rpi_linux_release=[{}]'.format(rpi_linux_release), debug=True)
def getLinuxVersion():
global rpi_linux_version
out = subprocess.Popen("/bin/uname -r",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_linux_version = stdout.decode('utf-8').rstrip()
print_line('rpi_linux_version=[{}]'.format(rpi_linux_version), debug=True)
def getHostnames():
global rpi_hostname
global rpi_fqdn
out = subprocess.Popen("/bin/hostname -f",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
fqdn_raw = stdout.decode('utf-8').rstrip()
print_line('fqdn_raw=[{}]'.format(fqdn_raw), debug=True)
rpi_hostname = fqdn_raw
if '.' in fqdn_raw:
# have good fqdn
nameParts = fqdn_raw.split('.')
rpi_fqdn = fqdn_raw
rpi_hostname = nameParts[0]
else:
# missing domain, if we have a fallback apply it
if len(fallback_domain) > 0:
rpi_fqdn = '{}.{}'.format(fqdn_raw, fallback_domain)
else:
rpi_fqdn = rpi_hostname
print_line('rpi_fqdn=[{}]'.format(rpi_fqdn), debug=True)
print_line('rpi_hostname=[{}]'.format(rpi_hostname), debug=True)
def getUptime():
global rpi_uptime_raw
global rpi_uptime
out = subprocess.Popen("/usr/bin/uptime",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_uptime_raw = stdout.decode('utf-8').rstrip().lstrip()
print_line('rpi_uptime_raw=[{}]'.format(rpi_uptime_raw), debug=True)
basicParts = rpi_uptime_raw.split()
timeStamp = basicParts[0]
lineParts = rpi_uptime_raw.split(',')
if('user' in lineParts[1]):
rpi_uptime_raw = lineParts[0]
else:
rpi_uptime_raw = '{}, {}'.format(lineParts[0], lineParts[1])
rpi_uptime = rpi_uptime_raw.replace(
timeStamp, '').lstrip().replace('up ', '')
print_line('rpi_uptime=[{}]'.format(rpi_uptime), debug=True)
def getNetworkIFsUsingIP(ip_cmd):
cmd_str = '{} link show | /bin/egrep -v "link" | /bin/egrep " eth| wlan"'.format(
ip_cmd)
out = subprocess.Popen(cmd_str,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
interfaceNames = []
line_count = len(lines)
if line_count > 2:
line_count = 2
if line_count == 0:
print_line('ERROR no lines left by ip(8) filter!', error=True)
sys.exit(1)
for lineIdx in range(line_count):
trimmedLine = lines[lineIdx].lstrip().rstrip()
if len(trimmedLine) > 0:
lineParts = trimmedLine.split()
interfaceName = lineParts[1].replace(':', '')
interfaceNames.append(interfaceName)
print_line('interfaceNames=[{}]'.format(interfaceNames), debug=True)
trimmedLines = []
for interface in interfaceNames:
lines = getSingleInterfaceDetails(interface)
for currLine in lines:
trimmedLines.append(currLine)
loadNetworkIFDetailsFromLines(trimmedLines)
def getSingleInterfaceDetails(interfaceName):
cmdString = '/sbin/ifconfig {} | /bin/egrep "Link|flags|inet |ether " | /bin/egrep -v -i "lo:|loopback|inet6|\:\:1|127\.0\.0\.1"'.format(
interfaceName)
out = subprocess.Popen(cmdString,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
trimmedLines = []
for currLine in lines:
trimmedLine = currLine.lstrip().rstrip()
if len(trimmedLine) > 0:
trimmedLines.append(trimmedLine)
#print_line('interface:[{}] trimmedLines=[{}]'.format(interfaceName, trimmedLines), debug=True)
return trimmedLines
def loadNetworkIFDetailsFromLines(ifConfigLines):
global rpi_interfaces
global rpi_mac
#
# OLDER SYSTEMS
# eth0 Link encap:Ethernet HWaddr b8:27:eb:c8:81:f2
# inet addr:192.168.100.41 Bcast:192.168.100.255 Mask:255.255.255.0
# wlan0 Link encap:Ethernet HWaddr 00:0f:60:03:e6:dd
# NEWER SYSTEMS
# The following means eth0 (wired is NOT connected, and WiFi is connected)
# eth0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
# ether b8:27:eb:1a:f3:bc txqueuelen 1000 (Ethernet)
# wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
# inet 192.168.100.189 netmask 255.255.255.0 broadcast 192.168.100.255
# ether b8:27:eb:4f:a6:e9 txqueuelen 1000 (Ethernet)
#
tmpInterfaces = []
haveIF = False
imterfc = ''
rpi_mac = ''
for currLine in ifConfigLines:
lineParts = currLine.split()
#print_line('- currLine=[{}]'.format(currLine), debug=True)
#print_line('- lineParts=[{}]'.format(lineParts), debug=True)
if len(lineParts) > 0:
# skip interfaces generated by Home Assistant on RPi
if 'docker' in currLine or 'veth' in currLine or 'hassio' in currLine:
haveIF = False
continue
# let's evaluate remaining interfaces
if 'flags' in currLine: # NEWER ONLY
haveIF = True
imterfc = lineParts[0].replace(':', '')
#print_line('newIF=[{}]'.format(imterfc), debug=True)
elif 'Link' in currLine: # OLDER ONLY
haveIF = True
imterfc = lineParts[0].replace(':', '')
newTuple = (imterfc, 'mac', lineParts[4])
if rpi_mac == '':
rpi_mac = lineParts[4]
print_line('rpi_mac=[{}]'.format(rpi_mac), debug=True)
tmpInterfaces.append(newTuple)
print_line('newTuple=[{}]'.format(newTuple), debug=True)
elif haveIF == True:
print_line('IF=[{}], lineParts=[{}]'.format(
imterfc, lineParts), debug=True)
if 'inet' in currLine: # OLDER & NEWER
newTuple = (imterfc, 'IP',
lineParts[1].replace('addr:', ''))
tmpInterfaces.append(newTuple)
print_line('newTuple=[{}]'.format(newTuple), debug=True)
elif 'ether' in currLine: # NEWER ONLY
newTuple = (imterfc, 'mac', lineParts[1])
tmpInterfaces.append(newTuple)
if rpi_mac == '':
rpi_mac = lineParts[1]
print_line('rpi_mac=[{}]'.format(rpi_mac), debug=True)
print_line('newTuple=[{}]'.format(newTuple), debug=True)
haveIF = False
rpi_interfaces = tmpInterfaces
print_line('rpi_interfaces=[{}]'.format(rpi_interfaces), debug=True)
print_line('rpi_mac=[{}]'.format(rpi_mac), debug=True)
def getNetworkIFs():
ip_cmd = getIPCmd()
if ip_cmd != '':
getNetworkIFsUsingIP(ip_cmd)
else:
out = subprocess.Popen('/sbin/ifconfig | /bin/egrep "Link|flags|inet |ether " | /bin/egrep -v -i "lo:|loopback|inet6|\:\:1|127\.0\.0\.1"',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
trimmedLines = []
for currLine in lines:
trimmedLine = currLine.lstrip().rstrip()
if len(trimmedLine) > 0:
trimmedLines.append(trimmedLine)
print_line('trimmedLines=[{}]'.format(trimmedLines), debug=True)
loadNetworkIFDetailsFromLines(trimmedLines)
def getFileSystemDrives():
global rpi_filesystem_space_raw
global rpi_filesystem_space
global rpi_filesystem_percent
global rpi_filesystem
out = subprocess.Popen("/bin/df -m | /usr/bin/tail -n +2 | /bin/egrep -v 'tmpfs|boot'",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
trimmedLines = []
for currLine in lines:
trimmedLine = currLine.lstrip().rstrip()
if len(trimmedLine) > 0:
trimmedLines.append(trimmedLine)
print_line('getFileSystemDrives() trimmedLines=[{}]'.format(
trimmedLines), debug=True)
# EXAMPLES
#
# Filesystem 1M-blocks Used Available Use% Mounted on
# /dev/root 59998 9290 48208 17% /
# /dev/sda1 937872 177420 712743 20% /media/data
# or
# /dev/root 59647 3328 53847 6% /
# /dev/sda1 3703 25 3472 1% /media/pi/SANDISK
# or
# xxx.xxx.xxx.xxx:/srv/c2db7b94 200561 148655 41651 79% /
# FAILING Case v1.4.0:
# Here is the output of 'df -m'
# Sys. de fichiers blocs de 1M Utilisé Disponible Uti% Monté sur
# /dev/root 119774 41519 73358 37% /
# devtmpfs 1570 0 1570 0% /dev
# tmpfs 1699 0 1699 0% /dev/shm
# tmpfs 1699 33 1667 2% /run
# tmpfs 5 1 5 1% /run/lock
# tmpfs 1699 0 1699 0% /sys/fs/cgroup
# /dev/mmcblk0p1 253 55 198 22% /boot
# tmpfs 340 0 340 0% /run/user/1000
tmpDrives = []
for currLine in trimmedLines:
lineParts = currLine.split()
print_line('lineParts({})=[{}]'.format(
len(lineParts), lineParts), debug=True)
if len(lineParts) < 6:
print_line('BAD LINE FORMAT, Skipped=[{}]'.format(
lineParts), debug=True, warning=True)
continue
# tuple { total blocks, used%, mountPoint, device }
#
# new mech:
# Filesystem 1M-blocks Used Available Use% Mounted on
# [0] [1] [2] [3] [4] [5]
# [--] [n-3] [n-2] [n-1] [n] [--]
# where percent_field_index is 'n'
#
# locate our % used field...
for percent_field_index in range(len(lineParts) - 2, 1, -1):
if '%' in lineParts[percent_field_index]:
break
print_line('percent_field_index=[{}]'.format(
percent_field_index), debug=True)
total_size_idx = percent_field_index - 3
mount_idx = percent_field_index + 1
# do we have a two part device name?
device = lineParts[0]
if total_size_idx != 1:
device = '{} {}'.format(lineParts[0], lineParts[1])
print_line('device=[{}]'.format(device), debug=True)
# do we have a two part mount point?
mount_point = lineParts[mount_idx]
if len(lineParts) - 1 > mount_idx:
mount_point = '{} {}'.format(
lineParts[mount_idx], lineParts[mount_idx + 1])
print_line('mount_point=[{}]'.format(mount_point), debug=True)
total_size_in_gb = '{:.0f}'.format(
next_power_of_2(lineParts[total_size_idx]))
newTuple = (total_size_in_gb, lineParts[percent_field_index].replace(
'%', ''), mount_point, device)
tmpDrives.append(newTuple)
print_line('newTuple=[{}]'.format(newTuple), debug=True)
if newTuple[2] == '/':
rpi_filesystem_space_raw = currLine
rpi_filesystem_space = newTuple[0]
rpi_filesystem_percent = newTuple[1]
print_line('rpi_filesystem_space=[{}GB]'.format(
newTuple[0]), debug=True)
print_line('rpi_filesystem_percent=[{}]'.format(
newTuple[1]), debug=True)
rpi_filesystem = tmpDrives
print_line('rpi_filesystem=[{}]'.format(rpi_filesystem), debug=True)
def next_power_of_2(size):
size_as_nbr = int(size) - 1
return 1 if size == 0 else (1 << size_as_nbr.bit_length()) / 1024
def getVcGenCmd():
cmd_locn1 = '/usr/bin/vcgencmd'
cmd_locn2 = '/opt/vc/bin/vcgencmd'
desiredCommand = cmd_locn1
if os.path.exists(desiredCommand) == False:
desiredCommand = cmd_locn2
if os.path.exists(desiredCommand) == False:
desiredCommand = ''
if desiredCommand != '':
print_line('Found vcgencmd(1)=[{}]'.format(desiredCommand), debug=True)
return desiredCommand
def getIPCmd():
cmd_locn1 = '/bin/ip'
cmd_locn2 = '/sbin/ip'
desiredCommand = ''
if os.path.exists(cmd_locn1) == True:
desiredCommand = cmd_locn1
elif os.path.exists(cmd_locn2) == True:
desiredCommand = cmd_locn2
if desiredCommand != '':
print_line('Found IP(8)=[{}]'.format(desiredCommand), debug=True)
return desiredCommand
def getSystemTemperature():
global rpi_system_temp
global rpi_gpu_temp
global rpi_cpu_temp
rpi_gpu_temp_raw = 'failed'
cmd_fspec = getVcGenCmd()
if cmd_fspec == '':
rpi_system_temp = float('-1.0')
rpi_gpu_temp = float('-1.0')
rpi_cpu_temp = float('-1.0')
else:
retry_count = 3
while retry_count > 0 and 'failed' in rpi_gpu_temp_raw:
cmd_string = "{} measure_temp | /bin/sed -e 's/\\x0//g'".format(
cmd_fspec)
out = subprocess.Popen(cmd_string,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_gpu_temp_raw = stdout.decode(
'utf-8').rstrip().replace('temp=', '').replace('\'C', '')
retry_count -= 1
sleep(1)
if 'failed' in rpi_gpu_temp_raw:
interpretedTemp = float('-1.0')
else:
interpretedTemp = float(rpi_gpu_temp_raw)
rpi_gpu_temp = interpretedTemp
print_line('rpi_gpu_temp=[{}]'.format(rpi_gpu_temp), debug=True)
out = subprocess.Popen("/bin/cat /sys/class/thermal/thermal_zone0/temp",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_cpu_temp_raw = stdout.decode('utf-8').rstrip()
rpi_cpu_temp = float(rpi_cpu_temp_raw) / 1000.0
print_line('rpi_cpu_temp=[{}]'.format(rpi_cpu_temp), debug=True)
# fallback to CPU temp is GPU not available
rpi_system_temp = rpi_gpu_temp
if rpi_gpu_temp == -1.0:
rpi_system_temp = rpi_cpu_temp
def getSystemThermalStatus():
global rpi_throttle_status
# sudo vcgencmd get_throttled
# throttled=0x0
#
# REF: https://harlemsquirrel.github.io/shell/2019/01/05/monitoring-raspberry-pi-power-and-thermal-issues.html
#
rpi_throttle_status = []
cmd_fspec = getVcGenCmd()
if cmd_fspec == '':
rpi_throttle_status.append('Not Available')
else:
cmd_string = "{} get_throttled".format(cmd_fspec)
out = subprocess.Popen(cmd_string,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
rpi_throttle_status_raw = stdout.decode('utf-8').rstrip()
print_line('rpi_throttle_status_raw=[{}]'.format(
rpi_throttle_status_raw), debug=True)
if not 'throttled' in rpi_throttle_status_raw:
rpi_throttle_status.append(
'bad response [{}] from vcgencmd'.format(rpi_throttle_status_raw))
else:
values = []
lineParts = rpi_throttle_status_raw.split('=')
print_line('lineParts=[{}]'.format(lineParts), debug=True)
rpi_throttle_value_raw = ''
if len(lineParts) > 1:
rpi_throttle_value_raw = lineParts[1]
rpi_throttle_value = int(0)
if len(rpi_throttle_value_raw) > 0:
values.append('throttled = {}'.format(rpi_throttle_value_raw))
if rpi_throttle_value_raw.startswith('0x'):
rpi_throttle_value = int(rpi_throttle_value_raw, 16)
else:
rpi_throttle_value = int(rpi_throttle_value_raw, 10)
# decode test code
#rpi_throttle_value = int('0x50002', 16)
if rpi_throttle_value > 0:
values = interpretThrottleValue(rpi_throttle_value)
else:
values.append('Not throttled')
if len(values) > 0:
rpi_throttle_status = values
print_line('rpi_throttle_status=[{}]'.format(
rpi_throttle_status), debug=True)
def interpretThrottleValue(throttleValue):
"""
01110000000000000010
|||| ||||_ Under-voltage detected
|||| |||_ Arm frequency capped
|||| ||_ Currently throttled
|||| |_ Soft temperature limit active
||||_ Under-voltage has occurred since last reboot
|||_ Arm frequency capped has occurred
||_ Throttling has occurred
|_ Soft temperature limit has occurred
"""
print_line('throttleValue=[{}]'.format(bin(throttleValue)), debug=True)
interpResult = []
meanings = [
(2**0, 'Under-voltage detected'),
(2**1, 'Arm frequency capped'),
(2**2, 'Currently throttled'),
(2**3, 'Soft temperature limit active'),
(2**16, 'Under-voltage has occurred'),
(2**17, 'Arm frequency capped has occurred'),
(2**18, 'Throttling has occurred'),
(2**19, 'Soft temperature limit has occurred'),
]
for meaningIndex in range(len(meanings)):
bitTuple = meanings[meaningIndex]
if throttleValue & bitTuple[0] > 0:
interpResult.append(bitTuple[1])
print_line('interpResult=[{}]'.format(interpResult), debug=True)
return interpResult
def getLastUpdateDate():
global rpi_last_update_date
# apt-get update writes to following dir (so date changes on update)
apt_listdir_filespec = '/var/lib/apt/lists/partial'
# apt-get dist-upgrade | autoremove update the following file when actions are taken
apt_lockdir_filespec = '/var/lib/dpkg/lock'
cmdString = '/bin/ls -ltrd {} {}'.format(
apt_listdir_filespec, apt_lockdir_filespec)
out = subprocess.Popen(cmdString,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
lines = stdout.decode('utf-8').split("\n")
trimmedLines = []
for currLine in lines:
trimmedLine = currLine.lstrip().rstrip()
if len(trimmedLine) > 0:
trimmedLines.append(trimmedLine)
print_line('trimmedLines=[{}]'.format(trimmedLines), debug=True)
fileSpec_latest = ''
if len(trimmedLines) > 0:
lastLineIdx = len(trimmedLines) - 1
lineParts = trimmedLines[lastLineIdx].split()
if len(lineParts) > 0:
lastPartIdx = len(lineParts) - 1
fileSpec_latest = lineParts[lastPartIdx]
print_line('fileSpec_latest=[{}]'.format(fileSpec_latest), debug=True)
fileModDateInSeconds = os.path.getmtime(fileSpec_latest)
fileModDate = datetime.fromtimestamp(fileModDateInSeconds)
rpi_last_update_date = fileModDate.replace(tzinfo=local_tz)
print_line('rpi_last_update_date=[{}]'.format(
rpi_last_update_date), debug=True)
def to_datetime(time):
return datetime.fromordinal(int(time)) + datetime.timedelta(time % 1)
def getLastInstallDate():
global rpi_last_update_date
#apt_log_filespec = '/var/log/dpkg.log'
#apt_log_filespec2 = '/var/log/dpkg.log.1'
out = subprocess.Popen("/bin/grep --binary-files=text 'status installed' /var/log/dpkg.log /var/log/dpkg.log.1 2>/dev/null | sort | tail -1",
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, _ = out.communicate()
last_installed_pkg_raw = stdout.decode(
'utf-8').rstrip().replace('/var/log/dpkg.log:', '').replace('/var/log/dpkg.log.1:', '')
print_line('last_installed_pkg_raw=[{}]'.format(
last_installed_pkg_raw), debug=True)
line_parts = last_installed_pkg_raw.split()
if len(line_parts) > 1:
pkg_date_string = '{} {}'.format(line_parts[0], line_parts[1])
print_line('pkg_date_string=[{}]'.format(pkg_date_string), debug=True)
# Example:
# 2020-07-22 17:08:26 status installed python3-tzlocal:all 1.3-1
pkg_install_date = datetime.strptime(
pkg_date_string, '%Y-%m-%d %H:%M:%S').replace(tzinfo=local_tz)
rpi_last_update_date = pkg_install_date
print_line('rpi_last_update_date=[{}]'.format(
rpi_last_update_date), debug=True)
# get our hostnames so we can setup MQTT
getHostnames()
if(sensor_name == default_sensor_name):
sensor_name = 'rpi-{}'.format(rpi_hostname)
# get model so we can use it too in MQTT
getDeviceModel()
getDeviceCpuInfo()
getLinuxRelease()
getLinuxVersion()
getFileSystemDrives()
# -----------------------------------------------------------------------------
# timer and timer funcs for ALIVE MQTT Notices handling
# -----------------------------------------------------------------------------
ALIVE_TIMOUT_IN_SECONDS = 60
def publishAliveStatus():
print_line('- SEND: yes, still alive -', debug=True)
mqtt_client.publish(lwt_topic, payload=lwt_online_val, retain=False)
def aliveTimeoutHandler():
print_line('- MQTT TIMER INTERRUPT -', debug=True)
_thread.start_new_thread(publishAliveStatus, ())
startAliveTimer()
def startAliveTimer():
global aliveTimer
global aliveTimerRunningStatus
stopAliveTimer()
aliveTimer = threading.Timer(ALIVE_TIMOUT_IN_SECONDS, aliveTimeoutHandler)
aliveTimer.start()
aliveTimerRunningStatus = True
print_line(
'- started MQTT timer - every {} seconds'.format(ALIVE_TIMOUT_IN_SECONDS), debug=True)
def stopAliveTimer():
global aliveTimer
global aliveTimerRunningStatus
aliveTimer.cancel()
aliveTimerRunningStatus = False
print_line('- stopped MQTT timer', debug=True)
def isAliveTimerRunning():
global aliveTimerRunningStatus
return aliveTimerRunningStatus