Advertisement
jarekmor

nvidia-smi_to_mqtt

Feb 8th, 2023 (edited)
911
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2. import subprocess
  3. import json
  4. import csv
  5. import time
  6.  
  7. # MQTT broker and topic information
  8. HOST = "192.168.1.5"
  9. TOPIC = "nvidia/params"
  10. USER = "mqtt"
  11. PASSWD = "mqtt#"
  12.  
  13.     # Capture the output of nvidia-smi
  14. def send_nvidia_mqtt():
  15.     result = subprocess.run(["nvidia-smi", "--query-gpu=index,temperature.gpu,utilization.gpu,memory.total,memory.free,memory.used", "--format=csv"], stdout=subprocess.PIPE)
  16.     nvidia_smi_output = result.stdout.decode('utf-8')  
  17.     reader = csv.DictReader(nvidia_smi_output.splitlines(), delimiter=',')
  18.    
  19.     rows = list()
  20.     for row in reader:
  21.         rows.append(row)
  22.    
  23.     dict_json = dict()
  24.     for item in rows:
  25.         for key, value in item.items():
  26.             try:
  27.                 dict_json[key.strip()] = float(value.strip())
  28.             except ValueError:
  29.                 try:
  30.                     dict_json[key.strip()] = float(value.strip().split(' ')[0])
  31.                 except ValueError:
  32.                     continue
  33.        
  34.     json_object = json.dumps(dict_json, indent=4)
  35.      
  36.     # Create MQTT client and connect to the broker
  37.     client = mqtt.Client()
  38.     client.username_pw_set(USER, PASSWD)
  39.     client.connect(HOST, 1883, 60)
  40.    
  41.     # Publish the JSON data to the desired topic
  42.     client.publish(TOPIC, json_object)
  43.    
  44.     # Disconnect from the broker
  45.     client.disconnect()
  46.  
  47. if __name__ == "__main__":
  48.     while True:
  49.         send_nvidia_mqtt()
  50.         time.sleep(5)       # Wait for 5 seconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement