Added option to disable discovery messages after the first execution

This commit is contained in:
hjelev
2023-02-05 15:25:39 +02:00
committed by Masoko
parent a00805cb38
commit b54cfee99f
4 changed files with 59 additions and 20 deletions

View File

@@ -42,6 +42,10 @@ Then install this module needed for the script:
```bash
$ pip3 install paho-mqtt
```
Install git if you don't have it:
```bash
$ apt install git
```
Clone the repository:
```bash
$ git clone https://github.com/hjelev/rpi-mqtt-monitor.git
@@ -58,6 +62,7 @@ This is the default configuration:
```
random_delay = randrange(1)
single_discovery_message = True
discovery_messages = True
group_messages = False
sleep_time = 0.5
@@ -73,22 +78,27 @@ wifi_signal = False
wifi_signal_dbm = False
```
If ```discovery_messages``` is set to true, the script will send MQTT Discovery config messages which allows Home Assistant to automatically add the sensors without having to define them in configuration. Note, this setting is only available when ```group_messages``` is set to False.
If ```discovery_messages``` is set to true, the script will send MQTT Discovery config messages which allows Home Assistant to automatically add the sensors without having to define them in configuration. Note, this setting is only available when ```group_messages``` is not used.
If ```single_discovery_message``` is set to true, discovery_messages will be automatically set to False after the first execution of the script. These messages are not needed once the sensors/device is created in Home Assistant.
If ```group_messages``` is set to true the script will send just one message containing all values in CSV format.
The group message looks like this:
```
1.3, 47.1, 12, 1.2, 600, nan, 14.1, 12, 50, -60
```
## Test Raspberry Pi MQTT monitor
## Test Raspberry Pi MQTT Monitor
Run Raspberry Pi MQTT Monitor (you might need to update the path in the command below, depending on where you installled it)
```bash
$ /usr/bin/python /home/pi/rpi-mqtt-monitor/rpi-cpu2mqtt.py
$ /usr/bin/python3 /home/pi/rpi-mqtt-monitor/rpi-cpu2mqtt.py
```
Once you run Raspberry Pi MQTT monitor there will be no output if it run OK, but you should get 8 or more messages via the configured MQTT server (the messages count depends on your configuration).
## Schedule Raspberry Pi MQTT Monitor execution
Create a cron entry like this (you might need to update the path in the cron entry below, depending on where you put the script files):
Create a cron entry like this (you might need to update the path in the cron entry below, depending on where you installed it):
```
*/2 * * * * /usr/bin/python /home/pi/rpi-mqtt-monitor/rpi-cpu2mqtt.py
```
@@ -97,7 +107,7 @@ Create a cron entry like this (you might need to update the path in the cron ent
![Rapsberry Pi MQTT monitor in Home Assistant](images/rpi-cpu2mqtt-hass.jpg)
Once you installed the script on your raspberry you need to create some sensors in home assistant.
If you are using ```discovery_messages```, then this step is not required as the sensors are automatically discovered by Home Assistant and all you need to do is add them from the UI.
If you are using ```discovery_messages```, then this step is not required as a new MQTT device will be automatically created in Home Assistant and all you need to do is add it to a dashboard.
This is the sensors configuration if ```group_messages = True``` assuming your sensors are separated in ```sensors.yaml``` file.
```yaml

View File

