Skip to content

Commit d637ee7

Browse files
committed
repaired MQTT subscript and LWT online/offline reporting
1 parent f08c88e commit d637ee7

File tree

5 files changed

+52
-43
lines changed

5 files changed

+52
-43
lines changed

ChangeLog

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
# ChangeLog
22

3-
---- Next Rls -------- v1.8.1
3+
Tue, 28 Feb 2023 17:24:07 -0700 v1.8.2
4+
5+
- fix LWT online/offline status updates of Daemon
6+
- repair MQTT command subscription mechanism
7+
- repaired the remote-control setup instructions for restart-service, updated config.ini.dist
8+
9+
Sun Feb 26 18:28:36 2023 -0700 v1.8.1
410

511
- Repair temperature units regression (#82)
612
- Disk Used sensor repaired (was reporting free vs. used) (#83)
13+
- Refine the advertisement of the command endpoints
714

815
Sat, 25 Feb 2023 19:36:42 -0700 v1.8.0
916

ISP-RPi-mqtt-daemon.py

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
except ImportError:
3535
apt_available = False
3636

37-
script_version = "1.8.1"
37+
script_version = "1.8.2"
3838
script_name = 'ISP-RPi-mqtt-daemon.py'
3939
script_info = '{} v{}'.format(script_name, script_version)
4040
project_name = 'RPi Reporter MQTT2HA Daemon'
@@ -143,8 +143,6 @@ def clean_identifier(name):
143143
'* init mqtt_client_connected=[{}]'.format(mqtt_client_connected), debug=True)
144144
mqtt_client_should_attempt_reconnect = True
145145

146-
command_base_topic = '{not-set}/command/{not-set}'
147-
148146
def on_connect(client, userdata, flags, rc):
149147
global mqtt_client_connected
150148
if rc == 0:
@@ -157,15 +155,6 @@ def on_connect(client, userdata, flags, rc):
157155
mqtt_client_connected), debug=True)
158156
client.on_publish = on_publish
159157

160-
# -------------------------------------------------------------------------
161-
# Commands Subscription
162-
if (len(commands) > 0):
163-
print_line('MQTT subscription to {}/+ enabled'.format(command_base_topic), console=True, sd_notify=True)
164-
client.on_message = on_message
165-
client.subscribe('{}/+'.format(command_base_topic))
166-
else:
167-
print_line('MQTT subscripton to {}/+ disabled'.format(command_base_topic), console=True, sd_notify=True)
168-
# -------------------------------------------------------------------------
169158
else:
170159
print_line('! Connection error with result code {} - {}'.format(str(rc),
171160
mqtt.connack_string(rc)), error=True)
@@ -191,16 +180,17 @@ def on_subscribe(client, userdata, mid, granted_qos):
191180
print_line('on_subscribe() - {} - {}'.format(str(mid),str(granted_qos)), debug=True, sd_notify=True)
192181

193182
def on_message(client, userdata, message):
194-
print_line('on_message(). Topic=[{}] payload=[{}]'.format(message.topic, message.payload), console=True, sd_notify=True, debug=True)
183+
print_line('on_message() Topic=[{}] payload=[{}]'.format(message.topic, message.payload), console=True, sd_notify=True, debug=True)
195184

196185
decoded_payload = message.payload.decode('utf-8')
197186
command = message.topic.split('/')[-1]
198187

199-
if command in commands:
200-
print_line('- Command "{}" Received - Run {} {} -'.format(command, commands[command], decoded_payload), console=True, debug=True)
201-
subprocess.Popen(["/usr/bin/sh", "-c", commands[command].format(decoded_payload)])
202-
else:
203-
print_line('* Invalid Command received.', error=True)
188+
if command != 'status':
189+
if command in commands:
190+
print_line('- Command "{}" Received - Run {} {} -'.format(command, commands[command], decoded_payload), console=True, debug=True)
191+
subprocess.Popen(["/usr/bin/sh", "-c", commands[command].format(decoded_payload)])
192+
else:
193+
print_line('* Invalid Command received.', error=True)
204194

