File: cmd_get_sensors.go

package info (click to toggle)
golang-github-bougou-go-ipmi 0.7.8-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,880 kB
  • sloc: makefile: 38
file content (352 lines) | stat: -rw-r--r-- 12,199 bytes parent folder | download
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package ipmi

import (
	"context"
	"fmt"
	"strings"
)

type SensorFilterOption func(sensor *Sensor) bool

func SensorFilterOptionIsThreshold(sensor *Sensor) bool {
	return sensor.IsThreshold()
}

func SensorFilterOptionIsReadingValid(sensor *Sensor) bool {
	return sensor.IsReadingValid()
}

// Sensor is matched if the sensor type of the sensor is one of the given sensor types.
func SensorFilterOptionIsSensorType(sensorTypes ...SensorType) func(sensor *Sensor) bool {
	return func(sensor *Sensor) bool {
		for _, sensorType := range sensorTypes {
			if sensor.SensorType == sensorType {
				return true
			}
		}
		return false
	}
}

// GetSensors retrieves all sensors with their current readings and status.
//
// Filter behavior:
//   - If no filter options are provided, returns all sensors
//   - If filter options are provided, returns only sensors that pass ALL filters (logical AND)
//   - For logical OR filtering, use GetSensorsAny instead
//
// Example usage:
//
//	// Get all fan sensors
//	sensors, err := client.GetSensors(ctx, ipmi.SensorFilterOptionIsSensorType(ipmi.SensorTypeFan))
//
//	// Get all temperature sensors with valid readings
//	sensors, err := client.GetSensors(ctx,
//	    ipmi.SensorFilterOptionIsSensorType(ipmi.SensorTypeTemperature),
//	    ipmi.SensorFilterOptionIsReadingValid)
func (c *Client) GetSensors(ctx context.Context, filterOptions ...SensorFilterOption) ([]*Sensor, error) {
	var out = make([]*Sensor, 0)

	sdrs, err := c.GetSDRs(ctx, SDRRecordTypeFullSensor, SDRRecordTypeCompactSensor)
	if err != nil {
		return nil, fmt.Errorf("GetSDRs failed, err: %w", err)
	}

	for _, sdr := range sdrs {
		sensor, err := c.sdrToSensor(ctx, sdr)
		if err != nil {
			return nil, fmt.Errorf("sdrToSensor failed, err: %w", err)
		}

		var choose bool = true
		for _, filterOption := range filterOptions {
			if !filterOption(sensor) {
				choose = false
				break
			}
		}

		if choose {
			out = append(out, sensor)
		}
	}

	return out, nil
}

// GetSensorsAny retrieves all sensors with their current readings and status.
//
// Filter behavior:
//   - If no filter options are provided, returns all sensors
//   - If filter options are provided, returns sensors that pass ANY of the filters (logical OR)
//   - For logical AND filtering, use GetSensors instead
//
// Example usage:
//
//	// Get sensors that are either temperature or voltage sensors
//	sensors, err := client.GetSensorsAny(ctx,
//	    ipmi.SensorFilterOptionIsSensorType(ipmi.SensorTypeTemperature),
//	    ipmi.SensorFilterOptionIsSensorType(ipmi.SensorTypeVoltage))
func (c *Client) GetSensorsAny(ctx context.Context, filterOptions ...SensorFilterOption) ([]*Sensor, error) {
	var out = make([]*Sensor, 0)

	sdrs, err := c.GetSDRs(ctx, SDRRecordTypeFullSensor, SDRRecordTypeCompactSensor)
	if err != nil {
		return nil, fmt.Errorf("GetSDRs failed, err: %w", err)
	}

	for _, sdr := range sdrs {
		sensor, err := c.sdrToSensor(ctx, sdr)
		if err != nil {
			return nil, fmt.Errorf("sdrToSensor failed, err: %w", err)
		}

		var choose bool = false
		for _, filterOption := range filterOptions {
			if filterOption(sensor) {
				choose = true
				break
			}
		}

		if choose {
			out = append(out, sensor)
		}
	}

	return out, nil
}

