方法1 (maxmaia@Home Assistant Community)
## cpu_info.py
import paho.mqtt.client as mqtt
import subprocess
from requests import post
# function
def connect_msg():
print('Connected to Broker.')
# function
def publish_msg():
print('Message Published.')
# Creating client
MQTT_IP = "192.168.x.x"
MQTT_PORT = "1883"
USER_MQ = "mqtt_user"
PW_MQ = "user_password"
# Retrieving CPUs temperatures from sensor
cpus = subprocess.check_output("sensors|grep 'Core'|awk '{print $3}'| rev | cut -c 4- | rev | cut -c2-", shell=True)
cpus = cpus.decode()
cpus = cpus.splitlines()
# Topics to publih for MQTT
TOPIC_TO_PUBLISH1 = "homeassistant/sensor/pve_system/cpu1"
TOPIC_TO_PUBLISH2 = "homeassistant/sensor/pve_system/cpu2"
TOPIC_TO_PUBLISH3 = "homeassistant/sensor/pve_system/cpu3"
TOPIC_TO_PUBLISH4 = "homeassistant/sensor/pve_system/cpu4"
client = mqtt.Client(client_id='pve_system')
# Connecting callback functions
client.on_connect = connect_msg
client.on_publish = publish_msg
# Connect to broker
client.username_pw_set(USER_MQ,PW_MQ)
client.connect(MQTT_IP,MQTT_PORT)
# if you experience Socket error then replace above statement with following one
# client.connect("192.168.x.x",1883,60)
# Publish a message with topic
client.publish(TOPIC_TO_PUBLISH1,cpus[0])
client.publish(TOPIC_TO_PUBLISH2,cpus[1])
client.publish(TOPIC_TO_PUBLISH3,cpus[2])
client.publish(TOPIC_TO_PUBLISH4,cpus[3])
# Run a loop
client.loop()
- Adapt crontab to run each 30 seconds
* * * * * python /root/work/cpu_info.py
* * * * * ( sleep 30 ; python /root/work/cpu_info.py )
- Add the following to configuration.yaml
mqtt:
sensor:
- name: cpu temperature
state_topic: "homeassistant/sensor/pve_system/cpu1"
unit_of_measurement: "°C"
方法2
nano proxmox_cpu_temp
#!/bin/bash
host = MQTT_IP
user = MQTT_USERNAME
pass = MQTT_PASSWORD
proxmox_name = pve1
temp=$(cat /sys/class/thermal/thermal_zone2/temp')
mosquitto_pub -h $host -u $user -P $pass -t proxmox/$proxmox_name/cpu_temp -m $temp
chmod +x proxmox_cpu_temp
while proxmox_cpu_temp; do sleep 10; done