@@ -122,7 +122,7 @@ set_cron(){
}
main(){
printm "Raspberry Pi MQTT monitor installer"
printm "Raspberry Pi MQTT Monitor installer"
welcome
find_python
check_and_install_pip

View File

@@ -9,29 +9,33 @@ mqtt_topic_prefix = "rpi-MQTT-monitor"
# Messages configuration
# If this is set to True the script will send just one message containing all values
group_messages = False
# Uncomment the line bellow to send just one CSV message containing all values (this method don't support HA discovery_messages)
# group_messages = True
# Disable dicovery_messages after the first execution of the script (they are not needed unless you delete the device from HA)
single_discovery_message = True
# If this is set, then the script will send MQTT discovery messages meaning a config less setup in HA. Only works
# when group_messages is set to False
# when group_messages is not used
discovery_messages = True
# Random delay in seconds before measuring the values
# - this is used for de-synchronizing message if you run this script on many hosts.
# - if you want a fix delay or 0 you can remove the randrange function and just set the needed value.
random_delay = randrange(1)
# - if you want a fixed delay you can remove the randrange function and just set the needed value.
# random_delay = randrange(10)
# This is the time between sending the individual messages
sleep_time = 0.5
sleep_time = 0.1
cpu_load = True
cpu_temp = True
used_space = True
used_space_path = '/'
voltage = True
sys_clock_speed = True
swap = True
voltage = False
sys_clock_speed = False
swap = False
memory = True
uptime = True
# Enable wifi_signal for unit of measuring % or wifi_signal_dbm for unit of meaning dBm
wifi_signal = False
wifi_signal = True
wifi_signal_dbm = False

View File

@@ -12,6 +12,7 @@ import paho.mqtt.client as paho
import json
import config
import os
import fileinput
# get device host name - used in mqtt topic
hostname = socket.gethostname()
@@ -31,6 +32,7 @@ def check_wifi_signal(format):
except Exception:
wifi_signal = 'NA'
return wifi_signal
@@ -39,16 +41,17 @@ def check_used_space(path):
free_space = st.f_bavail * st.f_frsize
total_space = st.f_blocks * st.f_frsize
used_space = int(100 - ((free_space / total_space) * 100))
return used_space
def check_cpu_load():
# bash command to get cpu load from uptime command
p = subprocess.Popen("uptime", shell=True, stdout=subprocess.PIPE).communicate()[0]
cores = subprocess.Popen("nproc", shell=True, stdout=subprocess.PIPE).communicate()[0]
cpu_load = str(p).split("average:")[1].split(", ")[0].replace(' ', '').replace(',', '.')
cpu_load = float(cpu_load) / int(cores) * 100
cpu_load = round(float(cpu_load), 1)
return cpu_load
@@ -67,6 +70,7 @@ def check_swap():
full_cmd = "free -t |grep -i swap | awk 'NR == 1 {print $3/$2*100}'"
swap = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
swap = round(float(swap.decode("utf-8").replace(",", ".")), 1)
return swap
@@ -74,6 +78,7 @@ def check_memory():
full_cmd = "free -t | awk 'NR == 2 {print $3/$2*100}'"
memory = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
memory = round(float(memory.decode("utf-8").replace(",", ".")))
return memory
@@ -84,16 +89,19 @@ def check_cpu_temp():
cpu_temp = p.decode("utf-8").strip()
except Exception:
cpu_temp = 0
return cpu_temp
def check_sys_clock_speed():
full_cmd = "awk '{printf (\"%0.0f\",$1/1000); }' </sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"
return subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
def check_uptime():
full_cmd = "awk '{print int($1/3600/24)}' /proc/uptime"
return int(subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0])
@@ -104,6 +112,7 @@ def check_model_name():
full_cmd = "cat /proc/cpuinfo | grep 'name'| uniq"
model_name = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode("utf-8")
model_name = model_name.split(':')[1]
return model_name
@@ -111,6 +120,7 @@ def get_os():
full_cmd = 'cat /etc/os-release | grep -i pretty_name'
pretty_name = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode("utf-8")
pretty_name = pretty_name.split('=')[1].replace('"', '')
return(pretty_name)
@@ -121,6 +131,7 @@ def get_manufacturer():
pretty_name = pretty_name.split(':')[1]
else:
pretty_name = 'Raspberry Pi'
return(pretty_name)
@@ -294,15 +305,26 @@ def bulk_publish_to_mqtt(cpu_load=0, cpu_temp=0, used_space=0, voltage=0, sys_cl
client.disconnect()
def single_discovery_message():
file_path = os.path.dirname(os.path.abspath(__file__))
for line in fileinput.input(file_path + "/config.py", inplace=True):
if line.strip().replace(' ','') == 'discovery_messages=True':
print('# Auto Disabled\ndiscovery_messages = False')
else:
print(line, end='')
if __name__ == '__main__':
# set all monitored values to False in case they are turned off in the config
cpu_load = cpu_temp = used_space = voltage = sys_clock_speed = swap = memory = uptime_days = wifi_signal = wifi_signal_dbm = False
# delay the execution of the script
time.sleep(config.random_delay)
if hasattr(config, 'random_delay'): time.sleep(config.random_delay)
if hasattr(config, 'used_space_path'): used_space_path = config.used_space_path
else: used_space_path = '/'
# collect the monitored values
if config.cpu_load:
cpu_load = check_cpu_load()
@@ -325,7 +347,10 @@ if __name__ == '__main__':
if config.wifi_signal_dbm:
wifi_signal_dbm = check_wifi_signal('dbm')
# Publish messages to MQTT
if config.group_messages:
if hasattr(config, 'group_messages') and config.group_messages:
bulk_publish_to_mqtt(cpu_load, cpu_temp, used_space, voltage, sys_clock_speed, swap, memory, uptime_days, wifi_signal, wifi_signal_dbm)
else:
publish_to_mqtt(cpu_load, cpu_temp, used_space, voltage, sys_clock_speed, swap, memory, uptime_days, wifi_signal, wifi_signal_dbm)
if hasattr(config, 'single_discovery_message') and config.single_discovery_message and config.discovery_messages:
single_discovery_message()