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
use std::sync;

#[derive(Debug)]
struct CapturedTelegram {
    sender: &'static str,
    timestamp: crate::time::Instant,
    index: usize,
    length: usize,
}

#[derive(Debug)]
struct SimulatorBus {
    baudrate: crate::Baudrate,
    telegrams: Vec<CapturedTelegram>,
    stream: Vec<u8>,
    bus_time: crate::time::Instant,
    /// Which master is currently holding the token.  We use this to verify correct timing.
    token_master: Option<u8>,
}

impl SimulatorBus {
    pub fn new(baudrate: crate::Baudrate) -> Self {
        Self {
            baudrate,
            telegrams: Vec::new(),
            stream: Vec::new(),
            bus_time: crate::time::Instant::ZERO,
            token_master: None,
        }
    }

    pub fn current_cursor(&self) -> usize {
        if self.telegrams.len() == 0 {
            return 0;
        }

        let last_telegram = self.telegrams.last().unwrap();

        let last_telegram_tx_duration = self.bus_time - last_telegram.timestamp;
        let last_telegram_tx_bytes =
            usize::try_from(self.baudrate.time_to_bits(last_telegram_tx_duration) / 11).unwrap();

        self.stream.len() - last_telegram.length + last_telegram_tx_bytes.min(last_telegram.length)
    }

    pub fn pending_bytes(&self, cursor: usize) -> &[u8] {
        &self.stream[cursor..self.current_cursor()]
    }

    pub fn is_active(&self) -> Option<&'static str> {
        if self.telegrams.len() == 0 {
            return None;
        }

        let last_telegram = self.telegrams.last().unwrap();

        let last_telegram_tx_duration = self.bus_time - last_telegram.timestamp;
        let last_telegram_tx_bytes =
            usize::try_from(self.baudrate.time_to_bits(last_telegram_tx_duration) / 11).unwrap();

        if last_telegram_tx_bytes < last_telegram.length {
            Some(last_telegram.sender)
        } else {
            None
        }
    }

    pub fn enqueue_telegram(&mut self, name: &'static str, mut data: Vec<u8>) {
        if let Some(active_sender) = self.is_active() {
            panic!(
                "\"{}\" attempted transmission while \"{}\" is still sending!",
                name, active_sender
            );
        }

        // Drop out early if nothing needs to be sent.
        if data.len() == 0 {
            return;
        }

        let sa = if let Some(Ok((decoded, length))) = crate::fdl::Telegram::deserialize(&data) {
            if length != data.len() {
                panic!("Enqueued more than one deserializable telegram? {data:?}");
            }
            match decoded {
                crate::fdl::Telegram::Token(crate::fdl::TokenTelegram { da, sa }) => {
                    self.token_master = Some(da);
                    Some(sa)
                }
                crate::fdl::Telegram::Data(crate::fdl::DataTelegram { h, pdu }) => Some(h.sa),
                _ => None,
            }
        } else {
            None
        };

        let min_delay = if sa == self.token_master {
            // Master must wait 33 bit synchronization pause before transmitting.
            33
        } else {
            // Peripherals must wait at least 11 bit minimum Tsdr before responding.
            11
        };

        // Ensure that at least 11 bit times were left between two consecutive transmissions.
        if let Some(last_telegram_and_pause) = self.telegrams.last().map(|t| {
            t.timestamp
                + self
                    .baudrate
                    .bits_to_time(u32::try_from(t.length).unwrap() * 11 + min_delay)
        }) {
            if self.bus_time < last_telegram_and_pause {
                if sa == self.token_master {
                    panic!(
                        "\"{}\" did not leave synchronization pause before its transmission.",
                        name
                    );
                } else {
                    panic!(
                        "\"{}\" did not leave minimum Tsdr time before its transmission.",
                        name
                    );
                }
            }
        }

        if let Some(Ok(decoded)) = crate::fdl::Telegram::deserialize(&data) {
            log::trace!("{:8} {}: {:?}", self.bus_time.total_micros(), name, decoded);
        } else {
            let data_fmt = data
                .iter()
                .map(|b| format!("0x{:02x}", b))
                .collect::<Vec<_>>()
                .join(" ");
            log::trace!("{:8} {}: {}", self.bus_time.total_micros(), name, data_fmt);
        }

        let telegram = CapturedTelegram {
            sender: name,
            timestamp: self.bus_time,
            index: self.stream.len(),
            length: data.len(),
        };
        self.stream.append(&mut data);
        self.telegrams.push(telegram);
    }

    pub fn print_log(&self) {
        for t in &self.telegrams {
            print!("{:16} {:>12}:", t.timestamp.total_micros(), t.sender);
            for b in &self.stream[t.index..t.index + t.length] {
                print!(" 0x{:02x}", b);
            }
            println!();
        }
    }

    // phy needs to find out what data is still pending for it
    // phy needs to find out whether it is still transmitting
    // phy needs to be able to submit new data
    //
    // bytes should become available with correct timing (i.e. no artificial framing)
    // bus should immediately panic on collision (at least for now)
}

