Skip to content

Commit 45a20f9

Browse files
committed
clean up docs and repair subscription to commands
- Handle re-subscription if MQTT broker restarts (#99) - Simplify installation / setup documentation (#97) - Repair bug in running shell to execute commands
1 parent 7160a83 commit 45a20f9

6 files changed

Lines changed: 171 additions & 59 deletions

File tree

‎ChangeLog‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
# ChangeLog
22

3+
Mon, 01 May 2023 16:51:08 -0600 v1.8.5
4+
5+
- Handle resubscription if MQTT broker restarts (#99)
6+
- Simplify installation / setup documentation (#97)
7+
- Repair bug in running shell to execute commands
8+
39
Tue, 28 Mar 2023 23:24:03 -0600 v1.8.4
410

511
- Remove unused Requirements file from repo. (#92)

‎Docs/images/Device-list.png‎

51.8 KB
Loading

‎Docs/images/Discovered-Device.png‎

127 KB
Loading

‎ISP-RPi-mqtt-daemon.py‎

Lines changed: 46 additions & 17 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.4"
37+
script_version = "1.8.5"
3838
script_name = 'ISP-RPi-mqtt-daemon.py'
3939
script_info = '{} v{}'.format(script_name, script_version)
4040
project_name = 'RPi Reporter MQTT2HA Daemon'
@@ -146,14 +146,21 @@ def clean_identifier(name):
146146
def on_connect(client, userdata, flags, rc):
147147
global mqtt_client_connected
148148
if rc == 0:
149-
print_line('* MQTT connection established',
150-
console=True, sd_notify=True)
149+
print_line('* MQTT connection established', console=True, sd_notify=True)
151150
print_line('') # blank line?!
152151
#_thread.start_new_thread(afterMQTTConnect, ())
153152
mqtt_client_connected = True
154153
print_line('on_connect() mqtt_client_connected=[{}]'.format(
155154
mqtt_client_connected), debug=True)
156-
client.on_publish = on_publish
155+
156+
# -------------------------------------------------------------------------
157+
# Commands Subscription
158+
if (len(commands) > 0):
159+
print_line('MQTT subscription to {}/+ enabled'.format(command_base_topic), console=True, sd_notify=True)
160+
mqtt_client.subscribe('{}/+'.format(command_base_topic))
161+
else:
162+
print_line('MQTT subscripton to {}/+ disabled'.format(command_base_topic), console=True, sd_notify=True)
163+
# -------------------------------------------------------------------------
157164

158165
else:
159166
print_line('! Connection error with result code {} - {}'.format(str(rc),
@@ -167,6 +174,13 @@ def on_connect(client, userdata, flags, rc):
167174
# kill main thread
168175
os._exit(1)
169176

177+
def on_disconnect(client, userdata, mid):
178+
global mqtt_client_connected
179+
mqtt_client_connected = False
180+
print_line('* MQTT connection lost', console=True, sd_notify=True)
181+
print_line('on_disconnect() mqtt_client_connected=[{}]'.format(
182+
mqtt_client_connected), debug=True)
183+
pass
170184

171185
def on_publish(client, userdata, mid):
172186
#print_line('* Data successfully published.')
@@ -179,16 +193,27 @@ def on_publish(client, userdata, mid):
179193
def on_subscribe(client, userdata, mid, granted_qos):
180194
print_line('on_subscribe() - {} - {}'.format(str(mid),str(granted_qos)), debug=True, sd_notify=True)
181195

196+
shell_cmd_fspec = ''
182197
def on_message(client, userdata, message):
183-
print_line('on_message() Topic=[{}] payload=[{}]'.format(message.topic, message.payload), console=True, sd_notify=True, debug=True)
198+
global shell_cmd_fspec
199+
if shell_cmd_fspec == '':
200+
shell_cmd_fspec = getShellCmd()
201+
if shell_cmd_fspec == '':
202+
print_line('* Failed to locate shell Command!', error=True)
203+
# kill main thread
204+
os._exit(1)
184205

185206
decoded_payload = message.payload.decode('utf-8')
186207
command = message.topic.split('/')[-1]
208+
print_line('on_message() Topic=[{}] payload=[{}] command=[{}]'.format(message.topic, message.payload, command), console=True, sd_notify=True, debug=True)
187209

188210
if command != 'status':
189211
if command in commands:
190212
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)])
213+
pHandle = subprocess.Popen([shell_cmd_fspec, "-c", commands[command].format(decoded_payload)])
214+
output, errors = pHandle.communicate()
215+
if errors:
216+
print_line('- Command exec says: errors=[{}]'.format(errors), console=True, debug=True)
192217
else:
193218
print_line('* Invalid Command received.', error=True)
194219

@@ -920,6 +945,17 @@ def getVcGenCmd():
920945
print_line('Found vcgencmd(1)=[{}]'.format(desiredCommand), debug=True)
921946
return desiredCommand
922947

948+
def getShellCmd():
949+
cmd_locn1 = '/usr/bin/sh'
950+
cmd_locn2 = '/bin/sh'
951+
desiredCommand = cmd_locn1
952+
if os.path.exists(desiredCommand) == False:
953+
desiredCommand = cmd_locn2
954+
if os.path.exists(desiredCommand) == False:
955+
desiredCommand = ''
956+
if desiredCommand != '':
957+
print_line('Found sh(1)=[{}]'.format(desiredCommand), debug=True)
958+
return desiredCommand
923959

924960
def getIPCmd():
925961
cmd_locn1 = '/bin/ip'
@@ -1248,8 +1284,11 @@ def isAliveTimerRunning():
12481284

12491285
print_line('Connecting to MQTT broker ...', verbose=True)
12501286
mqtt_client = mqtt.Client()
1287+
# hook up MQTT callbacks
12511288
mqtt_client.on_connect = on_connect
1252-
1289+
mqtt_client.on_disconnect = on_disconnect
1290+
mqtt_client.on_publish = on_publish
1291+
mqtt_client.on_message = on_message
12531292

12541293
mqtt_client.will_set(lwt_sensor_topic, payload=lwt_offline_val, retain=True)
12551294
mqtt_client.will_set(lwt_command_topic, payload=lwt_offline_val, retain=True)
@@ -1281,16 +1320,6 @@ def isAliveTimerRunning():
12811320
error=True, sd_notify=True)
12821321
sys.exit(1)
12831322
else:
1284-
# -------------------------------------------------------------------------
1285-
# Commands Subscription
1286-
if (len(commands) > 0):
1287-
print_line('MQTT subscription to {}/+ enabled'.format(command_base_topic), console=True, sd_notify=True)
1288-
mqtt_client.on_message = on_message
1289-
mqtt_client.subscribe('{}/+'.format(command_base_topic))
1290-
else:
1291-
print_line('MQTT subscripton to {}/+ disabled'.format(command_base_topic), console=True, sd_notify=True)
1292-
# -------------------------------------------------------------------------
1293-
12941323
mqtt_client.publish(lwt_sensor_topic, payload=lwt_online_val, retain=False)
12951324
mqtt_client.publish(lwt_command_topic, payload=lwt_online_val, retain=False)
12961325
mqtt_client.loop_start()

‎README.md‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ Additional pages:
3535

3636
## Features
3737

38-
- Tested on Raspberry Pi's 2/3/4 with Jessie, Stretch and Buster
39-
- Tested with Home Assistant v0.111.0 -> 2023.2.5
40-
- Tested with Mosquitto broker v5.1 - v6.1.3
38+
- Tested on Raspberry Pi's zero, 2, 3, and 4 with Jessie, Stretch, Buster, and Bullseye
39+
- Tested with Home Assistant v0.111.0 -> 2023.4.6
40+
- Tested with Mosquitto broker
4141
- Data is published via MQTT
4242
- MQTT discovery messages are sent so RPi's are automatically registered with Home Assistant (if MQTT discovery is enabled in your HA installation)
4343
- MQTT authentication support
@@ -129,7 +129,7 @@ First install extra packages the script needs (select one of the two following c
129129
### Packages for Ubuntu, Raspberry pi OS, and the like
130130

131131
```shell
132-
sudo apt-get install git python3 python3-pip python3-tzlocal python3-sdnotify python3-colorama python3-unidecode python3-apt python3-paho-mqtt
132+
sudo apt-get install git python3 python3-pip python3-tzlocal python3-sdnotify python3-colorama python3-unidecode python3-apt python3-paho-mqtt python3-requests
133133
```
134134

135135
### Additional Packages for pure Ubuntu
@@ -234,6 +234,8 @@ password = {your mqtt password if your setup requires one}
234234
235235
Now that your config.ini is setup let's test!
236236
237+
**NOTE:** *If you wish to support remote commanding of your RPi then you can find additional configuration steps in [Setting up RPi Control from Home Assistant](./RMTCTRL.md) However, to simplifly your effort, please complete the following steps to ensure all is running as desired before you attempt to set up remote control.*
238+
237239
## Execution
238240
239241
### Initial Test
@@ -278,6 +280,8 @@ $ daemon : daemon video
278280
# ^^^^^ now it is present
279281
```
280282
283+
*NOTE: Yes, `video` is correct. This appears to be due to our accessing the GPU temperatures.*
284+
281285
### Choose Run Style
282286
283287
You can choose to run this script as a `systemd service` or as a `Sys V init script`. If you are on a newer OS than `Jessie` or if as a system admin you are just more comfortable with Sys V init scripts then you can use the latter style.
@@ -458,6 +462,15 @@ This data can be subscribed to and processed by your home assistant installation
458462
459463
## Troubleshooting
460464
465+
### Issue: I've updated my RPi OS and now I'm getting reporter script startup errors
466+
467+
Most often fix: _Re-add the video perms to the daemon group_
468+
469+
See Closed Issues: [#94](https://github.com/ironsheep/RPi-Reporter-MQTT2HA-Daemon/issues/94), [#98](https://github.com/ironsheep/RPi-Reporter-MQTT2HA-Daemon/issues/98)
470+
471+
We occasionaly have reports of users who updated their RPi afterwhich the RPI reporter Daemon script fails to start. The issue is that one of the packages updated appears to have reset the `daemon` group perminsions. For instructions on resetting the permissions to what is needed see: [Set up daemon account to allow access to temperature values](https://github.com/ironsheep/RPi-Reporter-MQTT2HA-Daemon#set-up-daemon-account-to-allow-access-to-temperature-values)
472+
473+
461474
### Issue: Some of my RPi's don't show up in HA
462475
463476
Most often fix: _install the missing package._

0 commit comments

Comments
 (0)