Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.61 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2. from urllib.parse import urlparse
  3. import time, datetime
  4.  
  5. import json
  6. import os
  7.  
  8. import yaml
  9. import logging
  10.  
  11. import psutil
  12. import threading
  13.  
  14. import re
  15.  
  16. from logging.handlers import RotatingFileHandler
  17.  
  18. class ServerStats():
  19. def __init__(self):
  20. self.stop = False
  21. self.init_logging('Server_Metrics.log')
  22. self.thread = threading.Event()
  23. self.devices = {}
  24. self.devices['cpu_usage'] = {'name':'Cpu Usage', 'device_class':'sensor', 'location':'server', 'unit_of_measurement':'%', 'value_template':'{{ value_json.cpu_usage}}', 'value':0}
  25. self.devices['vmem_usage'] = {'name':'Virtual Memory', 'device_class':'sensor', 'location':'server', 'unit_of_measurement':'%', 'value_template':'{{ value_json.vmem_usage}}', 'value':0}
  26. self.devices['smem_usage'] = {'name':'Swap Memory', 'device_class':'sensor', 'location':'server', 'unit_of_measurement':'%', 'value_template':'{{ value_json.smem_usage}}', 'value':0}
  27. self.read_config()
  28. self.connect_to_mqtt()
  29. self.config_devices()
  30.  
  31.  
  32. self.get_stats()
  33.  
  34. def get_stats(self):
  35. self.devices['cpu_usage']['value'] = psutil.cpu_percent(interval=1)
  36. self.devices['vmem_usage']['value'] = psutil.virtual_memory().percent
  37. self.devices['smem_usage']['value'] = psutil.swap_memory().percent
  38.  
  39. state_topic = '%s/%s/%s/state' % (self.mqtt_topic, 'sensor', 'server')
  40.  
  41. self.mqttc.publish(state_topic, json.dumps({'cpu_usage': self.devices['cpu_usage']['value'],
  42. 'vmem_usage': self.devices['vmem_usage']['value'],
  43. 'smem_usage': self.devices['smem_usage']['value'],}))
  44.  
  45. if not self.thread.is_set() and not self.stop:
  46. threading.Timer(10, self.get_stats).start()
  47.  
  48. def read_config(self):
  49. """read config, filename is config.yml"""
  50. cur_dir = os.path.dirname(os.path.abspath(__file__))
  51. config_file = os.path.join(cur_dir, 'config.yml')
  52. with open(config_file, "r") as f:
  53. config = list(yaml.load_all(f))[0]
  54.  
  55. if 'mqtt' in config:
  56. self.mqtt_path = 'mqtt://%s:%s' % (config['mqtt']['server'], config['mqtt']['port'])
  57. self.mqtt_topic = config['mqtt']['topic']
  58. self.ha_state_topic = config['mqtt']['ha_state_topic']
  59.  
  60. def connect_to_mqtt(self):
  61. self.mqttc = mqtt.Client()
  62.  
  63. url = urlparse(self.mqtt_path)
  64.  
  65. # Connect
  66. self.mqttc.connect(url.hostname, url.port)
  67.  
  68. # Start subscribe, with QoS level 0
  69. self.mqttc.subscribe(self.mqtt_topic + '/server_stats', 0)
  70. self.mqttc.subscribe(self.ha_state_topic, 0)
  71.  
  72. # Assign event callbacks
  73. self.mqttc.on_message = self.on_message
  74.  
  75. def on_message(self, client, obj, msg):
  76. self.logger.debug(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
  77. #isilentllc/switch/garage/set
  78.  
  79. if msg.topic == self.ha_state_topic:
  80. if msg.payload == b'online':
  81. self.logger.debug('Homeassistant boot event, resending Server Metrics device list.')
  82. #Resend device info
  83. self.config_devices()
  84. def init_logging(self, path):
  85. """Start Logging"""
  86. self.logger = logging.getLogger("Server Metrics Log")
  87. self.logger.setLevel(logging.DEBUG)
  88.  
  89. handler = RotatingFileHandler(path, maxBytes=20000, backupCount=1)
  90. self.logger.addHandler(handler)
  91. self.logger.debug('Server Metrics Start Event')
  92.  
  93.  
  94. def config_devices(self):
  95. """Configure devices in home assistant"""
  96.  
  97. state_topic = '%s/%s/%s/state' % (self.mqtt_topic, 'sensor', 'server')
  98.  
  99. for dev, config in self.devices.items():
  100. config_topic = '%s/%s/%s/config' % (self.mqtt_topic, config['device_class'], dev)
  101. config_payload = {#'device_class': config['device_class'],
  102. 'name': config['name'],
  103. 'state_topic': state_topic,
  104. 'unit_of_measurement': config['unit_of_measurement'],
  105. 'value_template': config['value_template'],
  106. }
  107. self.mqttc.publish(config_topic, json.dumps(config_payload))
  108. if __name__ == "__main__":
  109. try:
  110. server_stats = ServerStats()
  111. server_stats.mqttc.loop_start()
  112.  
  113. print('server2mqtt running')
  114.  
  115. while 1:
  116. time.sleep(1)
  117.  
  118. except KeyboardInterrupt:
  119. pass
  120. except Exception as e:
  121. print(e)
  122. finally:
  123. if server_stats:
  124. server_stats.mqttc.loop_stop()
  125. server_stats.stop = True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement