-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
ISP-RPi-mqtt-daemon.py
executable file
·1912 lines (1639 loc) · 69.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 -*-
from urllib3.exceptions import InsecureRequestWarning
import requests
import time
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)
apt_available = True
try:
import apt
except ImportError:
apt_available = False
script_version = "1.9.x"
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()
# turn off insecure connection warnings (our KZ0Q site has bad certs)
# REF: https://www.geeksforgeeks.org/how-to-disable-security-certificate-checks-for-requests-in-python/
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
# 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 (sd_notify):
text = '* NOTIFY: {}'.format(text)
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('--------------------------------------------------------------------', debug=True)
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)
# -------------------------------------------------------------------------
# Commands Subscription
if (len(commands) > 0):
print_line('MQTT subscription to {}/+ enabled'.format(command_base_topic), console=True, sd_notify=True)
mqtt_client.subscribe('{}/+'.format(command_base_topic))
else:
print_line('MQTT subscripton to {}/+ disabled'.format(command_base_topic), console=True, sd_notify=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_disconnect(client, userdata, mid):
global mqtt_client_connected
mqtt_client_connected = False
print_line('* MQTT connection lost', console=True, sd_notify=True)
print_line('on_disconnect() mqtt_client_connected=[{}]'.format(
mqtt_client_connected), debug=True)
pass
def on_publish(client, userdata, mid):
# print_line('* Data successfully published.')
pass
# -----------------------------------------------------------------------------
# Commands - MQTT Subscription Callback
# -----------------------------------------------------------------------------
# Command catalog
def on_subscribe(client, userdata, mid, granted_qos):
print_line('on_subscribe() - {} - {}'.format(str(mid), str(granted_qos)), debug=True, sd_notify=True)
shell_cmd_fspec = ''
def on_message(client, userdata, message):
global shell_cmd_fspec
if shell_cmd_fspec == '':
shell_cmd_fspec = getShellCmd()
if shell_cmd_fspec == '':
print_line('* Failed to locate shell Command!', error=True)
# kill main thread
os._exit(1)
decoded_payload = message.payload.decode('utf-8')
command = message.topic.split('/')[-1]
print_line('on_message() Topic=[{}] payload=[{}] command=[{}]'.format(
message.topic, message.payload, command), console=True, sd_notify=True, debug=True)
if command != 'status':
if command in commands:
print_line('- Command "{}" Received - Run {} {} -'.format(command,
commands[command], decoded_payload), console=True, debug=True)
pHandle = subprocess.Popen([shell_cmd_fspec, "-c", commands[command].format(decoded_payload)])
output, errors = pHandle.communicate()
if errors or pHandle.returncode:
print_line('- Command exec says: errors=[{}]'.format(errors or output), console=True, debug=True)
else:
print_line('* Invalid Command received.', error=True)
# -----------------------------------------------------------------------------
# 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 could be set either via configuration file or `MQTT_SENSOR_NAME`
# environment variable, the latter takes precedence
sensor_name = os.environ.get(
"MQTT_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)
# check our RPi pending-updates every 4 hours
min_check_interval_in_hours = 2
max_check_interval_in_hours = 24
default_check_interval_in_hours = 4
check_interval_in_hours = config['Daemon'].getint(
'check_updates_in_hours', default_check_interval_in_hours)
# default domain when hostname -f doesn't return it
default_domain = ''
fallback_domain = config['Daemon'].get(
'fallback_domain', default_domain).lower()
commands = OrderedDict([])
if config.has_section('Commands'):
commandSet = dict(config['Commands'].items())
if len(commandSet) > 0:
commands.update(commandSet)
# -----------------------------------------------------------------------------
# Commands Subscription
# -----------------------------------------------------------------------------
# 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)
if (check_interval_in_hours < min_check_interval_in_hours) or (check_interval_in_hours > max_check_interval_in_hours):
print_line('ERROR: Invalid "check_updates_in_hours" found in configuration file: "config.ini"! Must be [{}-{}] Fix and try again... Aborting'.format(
min_check_interval_in_hours, max_check_interval_in_hours), 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)
# -----------------------------------------------------------------------------
# Daemon variables monitored
# -----------------------------------------------------------------------------
daemon_version_list = ['NOT-LOADED']
daemon_last_fetch_time = 0.0
def getDaemonReleases():
# retrieve latest formal release versions list from repo
global daemon_version_list
global daemon_last_fetch_time
newVersionList = []
latestVersion = ''
daemon_version_list = ['NOT-LOADED'] # mark as NOT fetched
error = False
try:
response = requests.request('GET', 'http://kz0q.com/daemon-releases', verify=False, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as exc:
print_line('- getDaemonReleases() RQST exception=({})'.format(exc), error=True)
error = True
if not error:
content = response.text
lines = content.split('\n')
for line in lines:
if len(line) > 0:
# print_line('- RLS Line=[{}]'.format(line), debug=True)
lineParts = line.split(' ')
# print_line('- RLS lineParts=[{}]'.format(lineParts), debug=True)
if len(lineParts) >= 2:
currVersion = lineParts[0]
rlsType = lineParts[1]
if not currVersion in newVersionList:
if not 'latest' in rlsType.lower():
newVersionList.append(currVersion) # append to list
else:
latestVersion = currVersion
if len(newVersionList) > 1:
newVersionList.sort()
if len(latestVersion) > 0:
if not latestVersion in newVersionList:
newVersionList.insert(0, latestVersion) # append to list
daemon_version_list = newVersionList
print_line('- RQST daemon_version_list=({})'.format(daemon_version_list), debug=True)
daemon_last_fetch_time = time() # record when we last fetched the versions
getDaemonReleases() # and load them!
print_line('* daemon_last_fetch_time=({})'.format(daemon_last_fetch_time), debug=True)
# -----------------------------------------------------------------------------
# Command invocation thru shell
def invoke_shell_cmd(cmd):
# Setting `pipefail` prior to command ensures the command will exit with
# non-zero status if any command in pipe (if any) fails.
# Using `Popen` with `args` being list setting such shell option there
# doesn't work for some shells, presumably due to argument processing
# order, so invoking shell needs to be specified explicitly with the option
# follows.
out = subprocess.Popen(['bash', '-o', 'pipefail', '-c', cmd],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
return stdout, stderr, out.returncode
# -----------------------------------------------------------------------------
# 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_uptime_sec = 0
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., Swap Total, Swap Free)
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 = ''
rpi_update_count = 0
if apt_available == False:
rpi_update_count = -1 # if packaging system not avail. report -1
# Time for network transfer calculation
previous_time = time()
# -----------------------------------------------------------------------------
# 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
stdout, _, returncode = invoke_shell_cmd("cat /proc/cpuinfo | /bin/egrep -i 'processor|model|bogo|hardware|serial'")
print_line('getDvcCPUinfo() stdout=[{}], retCode=({})'.format(stdout, returncode), debug=True)
lines = []
if not returncode:
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
stdout, _, returncode = invoke_shell_cmd('/bin/cat /proc/loadavg')
print_line('getDvcCPUinfo() stdout=[{}], retCode=({})'.format(stdout, returncode), debug=True)
cpu_loads_raw = [-1.0] * 3
if not returncode:
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
stdout, _, returncode = invoke_shell_cmd('cat /proc/meminfo')
lines = []
if not returncode:
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 = ''
swap_total = ''
swap_free = ''
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
if 'SwapTotal' in currLine:
swap_total = float(lineParts[1]) / 1024
if 'SwapFree' in currLine:
swap_free = float(lineParts[1]) / 1024
# Tuple (Total, Free, Avail., Swap Total, Swap Free)
# [0]=total, [1]=free, [2]=avail., [3]=swap total, [4]=swap free
rpi_memory_tuple = (mem_total, mem_free, mem_avail, swap_total, swap_free)
print_line('rpi_memory_tuple=[{}]'.format(rpi_memory_tuple), debug=True)
def getDeviceModel():
global rpi_model
global rpi_model_raw
global rpi_connections
stdout, _, returncode = invoke_shell_cmd("/bin/cat /proc/device-tree/model | /bin/sed -e 's/\\x0//g'")
rpi_model_raw = 'N/A'
if not returncode:
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
stdout, _, returncode = invoke_shell_cmd(
"/bin/cat /etc/apt/sources.list | /bin/egrep -v '#' | /usr/bin/awk '{ print $3 }' | /bin/sed -e 's/-/ /g' | /usr/bin/cut -f1 -d' ' | /bin/grep . | /usr/bin/sort -u")
rpi_linux_release = 'N/A'
if not returncode:
rpi_linux_release = stdout.decode('utf-8').rstrip()
print_line('rpi_linux_release=[{}]'.format(rpi_linux_release), debug=True)
def getLinuxVersion():
global rpi_linux_version
stdout, _, returncode = invoke_shell_cmd('/bin/uname -r')
rpi_linux_version = 'N/A'
if not returncode:
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
stdout, _, returncode = invoke_shell_cmd('/bin/hostname -f')
fqdn_from_hostname = stdout.decode('utf-8').rstrip() if not returncode else 'N/A'
# Allow overriding the sensor host name via `MQTT_SENSOR_HOSTNAME`
# environment variable
fqdn_raw = os.environ.get('MQTT_SENSOR_HOSTNAME', fqdn_from_hostname)
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
global rpi_uptime_sec
stdout, _, returncode = invoke_shell_cmd('/usr/bin/uptime')
rpi_uptime_raw = 'N/A'
if not returncode:
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)
# Ex: 10 days, 23:57
# Ex: 27 days, 27 min
# Ex: 0 min
bHasColon = (':' in rpi_uptime)
uptimeParts = rpi_uptime.split(',')
print_line('- uptimeParts=[{}]'.format(uptimeParts), debug=True)
if len(uptimeParts) > 1:
# have days and time
dayParts = uptimeParts[0].strip().split(' ')
daysVal = int(dayParts[0])
timeStr = uptimeParts[1].strip()
else:
# have time only
daysVal = 0
timeStr = uptimeParts[0].strip()
print_line('- days=({}), timeStr=[{}]'.format(daysVal, timeStr), debug=True)
if ':' in timeStr:
# timeStr = '23:57'
timeParts = timeStr.split(':')
hoursVal = int(timeParts[0])
minsVal = int(timeParts[1])
else:
# timeStr = 27 of: '27 min'
hoursVal = 0
timeParts = timeStr.split(' ')
minsVal = int(timeParts[0])
print_line('- hoursVal=({}), minsVal=({})'.format(hoursVal, minsVal), debug=True)
rpi_uptime_sec = (minsVal * 60) + (hoursVal * 60 * 60) + (daysVal * 24 * 60 * 60)
print_line('rpi_uptime_sec=({})'.format(rpi_uptime_sec), debug=True)
def getNetworkIFsUsingIP(ip_cmd):
cmd_str = '{} link show | /bin/egrep -v "link" | /bin/egrep " eth| wlan"'.format(
ip_cmd)
stdout, _, returncode = invoke_shell_cmd(cmd_str)
lines = []
if not returncode:
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()
# if interface is within a container then we have eth0@if77, so
# take the leftmost part up to '@' in that case
interfaceName = lineParts[1].replace(':', '').split('@')[0]
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 |TX packets |RX packets "'.format(
interfaceName)
stdout, _, returncode = invoke_shell_cmd(cmdString)
lines = []
if not returncode:
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
global previous_time
#
# 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)
# RX packets 0 bytes 0 (0.0 B)
# TX packets 0 bytes 0 (0.0 B)
# 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)
# RX packets 1358790 bytes 1197368205 (1.1 GiB)
# TX packets 916361 bytes 150440804 (143.4 MiB)
#
tmpInterfaces = []
haveIF = False
imterfc = ''
rpi_mac = ''
current_time = time()
if current_time == previous_time:
current_time += 1
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)
# OLDER ONLY, using 'Link ' (notice space) prevent from tripping on
# IPv6 ('Scope:Link')
elif 'Link ' in currLine:
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)
elif 'RX' in currLine: # NEWER ONLY
previous_value = getPreviousNetworkData(imterfc, 'rx_data')
current_value = int(lineParts[4])
rx_data = round((current_value - previous_value) / (current_time - previous_time) * 8 / 1024)
newTuple = (imterfc, 'rx_data', rx_data)
tmpInterfaces.append(newTuple)
print_line('newTuple=[{}]'.format(newTuple), debug=True)
elif 'TX' in currLine: # NEWER ONLY
previous_value = getPreviousNetworkData(imterfc, 'tx_data')
current_value = int(lineParts[4])
tx_data = round((current_value - previous_value) / (current_time - previous_time) * 8 / 1024)
newTuple = (imterfc, 'tx_data', tx_data)
tmpInterfaces.append(newTuple)
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 getPreviousNetworkData(interface, field):
global rpi_interfaces
value = [item for item in rpi_interfaces if item[0] == interface and item[1] == field]
if len(value) > 0:
return value[0][2]
else:
return 0
def getNetworkIFs():
ip_cmd = getIPCmd()
if ip_cmd != '':
getNetworkIFsUsingIP(ip_cmd)
else:
stdout, _, returncode = invoke_shell_cmd(
'/sbin/ifconfig | /bin/egrep "Link|flags|inet |ether " | /bin/egrep -v -i "lo:|loopback|inet6|\:\:1|127\.0\.0\.1"')
lines = []
if not returncode:
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
stdout, _, returncode = invoke_shell_cmd("/bin/df -m | /usr/bin/tail -n +2 | /bin/egrep -v 'tmpfs|boot'")
lines = []
if not returncode:
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
# FAILING Case v1.6.x (issue #61)
# [[/bin/df: /mnt/sabrent: No such device or address',
# '/dev/root 119756 19503 95346 17% /',
# '/dev/sda1 953868 882178 71690 93% /media/usb0',
# '/dev/sdb1 976761 93684 883078 10% /media/pi/SSD']]
tmpDrives = []
for currLine in trimmedLines:
if 'no such device' in currLine.lower():
print_line('BAD LINE FORMAT, Skipped=[{}]'.format(currLine), debug=True, warning=True)
continue
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 getShellCmd():
cmd_locn1 = '/usr/bin/sh'
cmd_locn2 = '/bin/sh'
desiredCommand = cmd_locn1
if os.path.exists(desiredCommand) == False:
desiredCommand = cmd_locn2
if os.path.exists(desiredCommand) == False:
desiredCommand = ''
if desiredCommand != '':
print_line('Found sh(1)=[{}]'.format(desiredCommand), debug=True)
return desiredCommand
def getIPCmd():
cmd_locn1 = '/bin/ip'
cmd_locn2 = '/sbin/ip'