// GetSensorByID returns the sensor with current reading and status by specified sensor number.
func (c *Client) GetSensorByID(ctx context.Context, sensorNumber uint8) (*Sensor, error) {
	sdr, err := c.GetSDRBySensorID(ctx, sensorNumber)
	if err != nil {
		return nil, fmt.Errorf("GetSDRBySensorID failed, err: %w", err)
	}

	c.Debug("SDR", sdr)

	sensor, err := c.sdrToSensor(ctx, sdr)
	if err != nil {
		return nil, fmt.Errorf("GetSensorFromSDR failed, err: %w", err)
	}

	return sensor, nil
}

// GetSensorByName returns the sensor with current reading and status by specified sensor name.
func (c *Client) GetSensorByName(ctx context.Context, sensorName string) (*Sensor, error) {
	sdr, err := c.GetSDRBySensorName(ctx, sensorName)
	if err != nil {
		return nil, fmt.Errorf("GetSDRBySensorName failed, err: %w", err)
	}

	c.Debug("SDR", sdr)

	sensor, err := c.sdrToSensor(ctx, sdr)
	if err != nil {
		return nil, fmt.Errorf("GetSensorFromSDR failed, err: %w", err)
	}

	return sensor, nil
}

// sdrToSensor converts a Sensor Data Record (SDR) to a Sensor struct.
//
// Requirements:
//   - Only Full and Compact SDR records are supported
//   - Returns error for other record types
//
// This function performs additional IPMI commands to fetch sensor-related values
// that are not stored in the SDR record, including:
//   - Current sensor readings
//   - Threshold values
//   - Event status
//   - Hysteresis values
//
// The function handles both Full and Compact SDR record types, populating
// the appropriate fields based on the record type.
func (c *Client) sdrToSensor(ctx context.Context, sdr *SDR) (*Sensor, error) {
	if sdr == nil {
		return nil, fmt.Errorf("nil sdr parameter")
	}

	sensor := &Sensor{
		SDRRecordType:    sdr.RecordHeader.RecordType,
		HasAnalogReading: sdr.HasAnalogReading(),
	}

	switch sdr.RecordHeader.RecordType {
	case SDRRecordTypeFullSensor:
		sensor.GeneratorID = sdr.Full.GeneratorID
		sensor.Number = uint8(sdr.Full.SensorNumber)
		sensor.Name = strings.TrimSpace(string(sdr.Full.IDStringBytes))
		sensor.SensorUnit = sdr.Full.SensorUnit
		sensor.SensorType = sdr.Full.SensorType
		sensor.EventReadingType = sdr.Full.SensorEventReadingType
		sensor.SensorInitialization = sdr.Full.SensorInitialization
		sensor.SensorCapabilities = sdr.Full.SensorCapabilities
		sensor.EntityID = sdr.Full.SensorEntityID
		sensor.EntityInstance = sdr.Full.SensorEntityInstance

		sensor.Threshold.LinearizationFunc = sdr.Full.LinearizationFunc
		sensor.Threshold.ReadingFactors = sdr.Full.ReadingFactors

	case SDRRecordTypeCompactSensor:
		sensor.GeneratorID = sdr.Compact.GeneratorID
		sensor.Number = uint8(sdr.Compact.SensorNumber)
		sensor.Name = strings.TrimSpace(string(sdr.Compact.IDStringBytes))
		sensor.SensorUnit = sdr.Compact.SensorUnit
		sensor.SensorType = sdr.Compact.SensorType
		sensor.EventReadingType = sdr.Compact.SensorEventReadingType
		sensor.SensorInitialization = sdr.Compact.SensorInitialization
		sensor.SensorCapabilities = sdr.Compact.SensorCapabilities
		sensor.EntityID = sdr.Compact.SensorEntityID
		sensor.EntityInstance = sdr.Compact.SensorEntityInstance

	default:
		return nil, fmt.Errorf("only support Full or Compact SDR record type, input is %s", sdr.RecordHeader.RecordType)
	}

	sensorOwner := uint8(sensor.GeneratorID.OwnerID())
	sensorLUN := uint8(sensor.GeneratorID.LUN())
	commandContext := &CommandContext{}
	commandContext.
		WithResponderAddr(sensorOwner).
		WithResponderLUN(sensorLUN)

	ctx = WithCommandContext(ctx, commandContext)
	c.Debug("Set CommandContext:", commandContext)

	if err := c.fillSensorReading(ctx, sensor); err != nil {
		return nil, fmt.Errorf("fillSensorReading failed, err: %w", err)
	}

	// notPresent is filled/set by fillSensorReading
	if sensor.notPresent {
		c.Debug(fmt.Sprintf(":( Sensor [%s](%#02x) not present\n", sensor.Name, sensor.Number), "")
		return sensor, nil
	}

	// scanningDisabled is filled/set by fillSensorReading
	if sensor.scanningDisabled {
		// Sensor scanning disabled, no need to continue
		c.Debug(fmt.Sprintf(":( Sensor [%s](%#02x) scanning disabled\n", sensor.Name, sensor.Number), "")
		return sensor, nil
	}

	if !sensor.EventReadingType.IsThreshold() || !sensor.SensorUnit.IsAnalog() {
		if err := c.fillSensorDiscrete(ctx, sensor); err != nil {
			return nil, fmt.Errorf("fillSensorDiscrete failed, err: %w", err)
		}
	} else {
		if err := c.fillSensorThreshold(ctx, sensor); err != nil {
			return nil, fmt.Errorf("fillSensorThreshold failed, err: %w", err)
		}
	}

	return sensor, nil
}