#[derive(Debug)]
pub struct SimulatorPhy {
    bus: sync::Arc<sync::Mutex<SimulatorBus>>,
    cursor: usize,
    name: &'static str,
}

impl SimulatorPhy {
    pub fn new(baudrate: crate::Baudrate, name: &'static str) -> Self {
        Self {
            bus: sync::Arc::new(sync::Mutex::new(SimulatorBus::new(baudrate))),
            cursor: 0,
            name,
        }
    }

    pub fn duplicate(&self, name: &'static str) -> Self {
        Self {
            bus: self.bus.clone(),
            cursor: 0,
            name,
        }
    }

    pub fn set_bus_time(&self, time: crate::time::Instant) {
        self.bus.lock().unwrap().bus_time = time;
    }

    pub fn advance_bus_time(&self, dur: crate::time::Duration) {
        self.bus.lock().unwrap().bus_time += dur;
    }

    pub fn print_bus_log(&self) {
        self.bus.lock().unwrap().print_log();
    }
}

impl crate::phy::ProfibusPhy for SimulatorPhy {
    fn poll_transmission(&mut self, _now: crate::time::Instant) -> bool {
        let bus = self.bus.lock().unwrap();
        bus.is_active() == Some(self.name)
    }

    fn transmit_data<F, R>(&mut self, _now: crate::time::Instant, f: F) -> R
    where
        F: FnOnce(&mut [u8]) -> (usize, R),
    {
        let mut bus = self.bus.lock().unwrap();

        let mut buffer = vec![0u8; 256];
        let (length, res) = f(&mut buffer);
        buffer.truncate(length);

        bus.enqueue_telegram(self.name, buffer);
        self.cursor += length;

        res
    }

    fn receive_data<F, R>(&mut self, now: crate::time::Instant, f: F) -> R
    where
        F: FnOnce(&[u8]) -> (usize, R),
    {
        if self.poll_transmission(now) {
            panic!(
                "\"{}\" attempted to receive while it was still transmitting!",
                self.name
            );
        }

        let bus = self.bus.lock().unwrap();
        let pending = bus.pending_bytes(self.cursor);

        let (drop, res) = f(pending);
        assert!(
            drop <= pending.len(),
            "\"{}\" attempted to drop more pending bytes than it has!",
            self.name,
        );
        self.cursor += drop;

        res
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::phy::ProfibusPhy;

    #[test]
    fn send_and_receive() {
        let mut phy1 = SimulatorPhy::new(crate::Baudrate::B19200, "phy1");
        let mut phy2 = phy1.duplicate("phy2");

        let mut now = crate::time::Instant::ZERO;

        let data = &[0xde, 0xad, 0xbe, 0xef, 0x12, 0x34];
        phy1.transmit_data(now, |buf| {
            buf[..data.len()].copy_from_slice(data);
            (data.len(), ())
        });

        phy2.receive_data(now, |buf| {
            assert_eq!(buf.len(), 0);
            (0, ())
        });

        now += crate::time::Duration::from_millis(100);
        phy1.set_bus_time(now);

        phy2.receive_data(now, |buf| {
            assert_eq!(buf, data);
            (4, ())
        });
        phy2.receive_data(now, |buf| {
            assert_eq!(buf.len(), data.len() - 4);
            (buf.len(), ())
        });

        let data = &[0xc0, 0xff, 0xee];
        phy2.transmit_data(now, |buf| {
            buf[..data.len()].copy_from_slice(data);
            (data.len(), ())
        });

        now += crate::time::Duration::from_millis(100);
        phy1.set_bus_time(now);

        phy1.receive_data(now, |buf| {
            assert_eq!(buf, data);
            (buf.len(), ())
        });

        phy1.print_bus_log();
    }
}