205195
# -----------------------------------------------------------------------------
206196
# Load configuration file
@@ -1180,6 +1170,9 @@ def getNumberOfAvailableUpdates():
11801170
if apt_available:
11811171
getNumberOfAvailableUpdates()
11821172

1173+
command_base_topic = '{}/command/{}'.format(base_topic, sensor_name.lower())
1174+
1175+
11831176
# -----------------------------------------------------------------------------
11841177
# timer and timer funcs for ALIVE MQTT Notices handling
11851178
# -----------------------------------------------------------------------------
@@ -1190,7 +1183,12 @@ def getNumberOfAvailableUpdates():
11901183
def publishAliveStatus():
11911184
print_line('- SEND: yes, still alive -', debug=True)
11921185
mqtt_client.publish(lwt_sensor_topic, payload=lwt_online_val, retain=False)
1186+
mqtt_client.publish(lwt_command_topic, payload=lwt_online_val, retain=False)
11931187

1188+
def publishShuttingDownStatus():
1189+
print_line('- SEND: shutting down -', debug=True)
1190+
mqtt_client.publish(lwt_sensor_topic, payload=lwt_offline_val, retain=False)
1191+
mqtt_client.publish(lwt_command_topic, payload=lwt_offline_val, retain=False)
11941192

11951193
def aliveTimeoutHandler():
11961194
print_line('- MQTT TIMER INTERRUPT -', debug=True)
@@ -1273,6 +1271,16 @@ def isAliveTimerRunning():
12731271
error=True, sd_notify=True)
12741272
sys.exit(1)
12751273
else:
1274+
# -------------------------------------------------------------------------
1275+
# Commands Subscription
1276+
if (len(commands) > 0):
1277+
print_line('MQTT subscription to {}/+ enabled'.format(command_base_topic), console=True, sd_notify=True)
1278+
mqtt_client.on_message = on_message
1279+
mqtt_client.subscribe('{}/+'.format(command_base_topic))
1280+
else:
1281+
print_line('MQTT subscripton to {}/+ disabled'.format(command_base_topic), console=True, sd_notify=True)
1282+
# -------------------------------------------------------------------------
1283+
12761284
mqtt_client.publish(lwt_sensor_topic, payload=lwt_online_val, retain=False)
12771285
mqtt_client.publish(lwt_command_topic, payload=lwt_online_val, retain=False)
12781286
mqtt_client.loop_start()
@@ -1378,8 +1386,6 @@ def isAliveTimerRunning():
13781386
))
13791387
])
13801388

1381-
command_base_topic = '{}/command/{}'.format(base_topic, sensor_name.lower())
1382-
13831389
for [command, _] in commands.items():
13841390
#print_line('- REGISTER command: [{}]'.format(command), debug=True)
13851391
iconName = 'mdi:gesture-tap'
@@ -1809,5 +1815,8 @@ def afterMQTTConnect():
18091815

18101816
finally:
18111817
# cleanup used pins... just because we like cleaning up after us
1818+
publishShuttingDownStatus()
18121819
stopPeriodTimer() # don't leave our timers running!
18131820
stopAliveTimer()
1821+
mqtt_client.disconnect()
1822+
print_line('* MQTT Disconnect()', verbose=True)

README.md

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,20 +12,19 @@ A simple Linux python script to query the Raspberry Pi on which it is running fo
1212

1313
![Discovery image](./Docs/images/DiscoveryV4.png)
1414

15-
This script should be configured to be run in **daemon mode** continously in the background as a systemd service (or optionally as a SysV init script). Instructions are provided below.
16-
15+
This script should be configured to be run in **daemon mode** continuously in the background as a systemd service (or optionally as a SysV init script). Instructions are provided below.
1716

1817
## Table of Contents
1918

2019
On this Page:
2120