func (c *Client) fillSensorReading(ctx context.Context, sensor *Sensor) error {
	c.Debug("try to fill sensor reading for sensor", sensor.Number)

	readingRes, err := c.GetSensorReading(ctx, sensor.Number)
	c.Debug("GetSensorReading response", readingRes.Format())

	if isErrOfCompletionCodes(err, uint8(CompletionCodeRequestedDataNotPresent)) {
		c.Debugf("GetSensorReading for sensor %#02x failed, err: %s", sensor.Number, err)
		sensor.notPresent = true
		return nil
	}

	if _canIgnoreSensorErr(err) != nil {
		return fmt.Errorf("GetSensorReading for sensor %#02x failed, err: %w", sensor.Number, err)
	}

	sensor.Raw = readingRes.Reading
	sensor.Value = sensor.ConvertReading(readingRes.Reading)

	sensor.scanningDisabled = readingRes.SensorScanningDisabled
	sensor.readingAvailable = !readingRes.ReadingUnavailable
	sensor.Threshold.ThresholdStatus = readingRes.ThresholdStatus()

	sensor.Discrete.ActiveStates = readingRes.ActiveStates
	sensor.Discrete.optionalData1 = readingRes.optionalData1
	sensor.Discrete.optionalData2 = readingRes.optionalData2

	return nil
}

// fillSensorDiscrete retrieves and fills extra sensor attributes for given discrete sensor.
func (c *Client) fillSensorDiscrete(ctx context.Context, sensor *Sensor) error {
	statusRes, err := c.GetSensorEventStatus(ctx, sensor.Number)
	if _canIgnoreSensorErr(err) != nil {
		return fmt.Errorf("GetSensorEventStatus for sensor %#02x failed, err: %w", sensor.Number, err)
	}
	sensor.OccurredEvents = statusRes.SensorEventFlag.TrueEvents()
	return nil
}

