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
#![deny(missing_docs)]
#![doc(html_root_url = "http://arcnmx.github.io/ddc-rs/")]
extern crate mccs;
use std::{iter, fmt, error};
use std::time::Duration;
pub use mccs::{FeatureCode, Value as VcpValue, ValueType as VcpValueType};
pub mod commands;
pub use commands::{Command, CommandResult, TimingMessage};
mod delay;
pub use delay::Delay;
pub const I2C_ADDRESS_EDID: u16 = 0x50;
pub const I2C_ADDRESS_EDID_SEGMENT: u16 = 0x30;
pub const I2C_ADDRESS_DDC_CI: u16 = 0x37;
pub const SUB_ADDRESS_DDC_CI: u8 = 0x51;
pub const DELAY_COMMAND_FAILED_MS: u64 = 40;
pub trait Edid {
type EdidError;
fn read_edid(&mut self, offset: u8, data: &mut [u8]) -> Result<usize, Self::EdidError>;
}
pub trait Eddc: Edid {
fn read_eddc_edid(&mut self, segment: u8, offset: u8, data: &mut [u8]) -> Result<usize, Self::EdidError>;
}
pub trait DdcHost {
type Error;
fn sleep(&mut self) { }
}
pub trait DdcCommandRaw: DdcHost {
fn execute_raw<'a>(&mut self, data: &[u8], out: &'a mut [u8], response_delay: Duration) -> Result<&'a mut [u8], Self::Error>;
}
pub trait DdcCommandRawMarker: DdcCommandRaw where Self::Error: From<ErrorCode> {
fn set_sleep_delay(&mut self, delay: Delay);
}
pub trait DdcCommand: DdcHost {
fn execute<C: Command>(&mut self, command: C) -> Result<C::Ok, Self::Error>;
fn checksum<II: IntoIterator<Item=u8>>(iter: II) -> u8 {
iter.into_iter().fold(0u8, |sum, v| sum ^ v)
}
fn encode_command<'a>(data: &[u8], packet: &'a mut [u8]) -> &'a [u8] {
packet[0] = SUB_ADDRESS_DDC_CI;
packet[1] = 0x80 | data.len() as u8;
packet[2..2 + data.len()].copy_from_slice(data);
packet[2 + data.len()] = Self::checksum(
iter::once((I2C_ADDRESS_DDC_CI as u8) << 1)
.chain(packet[..2 + data.len()].iter().cloned())
);
&packet[..3 + data.len()]
}
}
pub trait DdcCommandMarker: DdcCommand where Self::Error: From<ErrorCode> { }
pub trait Ddc: DdcHost {
fn capabilities_string(&mut self) -> Result<Vec<u8>, Self::Error>;
fn get_vcp_feature(&mut self, code: FeatureCode) -> Result<VcpValue, Self::Error>;
fn set_vcp_feature(&mut self, code: FeatureCode, value: u16) -> Result<(), Self::Error>;
fn save_current_settings(&mut self) -> Result<(), Self::Error>;
fn get_timing_report(&mut self) -> Result<TimingMessage, Self::Error>;
}
pub trait DdcTable: DdcHost {
fn table_read(&mut self, code: FeatureCode) -> Result<Vec<u8>, Self::Error>;
fn table_write(&mut self, code: FeatureCode, offset: u16, value: &[u8]) -> Result<(), Self::Error>;
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ErrorCode {
InvalidOffset,
InvalidLength,
InvalidChecksum,
InvalidOpcode,
InvalidData,
Invalid(String),
}
impl error::Error for ErrorCode {
fn description(&self) -> &str {
match *self {
ErrorCode::InvalidOffset => "invalid offset returned from DDC/CI",
ErrorCode::InvalidLength => "invalid DDC/CI length",
ErrorCode::InvalidChecksum => "DDC/CI checksum mismatch",
ErrorCode::InvalidOpcode => "DDC/CI VCP opcode mismatch",
ErrorCode::InvalidData => "invalid DDC/CI data",
ErrorCode::Invalid(ref s) => s,
}
}
}
impl fmt::Display for ErrorCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", error::Error::description(self))
}
}
impl<D: DdcCommandMarker> Ddc for D where D::Error: From<ErrorCode> {
fn capabilities_string(&mut self) -> Result<Vec<u8>, Self::Error> {
let mut string = Vec::new();
let mut offset = 0;
loop {
let caps = self.execute(commands::CapabilitiesRequest::new(offset))?;
if caps.offset != offset {
return Err(ErrorCode::InvalidOffset.into())
} else if caps.data.is_empty() {
break
}
string.extend(caps.data.iter());
offset += caps.data.len() as u16;
}
Ok(string)
}
fn get_vcp_feature(&mut self, code: FeatureCode) -> Result<VcpValue, Self::Error> {
self.execute(commands::GetVcpFeature::new(code))
}
fn set_vcp_feature(&mut self, code: FeatureCode, value: u16) -> Result<(), Self::Error> {
self.execute(commands::SetVcpFeature::new(code, value))
}
fn save_current_settings(&mut self) -> Result<(), Self::Error> {
self.execute(commands::SaveCurrentSettings)
}
fn get_timing_report(&mut self) -> Result<TimingMessage, Self::Error> {
self.execute(commands::GetTimingReport)
}
}
impl<D: DdcCommandMarker> DdcTable for D where D::Error: From<ErrorCode> {
fn table_read(&mut self, code: FeatureCode) -> Result<Vec<u8>, Self::Error> {
let mut value = Vec::new();
let mut offset = 0;
loop {
let table = self.execute(commands::TableRead::new(code, offset))?;
if table.offset != offset {
return Err(ErrorCode::InvalidOffset.into())
} else if table.bytes().is_empty() {
break
}
value.extend(table.bytes().iter());
offset += table.bytes().len() as u16;
}
Ok(value)
}
fn table_write(&mut self, code: FeatureCode, mut offset: u16, value: &[u8]) -> Result<(), Self::Error> {
for chunk in value.chunks(32) {
self.execute(commands::TableWrite::new(code, offset, chunk))?;
offset += chunk.len() as u16;
}
Ok(())
}
}
impl<D: DdcCommandRawMarker> DdcCommand for D where D::Error: From<ErrorCode> {
fn execute<C: Command>(&mut self, command: C) -> Result<C::Ok, Self::Error> {
let mut data = [0u8; 36];
command.encode(&mut data)?;
let mut out = [0u8; 36 + 3]; let out = &mut out[..C::Ok::MAX_LEN + 3];
let res = self.execute_raw(
&data[..command.len()],
out,
Duration::from_millis(C::DELAY_RESPONSE_MS as _)
);
let res = match res {
Ok(res) => {
self.set_sleep_delay(Delay::new(Duration::from_millis(C::DELAY_COMMAND_MS)));
res
},
Err(e) => {
self.set_sleep_delay(Delay::new(Duration::from_millis(DELAY_COMMAND_FAILED_MS)));
return Err(e)
},
};
let res = C::Ok::decode(res);
if res.is_err() {
self.set_sleep_delay(Delay::new(Duration::from_millis(DELAY_COMMAND_FAILED_MS)));
}
res.map_err(From::from)
}
}