The Home Assistant container on the Raspberry Pi uses the command sensor to obtain and display information such as CPU temperature and memory usage

foreword

In Home Assistant, the sensor entity object sensor can obtain object information, such as: custom light sensor, human body sensor, etc.

Among them, there is a special sensor: Command Line Sensor(command line sensor), using it, scripts such as Python and Shell can be activated, and then data can be obtained through scripts.

For example: This article uses Shell and Python scripts to obtain the CPU temperature, CPU usage, storage usage, and memory usage of the Raspberry Pi:
final effect
This article reference: https://bbs.hassbian.com/thread-8475-1-1 .html

Cooperating with third-party front-end card plug-ins, the effect can be achieved:
card effect

premise

The premise of using it is very simple. We need a Raspberry Pi with Home Assistant installed. If your Raspberry Pi does not have Home Assistant Core or Supervised installed, you can refer to the tutorial:

If the Raspberry Pi is installed with the System version, this tutorial can also be used theoretically.

Shell to obtain information

First of all, we need to know, how to use Shell to get the information of Raspberry Pi? Very simple, simple cat, freeand df, topcommands can be completed.

CPU temperature

If we need to get the CPU temperature, we can get it in the temporary partition cache file:

# 获取树莓派温度
cat /sys/class/thermal/thermal_zone0/temp

Raspberry Pi temperature
The temperature here needs to be divided by 1000 to be the real temperature in Celsius; therefore, my CPU temperature here is 45.764摄氏度.

CPU usage

CPU usage is a bit of a hassle, the final command is:

top -n1 | awk '/Cpu\(s\):/ {print $2}'

CPU usage get command
Let's dismantle them one by one, first of all, topthe command, which is used to obtain system information:
top command
plus -n1the representative cancels the interactive mode, and only obtains an output refresh. Cooperate with awkfield interception.

memory usage

In terms of memory, it is even simpler, just use freethe command directly and cooperate with the "Three Musketeers" awk:

free | awk '/Mem/ {print $2,$3,$4}'

free with awk

disk usage

Disk usage is very simple, and the information is clear to everyone. only need to:

df -h

get disk usage

Python package

After that, we use the above Shell command to call it using a Python script. You only need to use the Python ospackage and cooperate with os.popenthe method to run the Shell command. for example:

# 获取CPU使用率
import os
info = os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()
print(info)

Get CPU usage
To expand, all the information in the previous chapter is obtained and encapsulated as a JSON object:

import os
import json

# Return CPU temperature as a float
def getCPUtemperature():
    f = os.popen("cat /sys/class/thermal/thermal_zone0/temp")
    temp = int(f.readline().strip())/1000
    return round(temp, 1)

# Return RAM information (unit=MB) in a list
# Index 0: total RAM
# Index 1: used RAM
# Index 2: free RAM
def getRAMinfo():
    f = os.popen("free | awk '/Mem/ {print $2,$3,$4}'")
    info = f.readline().split()
    info = [round(int(i)/1024, 1) for i in info]
    return info

# Return % of CPU used by user as float
def getCPUinfo():
    # Docker外部(真实环境内)
    ## info = os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()
    # Docker内部(Home Assistant Docker内)
    info = os.popen("top -n1 | awk '/CPU:/ {print $2}'").readline().strip()
    if info=="":
        info=0
    return info

# Return information about disk space as a list (unit included)
# Index 0: total disk space
# Index 1: used disk space
# Index 2: remaining disk space
# Index 3: percentage of disk used
def getDiskinfo():
    f = os.popen("df -h /")
    info = f.readlines()[1].split()[1:5]
    return info

if __name__ == '__main__':
    RaspiInfo = {
    
    }
    RaspiInfo['CPUtemp'] = getCPUtemperature()
    RaspiInfo['RAMinfo'] = getRAMinfo()
    RaspiInfo['DISKinfo'] = getDiskinfo()
    RaspiInfo['CPUuse'] = getCPUinfo()
    # 必须转化为标准 JSON 格式
    print(json.dumps(RaspiInfo))