// fillSensorThreshold retrieves and fills sensor attributes for given threshold sensor.
func (c *Client) fillSensorThreshold(ctx context.Context, sensor *Sensor) error {
	if sensor.SDRRecordType != SDRRecordTypeFullSensor {
		return nil
	}

	// If Non Linear, should update the ReadingFactors
	// see 36.2 Non-Linear Sensors
	if sensor.Threshold.LinearizationFunc.IsNonLinear() {
		factorsRes, err := c.GetSensorReadingFactors(ctx, sensor.Number, sensor.Raw)
		if _canIgnoreSensorErr(err) != nil {
			return fmt.Errorf("GetSensorReadingFactors for sensor %#02x failed, err: %w", sensor.Number, err)
		}
		sensor.Threshold.ReadingFactors = factorsRes.ReadingFactors
	}

	thresholdRes, err := c.GetSensorThresholds(ctx, sensor.Number)
	if _canIgnoreSensorErr(err) != nil {
		return fmt.Errorf("GetSensorThresholds for sensor %#02x failed, err: %w", sensor.Number, err)
	}
	sensor.Threshold.Mask.UNR.Readable = thresholdRes.UNR_Readable
	sensor.Threshold.Mask.UCR.Readable = thresholdRes.UCR_Readable
	sensor.Threshold.Mask.UNC.Readable = thresholdRes.UNC_Readable
	sensor.Threshold.Mask.LNR.Readable = thresholdRes.LNR_Readable
	sensor.Threshold.Mask.LCR.Readable = thresholdRes.LCR_Readable
	sensor.Threshold.Mask.LNC.Readable = thresholdRes.LNC_Readable
	sensor.Threshold.LNC_Raw = thresholdRes.LNC_Raw
	sensor.Threshold.LCR_Raw = thresholdRes.LCR_Raw
	sensor.Threshold.LNR_Raw = thresholdRes.LNR_Raw
	sensor.Threshold.UNC_Raw = thresholdRes.UNC_Raw
	sensor.Threshold.UCR_Raw = thresholdRes.UCR_Raw
	sensor.Threshold.UNR_Raw = thresholdRes.UNR_Raw
	sensor.Threshold.LNC = sensor.ConvertReading(thresholdRes.LNC_Raw)
	sensor.Threshold.LCR = sensor.ConvertReading(thresholdRes.LCR_Raw)
	sensor.Threshold.LNR = sensor.ConvertReading(thresholdRes.LNR_Raw)
	sensor.Threshold.UNC = sensor.ConvertReading(thresholdRes.UNC_Raw)
	sensor.Threshold.UCR = sensor.ConvertReading(thresholdRes.UCR_Raw)
	sensor.Threshold.UNR = sensor.ConvertReading(thresholdRes.UNR_Raw)

	hysteresisRes, err := c.GetSensorHysteresis(ctx, sensor.Number)
	if _canIgnoreSensorErr(err) != nil {
		return fmt.Errorf("GetSensorHysteresis for sensor %#02x failed, err: %w", sensor.Number, err)
	}
	sensor.Threshold.PositiveHysteresisRaw = hysteresisRes.PositiveRaw
	sensor.Threshold.NegativeHysteresisRaw = hysteresisRes.NegativeRaw
	sensor.Threshold.PositiveHysteresis = sensor.ConvertSensorHysteresis(hysteresisRes.PositiveRaw)
	sensor.Threshold.NegativeHysteresis = sensor.ConvertSensorHysteresis(hysteresisRes.NegativeRaw)

	return nil
}

func _canIgnoreSensorErr(err error) error {
	canIgnore := buildCanIgnoreFn(
		// the following completion codes CAN be ignored,
		// it normally means the sensor device does not exist or the sensor device does not recognize the IPMI command
		uint8(CompletionCodeRequestedDataNotPresent),
		uint8(CompletionCodeIllegalCommand),
		uint8(CompletionCodeInvalidCommand),
	)

	return canIgnore(err)
}