2221
- [Features](#features)- key features of this reporter
23-
- [Prerequisites](#prerequisites)
22+
- [Prerequisites](#prerequisites)
2423
- [Installation](#installation) - install prerequisites and the daemon project
2524
- [Configuration](#configuration) - configuring the script to talk with your MQTT broker
2625
- [Execution](#execution) - initial run by hand, then setup to run from boot
2726
- [Integration](#integration) - a quick look at what's reported to MQTT about this RPi
28-
- [Troubleshooting](#troubleshooting) - having start up issues? Check here for common problems
27+
- [Troubleshooting](#troubleshooting) - having start up issues? Check here for common problems
2928

3029
Additional pages:
3130

@@ -34,7 +33,6 @@ Additional pages:
3433
- [The Associated Lovelace RPi Monitor Card](https://github.com/ironsheep/lovelace-rpi-monitor-card) - This is our companion Lovelace Card that makes displaying this RPi Monitor data very easy
3534
- [ChangeLog](./ChangeLog) - We've been repairing or adding features to this script as users report issues or wishes. This is our list of changes
3635

37-
3836
## Features
3937

4038
- Tested on Raspberry Pi's 2/3/4 with Jessie, Stretch and Buster
@@ -111,7 +109,7 @@ The monitored topic reports the following information:
111109
| `throttle` | | reports the throttle status value plus interpretation thereof |
112110
| `timestamp` | | date, time when this report was generated |
113111

114-
_NOTE: cpu load averages are divided by the number of cores_
112+
NOTE: _cpu load averages are divided by the number of cores_
115113

116114
## Prerequisites
117115

@@ -143,10 +141,10 @@ sudo apt-get install libraspberrypi-bin net-tools
143141
### Packages for Arch Linux
144142

145143
```shell
146-
sudo pacman -S python python-pip python-tzlocal python-notify2 python-colorama python-unidecode python-paho-mqtt python-requests inetutils
144+
sudo pacman -S python python-pip python-tzlocal python-notify2 python-colorama python-unidecode python-paho-mqtt python-requests inetutils
147145
```
148146

149-
**NOTE**: *for users of Arch Linux the number of updates available will NOT be reported (will always show as '-1'.) This is due to Arch Linux not using the apt package manager.*
147+
**NOTE**: _for users of Arch Linux the number of updates available will NOT be reported (will always show as '-1'.) This is due to Arch Linux not using the apt package manager._
150148

151149
### With these extra packages installed, verify access to network information
152150

@@ -185,7 +183,7 @@ wlan0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
185183

186184
```
187185

188-
If you are seeing output from the `ifconfig` tool then continue on with the following steps. If you don't you may have missed installing `net-utils` in an earlier step.
186+
If you are seeing output from the `ifconfig` tool then continue on with the following steps. If you don't you may have missed installing `net-utils` in an earlier step.
189187

190188
### Now finish with the script install
191189

@@ -436,10 +434,7 @@ An example:
436434
"load_5min_prcnt": 0,
437435
"load_15min_prcnt": 0
438436
},
439-
"throttle": [
440-
"throttled = 0x0",
441-
"Not throttled"
442-
],
437+
"throttle": ["throttled = 0x0", "Not throttled"],
443438
"temperature_c": 25.8,
444439
"temp_gpu_c": 25.8,
445440
"temp_cpu_c": 25.8,
@@ -450,11 +445,10 @@ An example:
450445
}
451446
```
452447
453-
**NOTE:** Where there's an IP address that interface is connected. Also, there are new `tx_data` and `rx_data` values which show traffic in bytes for this reporting interval for each network interface.
448+
**NOTE:** Where there's an IP address that interface is connected. Also, there are new `tx_data` and `rx_data` values which show traffic in bytes for this reporting interval for each network interface.
454449
455450
This data can be subscribed to and processed by your home assistant installation. How you build your RPi dashboard from here is up to you!
456451
457-
458452
## Troubleshooting
459453
460454
### Issue: Some of my RPi's don't show up in HA
@@ -467,7 +461,7 @@ We occasionaly have reports of users with more than one RPi on their network but
467461
468462
Most often fix: _reboot the missing RPi._
469463
470-
When you remove a sensor from Home Assistant it tells the MQTT broker to 'forget' everything it knows about the RPi. Some of the information is actually `stored by the MQTT broker` so it is available while the RPi is offline. Our Daemon script only broadcasts this `stored` information when it is first started. As a result the RPi will not re-appear after delete from Home Assistant until you reboot the RPi in question. (or, alternatively, stop then restart the script.). You may find reboot easier to do.
464+
When you remove a sensor from Home Assistant it tells the MQTT broker to 'forget' everything it knows about the RPi. Some of the information is actually `stored by the MQTT broker` so it is available while the RPi is offline. Our Daemon script only broadcasts this `stored` information when it is first started. As a result the RPi will not re-appear after delete from Home Assistant until you reboot the RPi in question. (or, alternatively, stop then restart the script.). You may find reboot easier to do.
471465
472466
To reboot:
473467
@@ -510,13 +504,12 @@ I find [MQTT Explorer](http://mqtt-explorer.com/) to be an excellent tool to use
510504
511505
Alternatively I also use **MQTTBox** when I want to send messages by hand to interact via MQTT. it is affered as a web extension or a native application.
512506
513-
514507
#### Viewing the Daemon logs
515508
516509
When your script is being run as a Daemon it is logging. You can view the log output since last reboot with:
517510
518511
```bash
519-
$ journalctl -b --no-pager -u isp-rpi-reporter.service
512+
journalctl -b --no-pager -u isp-rpi-reporter.service
520513
```
521514
522515
Alternatively you can create a simple script which you can run any time you want to see the log. Here's my show Daemon log script `showRpiLog`:
@@ -527,7 +520,7 @@ Alternatively you can create a simple script which you can run any time you want
527520
(set -x;journalctl -b --no-pager -u isp-rpi-reporter.service)
528521
```
529522
530-
**NOTE**: *the -b says 'since last boot' the --no-pager says just show it all without breaking it up into pages and requiring the enter key press for each page.*
523+
**NOTE**: _the -b says 'since last boot' the --no-pager says just show it all without breaking it up into pages and requiring the enter key press for each page._
531524
532525
---
533526

RMTECTRL.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ An example to reboot or shutdown the Pi:
8787
[Commands]
8888
shutdown = /usr/bin/sudo /sbin/shutdown -h now 'shutdown rqst via MQTT'
8989
reboot = /usr/bin/sudo /sbin/shutdown -r now 'reboot rqst via MQTT'
90-
restart_service = /usr/bin/sudo systemctl restart {}
90+
restart_service = /usr/bin/sudo systemctl restart isp-rpi-reporter.service
9191
```
9292

9393
*NOTE* the message in the `{action} rqst via MQTT` message is logged in `/var/log/auth.log` so one can keep track of when commands are executed via MQTT.
@@ -109,7 +109,7 @@ the sudoers configuration file:
109109

110110
# add the following lines at the bottom.
111111
# note that every service that we want to allow to restart must be specified here
112-
daemon <raspberrypihostname> =NOPASSWD: /usr/bin/systemctl restart isp-rpi-reporter,/sbin/shutdown
112+
daemon <raspberrypihostname> =NOPASSWD: /usr/bin/systemctl restart isp-rpi-reporter.service,/sbin/shutdown
113113
```
114114

115115
NOTE: In some systems the path for `systemctl` / `reboot` / `shutdown` can be different. Make sure the path you specify is correct for your system.

config.ini.dist

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
[Commands]
2323
#shutdown = /usr/bin/sudo /sbin/shutdown -h now 'shutdown rqst via MQTT'
2424
#reboot = /usr/bin/sudo /sbin/shutdown -r now 'reboot rqst via MQTT'
25-
#restart_service = /usr/bin/sudo systemctl restart {}
25+
#restart_service = /usr/bin/sudo systemctl restart isp-rpi-reporter.service
2626

2727
[MQTT]
2828

0 commit comments

Comments
 (0)