Advertisement
Masoko

Python 2 mqtt cpu tem, cpu load and disk usage monitor

Nov 19th, 2017
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | None | 0 0
  1. # Python 2 script to monitor cpu load, cpu temperature and free space,
  2. # on a Raspberry Pi computer and publish the data to a MQTT server.
  3.  
  4. from __future__ import division
  5. import subprocess, time, socket, os
  6. import paho.mqtt.client as paho
  7.  
  8. #get device host name - used in mqtt topic
  9. hostname = socket.gethostname()
  10.  
  11. #mqtt server configuration
  12. mqtt_host = "mqtt_host"
  13. mqtt_user = "mqtt_user"
  14. mqtt_password = "mqtt_password"
  15. mqtt_port = "1883"
  16.  
  17. def check_used_space(path):
  18.     st = os.statvfs(path)
  19.     free_space = st.f_bavail * st.f_frsize
  20.     total_space = st.f_blocks * st.f_frsize
  21.     used_space = int(100 - ((free_space / total_space) * 100))
  22.     return used_space
  23.  
  24. def check_cpu_load():
  25.     #bash command to get cpu load from uptime command
  26.     p = subprocess.Popen("uptime", shell=True, stdout=subprocess.PIPE).communicate()[0]
  27.     cpu_load = p.split("average:")[1].split(",")[0].replace(' ', '')
  28.     return cpu_load
  29.    
  30. def check_cpu_temp():
  31.     #bash command to get rpi cpu temp
  32.     full_cmd = "/opt/vc/bin/vcgencmd measure_temp"
  33.     p = subprocess.Popen(full_cmd, shell=True, stdout=subprocess.PIPE).communicate()[0]
  34.     cpu_temp = p.replace('\n', ' ').replace('\r', '').split("=")[1].split("'")[0]
  35.     return cpu_temp
  36.  
  37. if __name__ == '__main__':
  38.     #check cpu load
  39.     cpu_load = check_cpu_load()
  40.     #check cpu temp
  41.     cpu_temp = check_cpu_temp()
  42.     #check used space
  43.     used_space = check_used_space('/')
  44.    
  45.     #connect to mqtt server
  46.     client = paho.Client()
  47.     client.username_pw_set(mqtt_user, mqtt_password)
  48.     client.connect(mqtt_host, mqtt_port)
  49.  
  50.     #publish cpu load mqtt message
  51.     client.publish(hostname+"/cpuload", cpu_load, qos=1)
  52.     time.sleep(1)
  53.    
  54.     #publish cpu temperature mqtt message
  55.     client.publish(hostname+"/cputemp", cpu_temp, qos=1)       
  56.     time.sleep(1)
  57.    
  58.     #publish used space mqtt message
  59.     client.publish(hostname+"/diskusage", used_space, qos=1)
  60.    
  61.     #disconect from mqtt server
  62.     client.disconnect()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement