main.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "syscall"
  12. "time"
  13. mqtt "github.com/eclipse/paho.mqtt.golang"
  14. "github.com/spf13/cobra"
  15. )
  16. var (
  17. mqttHost string
  18. mqttPort int
  19. mqttUsername string
  20. mqttPassword string
  21. tempDir string
  22. deviceID string
  23. rootCmd = &cobra.Command{
  24. Use: "ha-gpu-ccd",
  25. Short: "Home Assistant GPU CCD Temperature Monitor",
  26. Long: "Monitor GPU temperatures from Home Assistant MQTT and write to sysfs format files for CCD integration",
  27. Run: run,
  28. }
  29. )
  30. func init() {
  31. rootCmd.PersistentFlags().StringVar(&mqttHost, "mqtt-host", "localhost", "MQTT broker host")
  32. rootCmd.PersistentFlags().IntVar(&mqttPort, "mqtt-port", 1883, "MQTT broker port")
  33. rootCmd.PersistentFlags().StringVar(&mqttUsername, "mqtt-username", "", "MQTT username")
  34. rootCmd.PersistentFlags().StringVar(&mqttPassword, "mqtt-password", "", "MQTT password")
  35. rootCmd.PersistentFlags().StringVar(&tempDir, "temp-dir", "/tmp", "Directory to write temperature files")
  36. rootCmd.PersistentFlags().StringVar(&deviceID, "device-id", "", "Specific GPU device ID to monitor (leave empty to monitor all devices)")
  37. }
  38. func main() {
  39. if err := rootCmd.Execute(); err != nil {
  40. log.Fatal(err)
  41. }
  42. }
  43. func run(cmd *cobra.Command, args []string) {
  44. log.Printf("Starting ha-gpu-ccd")
  45. log.Printf("MQTT Broker: %s:%d", mqttHost, mqttPort)
  46. log.Printf("Temperature directory: %s", tempDir)
  47. log.Printf("MQTT Username: %s", func() string {
  48. if mqttUsername != "" {
  49. return mqttUsername
  50. }
  51. return "(none)"
  52. }())
  53. // Create temp directory if it doesn't exist
  54. if err := os.MkdirAll(tempDir, 0755); err != nil {
  55. log.Fatalf("Failed to create temp directory %s: %v", tempDir, err)
  56. }
  57. // Setup MQTT client
  58. mqttClient := setupMQTTClient()
  59. defer mqttClient.Disconnect(250)
  60. // Setup graceful shutdown
  61. quit := make(chan os.Signal, 1)
  62. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  63. log.Println("Monitoring GPU temperatures from Home Assistant...")
  64. log.Println("Press Ctrl+C to stop")
  65. <-quit
  66. log.Println("Shutting down...")
  67. }
  68. func setupMQTTClient() mqtt.Client {
  69. opts := mqtt.NewClientOptions()
  70. opts.AddBroker(fmt.Sprintf("tcp://%s:%d", mqttHost, mqttPort))
  71. opts.SetClientID("ha-gpu-ccd")
  72. opts.SetUsername(mqttUsername)
  73. opts.SetPassword(mqttPassword)
  74. opts.SetAutoReconnect(true)
  75. opts.SetConnectRetry(true)
  76. opts.SetConnectRetryInterval(10 * time.Second)
  77. opts.SetKeepAlive(60 * time.Second)
  78. opts.SetOnConnectHandler(func(client mqtt.Client) {
  79. log.Println("Connected to MQTT broker")
  80. // Wait a moment for connection to stabilize
  81. go func() {
  82. time.Sleep(1 * time.Second)
  83. // Check if connection is still active
  84. if !client.IsConnected() {
  85. log.Println("Connection lost during stabilization")
  86. return
  87. }
  88. // Subscribe to temperature topics after successful connection
  89. if err := subscribeToTemperatureTopics(client); err != nil {
  90. log.Printf("Failed to subscribe to temperature topics: %v", err)
  91. }
  92. }()
  93. })
  94. opts.SetConnectionLostHandler(func(client mqtt.Client, err error) {
  95. log.Printf("Connection lost to MQTT broker: %v", err)
  96. })
  97. client := mqtt.NewClient(opts)
  98. if token := client.Connect(); token.Wait() && token.Error() != nil {
  99. log.Fatalf("Failed to connect to MQTT broker: %v", token.Error())
  100. }
  101. // Wait a bit to ensure connection is stable
  102. time.Sleep(2 * time.Second)
  103. return client
  104. }
  105. func subscribeToTemperatureTopics(client mqtt.Client) error {
  106. var topic string
  107. if deviceID != "" {
  108. // Subscribe to specific device temperature topic
  109. topic = fmt.Sprintf("homeassistant/sensor/nvml-gpu/%s_temperature/state", deviceID)
  110. } else {
  111. // Subscribe to all GPU temperature topics using # wildcard
  112. topic = "homeassistant/sensor/nvml-gpu/#"
  113. }
  114. // Wait for subscription with timeout
  115. token := client.Subscribe(topic, 1, onTemperatureMessage)
  116. if !token.WaitTimeout(10 * time.Second) {
  117. return fmt.Errorf("timeout waiting for subscription to %s", topic)
  118. }
  119. if token.Error() != nil {
  120. return fmt.Errorf("failed to subscribe to %s: %v", topic, token.Error())
  121. }
  122. log.Printf("Successfully subscribed to: %s", topic)
  123. return nil
  124. }
  125. func onTemperatureMessage(client mqtt.Client, msg mqtt.Message) {
  126. topic := msg.Topic()
  127. payload := string(msg.Payload())
  128. // Filter for temperature topics only
  129. // Topic format: homeassistant/sensor/nvml-gpu/{DEVICEID}_temperature/state
  130. if !strings.Contains(topic, "_temperature/state") {
  131. // Ignore non-temperature topics
  132. return
  133. }
  134. parts := strings.Split(topic, "/")
  135. if len(parts) < 4 {
  136. log.Printf("Invalid topic format: %s", topic)
  137. return
  138. }
  139. deviceSensor := parts[3] // This should be {DEVICEID}_temperature
  140. if !strings.HasSuffix(deviceSensor, "_temperature") {
  141. log.Printf("Topic does not end with _temperature: %s", topic)
  142. return
  143. }
  144. deviceID := strings.TrimSuffix(deviceSensor, "_temperature")
  145. // Parse temperature from JSON payload
  146. var temperature float64
  147. if err := json.Unmarshal([]byte(payload), &temperature); err != nil {
  148. log.Printf("Failed to parse temperature from payload '%s': %v", payload, err)
  149. return
  150. }
  151. log.Printf("Received temperature for device %s: %.1f°C", deviceID, temperature)
  152. // Convert temperature to sysfs format (millidegrees)
  153. // Example: 80.5°C -> 80500
  154. tempMillidegrees := int(temperature * 1000)
  155. // Write to temp file
  156. tempFile := filepath.Join(tempDir, fmt.Sprintf("temp_%s", deviceID))
  157. if err := writeTemperatureFile(tempFile, tempMillidegrees); err != nil {
  158. log.Printf("Failed to write temperature file %s: %v", tempFile, err)
  159. return
  160. }
  161. log.Printf("Updated %s: %d (%.1f°C)", tempFile, tempMillidegrees, temperature)
  162. }
  163. func writeTemperatureFile(filename string, tempMillidegrees int) error {
  164. content := strconv.Itoa(tempMillidegrees)
  165. // Create or overwrite the file
  166. file, err := os.Create(filename)
  167. if err != nil {
  168. return fmt.Errorf("failed to create file: %v", err)
  169. }
  170. defer file.Close()
  171. // Write the temperature value
  172. if _, err := file.WriteString(content); err != nil {
  173. return fmt.Errorf("failed to write temperature: %v", err)
  174. }
  175. return nil
  176. }