Get it running:
operation result
After that, we're calling on Home Assistant.

It should be noted that the acquisition of CPU usage uses the Docker environment in Home Assistant; so the CPU obtained by the top command is different from the CPU information obtained by the real environment.

Command Senior

Refer to the official document: https://www.home-assistant.io/integrations/sensor.command_line/

We need to create a Command Line sensor. In order to avoid the core configuration file of Home Assistant being too long, I use the YAML external reference method to refer to a separate configuration file for appending: After that, create the Command Line sensor configuration
citation external placement
:

- platform: command_line
  name: RaspInfo
  scan_interval: 60
  command: "python3 /config/scripts/queryRaspi.py" # 脚本路径问题参考下面注意事项
  json_attributes: # 键名可为大小写
    - RAMinfo
    - DISKinfo
    - CPUuse
    - CPUtemp

- platform: template
  # 传感器列表
  sensors:
    # 实体名称:小写,下划线
    cpu_temp:
      # (可选)在前端显示的传感器昵称
      friendly_name: "CPU Temperature"
      # (可选)传感器数值的单位
      unit_of_measurement: '℃'
      #(必须)定义一个获取传感器状态(数值)的模板
      # 这里就是获取上面定义的命令行传感器实体 sensor.raspinfo 的相应属性值,注意大小写
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'CPUtemp')}}"
    # 以下配置类似,不再赘述
    cpu_used:
      friendly_name: "CPU Used"
      # unit_of_measurement: '%'
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'CPUuse')}}"
    ram_total:
      friendly_name: "RAM total"
      unit_of_measurement: 'MB'
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'RAMinfo')[0]}}"
    ram_used:
      friendly_name: "RAM used"
      unit_of_measurement: 'MB'
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'RAMinfo')[1]}}"
    ram_free:
      friendly_name: "RAM free"
      unit_of_measurement: 'MB'
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'RAMinfo')[2]}}"
    disk_total:
      friendly_name: "DISK total"
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'DISKinfo')[0]}}"
    disk_used:
      friendly_name: "DISK used"
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'DISKinfo')[1]}}"
    disk_left:
      friendly_name: "DISK left"
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'DISKinfo')[2]}}"
    disk_percentage:
      friendly_name: "DISK percentage"
      value_template: "{
    
    {state_attr('sensor.raspinfo', 'DISKinfo')[3]}}"

sensor configuration

Among them: platform-commandfor the Python script we just wrote, pay attention to your own file address.

After saving, restart the Home Assistant on the Raspberry Pi, and you can see the effect:
sensor
at this point, you can actually add a display card. However, I see that other people will also combine multiple sensors into a group, which is indeed more convenient to find the data of physical sensor objects, so let's do it too.

Group

Indeed, Group is similar to SQL group by. After using Group to group, multiple unconnected objects can be combined into a related one. For example:
Group
very simple, we edit a group according to the official document: https://www.home-assistant.io/integrations/group
object.

Just like before, to keep my config file from getting too long:
quote
Afterwards, create groups.yamlthe file, and add the following:

raspinfo:
  name: 树莓派
  entities:
    - sensor.cpu_used
    - sensor.cpu_temp
    - sensor.ram_total
    - sensor.ram_used
    - sensor.ram_free
    - sensor.disk_total
    - sensor.disk_used
    - sensor.disk_left
    - sensor.disk_percentage

Save and restart Home Assistant.

END

In fact, topthe command itself consumes the resources of the Raspberry Pi. If you do not need to monitor the Raspberry Pi frequently, you can try not to monitor the CPU usage.

Card effect, you can refer to the GitHub project: https://github.com/RomRider/apexcharts-card

Guess you like

Origin blog.csdn.net/weixin_43890033/article/details/124289532