-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserial.rs
More file actions
479 lines (413 loc) · 16.3 KB
/
Copy pathserial.rs
File metadata and controls
479 lines (413 loc) · 16.3 KB
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use crate::{BatterySource, ErrorType, RtcSource, ThermalSource, Threshold, common};
use battery_service_interface::{BixFixedStrings, BstReturn, Btp};
use battery_service_relay::{AcpiBatteryRequest, AcpiBatteryResponse};
use embedded_services::relay::{MessageSerializationError, SerializableMessage};
use serialport::SerialPort;
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use thermal_service_relay::{ThermalRequest, ThermalResponse};
use time_alarm_service_interface::{
AcpiTimerId, AcpiTimestamp, AlarmExpiredWakePolicy, AlarmTimerSeconds, TimeAlarmDeviceCapabilities, TimerStatus,
};
use time_alarm_service_relay::{AcpiTimeAlarmRequest, AcpiTimeAlarmResponse};
/// Errors produced by serial data source operations.
#[derive(Debug)]
pub enum Error {
/// Serial port I/O error (read, write, flush, clear)
Io(String),
/// Serial protocol framing error (invalid MCTP packet length, buffer overflow, etc.)
Protocol(String),
/// Message serialization or deserialization error
Serialization(String),
/// Response had an unexpected format
UnexpectedResponse,
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(msg) => write!(f, "serial I/O error: {msg}"),
Self::Protocol(msg) => write!(f, "serial protocol error: {msg}"),
Self::Serialization(msg) => write!(f, "serialization error: {msg}"),
Self::UnexpectedResponse => write!(f, "unexpected response"),
}
}
}
impl std::error::Error for Error {}
impl crate::Error for Error {
fn kind(&self) -> crate::ErrorKind {
match self {
Self::Io(_) => crate::ErrorKind::Io,
Self::Protocol(_) => crate::ErrorKind::Protocol,
Self::Serialization(_) => crate::ErrorKind::Serialization,
Self::UnexpectedResponse => crate::ErrorKind::UnexpectedResponse,
}
}
}
// If it took longer than a second to receive a response, something is definitely wrong
const READ_TIMEOUT: Duration = Duration::from_millis(1000);
const SMBUS_HEADER_SZ: usize = 4;
const SMBUS_LEN_IDX: usize = 2;
const MCTP_FLAGS_IDX: usize = 7;
const MCTP_HEADER_SZ: usize = 5;
const ODP_HEADER_SZ: usize = 2; // This does not include the 2 byte command code
const HEADER_SZ: usize = SMBUS_HEADER_SZ + MCTP_HEADER_SZ + ODP_HEADER_SZ;
const CMD_CODE_SZ: usize = 2;
const BUFFER_SZ: usize = 256;
const MCTP_MAX_PACKET_LEN: usize = 69;
const THERMAL_VAR_LEN: u16 = 4;
const BATTERY_INSTANCE: u8 = 0;
#[derive(Clone, Copy, Debug)]
enum Destination {
Battery,
Thermal,
TimeAlarm,
}
impl From<Destination> for u8 {
fn from(dst: Destination) -> Self {
match dst {
Destination::Battery => 0x08,
Destination::Thermal => 0x09,
Destination::TimeAlarm => 0x0B,
}
}
}
fn prepend_headers(buffer: &mut [u8], dst: Destination, payload_sz: usize) -> Result<(), Error> {
let packet_len = MCTP_HEADER_SZ + ODP_HEADER_SZ + payload_sz;
let packet_len_u8: u8 = packet_len
.try_into()
.map_err(|_| Error::Protocol(format!("Packet length {packet_len} exceeds u8 maximum")))?;
// SMBUS
buffer[0] = 0x2;
buffer[1] = 0xF;
buffer[2] = packet_len_u8;
buffer[3] = 0x1;
// MCTP
buffer[4] = 0x1;
buffer[5] = dst.into();
buffer[6] = 0x80;
buffer[7] = 0xD3;
buffer[8] = 0x7D; // Additional MCTP message type header byte
// ODP
buffer[9] = 1 << 1;
buffer[10] = dst.into();
Ok(())
}
fn append_cmd(
to: &mut [u8],
from: impl SerializableMessage,
cmd_code: u16,
) -> Result<usize, MessageSerializationError> {
to[HEADER_SZ..HEADER_SZ + CMD_CODE_SZ].copy_from_slice(&cmd_code.to_be_bytes());
let payload_sz = from.serialize(&mut to[HEADER_SZ + CMD_CODE_SZ..])?;
Ok(payload_sz + CMD_CODE_SZ)
}
#[derive(Clone)]
pub struct Serial {
port: Arc<Mutex<Box<dyn SerialPort>>>,
sensor_instance: u8,
fan_instance: u8,
}
impl Serial {
pub fn new(
path: &str,
baud_rate: u32,
flow_control: bool,
sensor_instance: u8,
fan_instance: u8,
) -> Result<Self, Error> {
let flow_control = if flow_control {
serialport::FlowControl::Hardware
} else {
serialport::FlowControl::None
};
let port = serialport::new(path, baud_rate)
.flow_control(flow_control)
.timeout(READ_TIMEOUT)
.open()
.map_err(|e| Error::Io(format!("{e}")))?;
port.clear(serialport::ClearBuffer::All)
.map_err(|e| Error::Io(format!("{e}")))?;
Ok(Self {
port: Arc::new(Mutex::new(port)),
sensor_instance,
fan_instance,
})
}
}
impl Serial {
fn send<REQ: SerializableMessage + Copy, RESP: SerializableMessage>(
&self,
dst: Destination,
request: REQ,
) -> Result<RESP, Error> {
let mut buffer = [0u8; BUFFER_SZ];
// Serialize command into buffer
let request_sz = append_cmd(&mut buffer, request, request.discriminant())
.map_err(|e| Error::Serialization(format!("{e:?}")))?;
// NOTE: The `mctp-rs` crate does not appear to support serializing requests and deserializing
// responses (only the opposite), so we have to do manual serialization until that is changed.
// And now that we know request size, serialize headers into beginning of buffer
prepend_headers(&mut buffer, dst, request_sz)?;
let mut port = self
.port
.lock()
.map_err(|_| Error::Io("serial port mutex poisoned".into()))?;
// Write entire request packet
// We first clear the input buffer in case there's anything left over if we had to bail out
// early on previous call due to error
port.clear(serialport::ClearBuffer::Input)
.map_err(|e| Error::Io(format!("{e:?}")))?;
port.write_all(&buffer[..HEADER_SZ + request_sz])
.map_err(|e| Error::Io(format!("{e:?}")))?;
let pec = smbus_pec::pec(&buffer[..HEADER_SZ + request_sz]);
port.write_all(&[pec]).map_err(|e| Error::Io(format!("{e:?}")))?;
port.flush().map_err(|e| Error::Io(format!("{e:?}")))?;
// Read response packets
let mut response_buf = Vec::new();
let mut cmd_code = 0;
loop {
// Wait for SMBUS header from response packet
let mut buffer = [0u8; BUFFER_SZ];
port.read_exact(&mut buffer[..SMBUS_HEADER_SZ])
.map_err(|e| Error::Io(format!("{e:?}")))?;
// Get the length of the response and do a sanity check on it
let len = buffer[SMBUS_LEN_IDX] as usize;
if !(MCTP_HEADER_SZ..=MCTP_MAX_PACKET_LEN).contains(&len) {
return Err(Error::Protocol(format!("Invalid MCTP packet length {len}")));
}
// Then read rest of packet
let packet_slice = buffer
.get_mut(SMBUS_HEADER_SZ..SMBUS_HEADER_SZ + len)
.ok_or_else(|| Error::Protocol("Response does not fit in buffer".into()))?;
port.read_exact(packet_slice).map_err(|e| Error::Io(format!("{e:?}")))?;
let mut pec_buf = [0u8; 1];
port.read_exact(&mut pec_buf).map_err(|e| Error::Io(format!("{e:?}")))?;
let computed = smbus_pec::pec(&buffer[..SMBUS_HEADER_SZ + len]);
if pec_buf[0] != computed {
return Err(Error::Protocol(format!(
"PEC mismatch: received {:#04x}, computed {:#04x}",
pec_buf[0], computed
)));
}
let flags = buffer[MCTP_FLAGS_IDX];
// If this is a SOM packet, skip ODP header (we don't use it) and grab the command code/discriminant
let payload_start_idx = if flags & 0x80 != 0 {
cmd_code = u16::from_be_bytes(
buffer[HEADER_SZ..HEADER_SZ + CMD_CODE_SZ]
.try_into()
.expect("CMD_CODE_SZ must equal 2"),
);
HEADER_SZ + CMD_CODE_SZ
} else {
// -1 because non-SOM packets don't have the message type byte
SMBUS_HEADER_SZ + MCTP_HEADER_SZ - 1
};
// Append the payload to the reassembly buffer
let data_slice = &buffer[payload_start_idx..SMBUS_HEADER_SZ + len];
response_buf.extend_from_slice(data_slice);
// If this is EOM packet, we are done
if flags & 0x40 != 0 {
break;
}
}
RESP::deserialize(cmd_code, &response_buf).map_err(|e| Error::Serialization(format!("deserialization: {e:?}")))
}
fn thermal_get_var(&self, guid: uuid::Uuid) -> Result<f64, Error> {
let request = ThermalRequest::ThermalGetVarRequest {
instance_id: self.fan_instance,
len: THERMAL_VAR_LEN,
var_uuid: guid.to_bytes_le(),
};
let response = self.send(Destination::Thermal, request)?;
if let ThermalResponse::ThermalGetVarResponse { val } = response {
Ok(val as f64)
} else {
Err(Error::UnexpectedResponse)
}
}
fn thermal_set_var(&self, guid: uuid::Uuid, raw: u32) -> Result<(), Error> {
let request = ThermalRequest::ThermalSetVarRequest {
instance_id: self.fan_instance,
len: THERMAL_VAR_LEN,
var_uuid: guid.to_bytes_le(),
set_var: raw,
};
let response = self.send(Destination::Thermal, request)?;
if let ThermalResponse::ThermalSetVarResponse = response {
Ok(())
} else {
Err(Error::UnexpectedResponse)
}
}
}
impl ErrorType for Serial {
type Error = Error;
}
impl ThermalSource for Serial {
fn get_temperature(&self) -> Result<f64, Self::Error> {
let request = ThermalRequest::ThermalGetTmpRequest {
instance_id: self.sensor_instance,
};
let response = self.send(Destination::Thermal, request)?;
if let ThermalResponse::ThermalGetTmpResponse { temperature } = response {
Ok(common::dk_to_c(temperature.0))
} else {
Err(Error::UnexpectedResponse)
}
}
fn get_rpm(&self) -> Result<f64, Self::Error> {
self.thermal_get_var(common::guid::FAN_CURRENT_RPM)
}
fn get_min_rpm(&self) -> Result<f64, Self::Error> {
self.thermal_get_var(common::guid::FAN_MIN_RPM)
}
fn get_max_rpm(&self) -> Result<f64, Self::Error> {
self.thermal_get_var(common::guid::FAN_MAX_RPM)
}
fn get_threshold(&self, threshold: Threshold) -> Result<f64, Self::Error> {
let raw = match threshold {
Threshold::On => self.thermal_get_var(common::guid::FAN_ON_TEMP),
Threshold::Ramping => self.thermal_get_var(common::guid::FAN_RAMP_TEMP),
Threshold::Max => self.thermal_get_var(common::guid::FAN_MAX_TEMP),
}?;
Ok(common::dk_to_c(raw as u32))
}
fn set_threshold(&self, threshold: Threshold, value: f64) -> Result<(), Self::Error> {
let guid = match threshold {
Threshold::On => common::guid::FAN_ON_TEMP,
Threshold::Ramping => common::guid::FAN_RAMP_TEMP,
Threshold::Max => common::guid::FAN_MAX_TEMP,
};
self.thermal_set_var(guid, common::c_to_dk(value))
}
fn set_rpm(&self, rpm: f64) -> Result<(), Self::Error> {
self.thermal_set_var(common::guid::FAN_CURRENT_RPM, rpm as u32)
}
}
impl BatterySource for Serial {
fn get_bst(&self) -> Result<BstReturn, Self::Error> {
let request = AcpiBatteryRequest::GetBst {
battery_id: BATTERY_INSTANCE,
};
let response = self.send(Destination::Battery, request)?;
if let AcpiBatteryResponse::GetBst { bst } = response {
Ok(bst)
} else {
Err(Error::UnexpectedResponse)
}
}
fn get_bix(&self) -> Result<BixFixedStrings, Self::Error> {
let request = AcpiBatteryRequest::GetBix {
battery_id: BATTERY_INSTANCE,
};
let response = self.send(Destination::Battery, request)?;
if let AcpiBatteryResponse::GetBix { bix } = response {
Ok(bix)
} else {
Err(Error::UnexpectedResponse)
}
}
fn set_btp(&self, trip_point: u32) -> Result<(), Self::Error> {
let request = AcpiBatteryRequest::SetBtp {
battery_id: BATTERY_INSTANCE,
btp: Btp { trip_point },
};
let response = self.send(Destination::Battery, request)?;
if matches!(response, AcpiBatteryResponse::SetBtp {}) {
Ok(())
} else {
Err(Error::UnexpectedResponse)
}
}
}
impl RtcSource for Serial {
fn get_capabilities(&self) -> Result<TimeAlarmDeviceCapabilities, Self::Error> {
let request = AcpiTimeAlarmRequest::GetCapabilities;
let response = self.send(Destination::TimeAlarm, request)?;
if let AcpiTimeAlarmResponse::Capabilities(capabilities) = response {
Ok(capabilities)
} else {
Err(Error::UnexpectedResponse)
}
}
fn get_real_time(&self) -> Result<AcpiTimestamp, Self::Error> {
let request = AcpiTimeAlarmRequest::GetRealTime;
let response = self.send(Destination::TimeAlarm, request)?;
if let AcpiTimeAlarmResponse::RealTime(timestamp) = response {
Ok(timestamp)
} else {
Err(Error::UnexpectedResponse)
}
}
fn get_wake_status(&self, timer_id: AcpiTimerId) -> Result<TimerStatus, Self::Error> {
let request = AcpiTimeAlarmRequest::GetWakeStatus(timer_id);
let response = self.send(Destination::TimeAlarm, request)?;
if let AcpiTimeAlarmResponse::TimerStatus(status) = response {
Ok(status)
} else {
Err(Error::UnexpectedResponse)
}
}
fn get_expired_timer_wake_policy(&self, timer_id: AcpiTimerId) -> Result<AlarmExpiredWakePolicy, Self::Error> {
let request = AcpiTimeAlarmRequest::GetExpiredTimerPolicy(timer_id);
let response = self.send(Destination::TimeAlarm, request)?;
if let AcpiTimeAlarmResponse::WakePolicy(policy) = response {
Ok(policy)
} else {
Err(Error::UnexpectedResponse)
}
}
fn get_timer_value(&self, timer_id: AcpiTimerId) -> Result<AlarmTimerSeconds, Self::Error> {
let request = AcpiTimeAlarmRequest::GetTimerValue(timer_id);
let response = self.send(Destination::TimeAlarm, request)?;
if let AcpiTimeAlarmResponse::TimerSeconds(seconds) = response {
Ok(seconds)
} else {
Err(Error::UnexpectedResponse)
}
}
fn set_real_time(&self, timestamp: AcpiTimestamp) -> Result<(), Self::Error> {
let response = self.send(Destination::TimeAlarm, AcpiTimeAlarmRequest::SetRealTime(timestamp))?;
if matches!(response, AcpiTimeAlarmResponse::OkNoData) {
Ok(())
} else {
Err(Error::UnexpectedResponse)
}
}
fn set_timer_value(&self, timer_id: AcpiTimerId, value: AlarmTimerSeconds) -> Result<(), Self::Error> {
let response = self.send(
Destination::TimeAlarm,
AcpiTimeAlarmRequest::SetTimerValue(timer_id, value),
)?;
if matches!(response, AcpiTimeAlarmResponse::OkNoData) {
Ok(())
} else {
Err(Error::UnexpectedResponse)
}
}
fn set_expired_timer_wake_policy(
&self,
timer_id: AcpiTimerId,
policy: AlarmExpiredWakePolicy,
) -> Result<(), Self::Error> {
let response = self.send(
Destination::TimeAlarm,
AcpiTimeAlarmRequest::SetExpiredTimerPolicy(timer_id, policy),
)?;
if matches!(response, AcpiTimeAlarmResponse::OkNoData) {
Ok(())
} else {
Err(Error::UnexpectedResponse)
}
}
fn clear_wake_status(&self, timer_id: AcpiTimerId) -> Result<(), Self::Error> {
let response = self.send(Destination::TimeAlarm, AcpiTimeAlarmRequest::ClearWakeStatus(timer_id))?;
if matches!(response, AcpiTimeAlarmResponse::OkNoData) {
Ok(())
} else {
Err(Error::UnexpectedResponse)
}
}
}