summaryrefslogtreecommitdiffstats
path: root/devices/temp_nix.go
blob: 79fc53b0c6a3994d3aaf299346a37049b5656b29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//go:build linux || darwin
// +build linux darwin

package devices

import (
	"log"

	"github.com/anatol/smart.go"
	"github.com/jaypipes/ghw"
	"github.com/shirou/gopsutil/host"
)

var smDevices map[string]smart.Device

func init() {
	devs() // Populate the sensorMap
	RegisterStartup(startBlock)
	RegisterTemp(getTemps)
	RegisterDeviceList(Temperatures, devs, defs)
	RegisterShutdown(endBlock)
}

func startBlock(vars map[string]string) error {
	smDevices = make(map[string]smart.Device)

	block, err := ghw.Block()
	if err != nil {
		log.Printf("error getting block device info: %s", err)
		return err
	}
	for _, disk := range block.Disks {
		dev, err := smart.Open("/dev/" + disk.Name)
		if err != nil {
			log.Printf("error opening smart info for %s: %s", disk.Name, err)
			continue
		}
		smDevices[disk.Name+"_"+disk.Model] = dev
	}
	return nil
}

func endBlock() error {
	for name, dev := range smDevices {
		err := dev.Close()
		if err != nil {
			log.Printf("error closing device %s: %s", name, err)
		}
	}
	return nil
}

func getTemps(temps map[string]int) map[string]error {
	sensors, err := host.SensorsTemperatures()
	if err != nil {
		if _, ok := err.(*host.Warnings); ok {
			// ignore warnings
		} else {
			return map[string]error{"gopsutil host": err}
		}
	}
	for _, sensor := range sensors {
		label := sensorMap[sensor.SensorKey]
		if _, ok := temps[label]; ok {
			temps[label] = int(sensor.Temperature)
		}
	}

	for name, dev := range smDevices {
		attr, err := dev.ReadGenericAttributes()
		if err != nil {
			log.Printf("error getting smart data for %s: %s", name, err)
			continue
		}
		temps[name] = int(attr.Temperature)
	}
	return nil
}

// Optimization to avoid string manipulation every update
var sensorMap map[string]string