x328-proto 0.2.0

Sans-io implementation of the X3.28 field bus protocol.
Documentation
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
//! An implementation of the "node" half of the X3.28 protocol. See [`Node`] for more details.

use crate::ascii::*;
use crate::bcc;
use crate::buffer::Buffer;
use crate::nom_parser::node::{parse_command, CommandToken};
use crate::types::{Address, Parameter, Value};
use core::marker::PhantomData;

/// Bus node (listener/server) part of the X3.28 protocol
///
/// Create a new protocol instance with `Node::new(address)`. The current protocol state can be
/// retrieved by calling `state()`. The [`NodeState`] enum returned contains structs that should
/// be acted upon in order to advance the protocol state machine.
///
/// # Example
///
/// ```
/// use x328_proto::node::{Node, NodeState};
/// # use std::io::{Read, Write, Cursor};
/// # fn connect_serial_interface() -> Result<Cursor<Vec<u8>>,  &'static str>
/// # { Ok(Cursor::new(Vec::new())) }
/// #
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use x328_proto::{addr, Value};
/// let mut node = Node::new(addr(10)); // new protocol instance with address 10
/// let mut serial = connect_serial_interface()?;
/// let mut token = node.reset();
///
/// 'main: loop {
///        # break // this snippet is only for show
///        match node.state(token) {
///            NodeState::ReceiveData(recv) => {
///                let mut buf = [0; 1];
///                if let Ok(len) = serial.read(&mut buf) {
///                    if len == 0 {
///                        break 'main;
///                    }
///                    token = recv.receive_data(&buf[..len]);
///                } else {
///                    break 'main;
///                }
///            }
///
///            NodeState::SendData(mut send) => {
///                serial.write_all(send.send_data()).unwrap();
///            }
///
///            NodeState::ReadParameter(read_command) => {
///                if read_command.parameter() == 3 {
///                    read_command.send_invalid_parameter();
///                } else {
///                    read_command.send_reply_ok(4u16.into());
///                }
///            }
///
///            NodeState::WriteParameter(write_command) => {
///                let param = write_command.parameter();
///                if param == 3 {
///                    write_command.write_error();
///                } else {
///                    write_command.write_ok();
///                }
///            }
///        };
/// }
/// # Ok(()) }
///  ```
#[derive(Debug)]
pub struct Node {
    state: InternalState,
    address: Address,
    read_again_param: Option<(Address, Parameter)>,
    buffer: Buffer,
}

/// The current protocol state, as seen by this node.
pub enum NodeState<'node> {
    /// More data needs to be received from the bus.
    ReceiveData(ReceiveData<'node>),
    /// Data is waiting to be transmitted.
    SendData(SendData<'node>),
    /// A parameter read request.
    ReadParameter(ReadParam<'node>),
    /// A parameter write request.
    WriteParameter(WriteParam<'node>),
}

/// ZST used for making sure that the protocol state always is advancing.
pub struct StateToken(PhantomData<()>);

impl<'a> From<ReceiveData<'a>> for NodeState<'a> {
    fn from(x: ReceiveData<'a>) -> Self {
        Self::ReceiveData(x)
    }
}

impl<'a> From<SendData<'a>> for NodeState<'a> {
    fn from(x: SendData<'a>) -> Self {
        Self::SendData(x)
    }
}

impl<'a> From<WriteParam<'a>> for NodeState<'a> {
    fn from(x: WriteParam<'a>) -> Self {
        Self::WriteParameter(x)
    }
}
impl<'a> From<ReadParam<'a>> for NodeState<'a> {
    fn from(x: ReadParam<'a>) -> Self {
        Self::ReadParameter(x)
    }
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum InternalState {
    Recv,
    Send,
    Read {
        address: Address,
        parameter: Parameter,
    },
    Write {
        address: Address,
        parameter: Parameter,
        value: Value,
    },
}

impl Node {
    /// Create a new protocol instance, accepting commands for the given address.
    /// # Example
    ///
    /// ```
    /// use x328_proto::{addr, node::Node};
    /// let mut node = Node::new(addr(10)); // new protocol instance with address 10
    /// ```
    pub fn new(address: Address) -> Self {
        Self {
            state: InternalState::Recv,
            address,
            read_again_param: None,
            buffer: Buffer::new(),
        }
    }

    /// Obtain a new StateToken by resetting the protocol state to "receive data".
    pub fn reset(&mut self) -> StateToken {
        ReceiveData::from_state(self);
        StateToken(PhantomData)
    }

    /// Returns the current protocol state. Act on the inner structs in order to advance the
    /// protocol state machine.
    pub fn state(&mut self, token: StateToken) -> NodeState<'_> {
        let _ = token;
        match self.state {
            InternalState::Recv => ReceiveData::from_state(self).into(),
            InternalState::Send => SendData::from_state(self).into(),
            InternalState::Read { address, parameter } => {
                ReadParam::from_state(self, address, parameter).into()
            }
            InternalState::Write {
                address,
                parameter,
                value,
            } => WriteParam::from_state(self, address, parameter, value).into(),
        }
    }

    fn set_state(&mut self, state: InternalState) {
        self.state = state;
    }

    /// Do not send any reply to the bus controller. Transition to the idle `ReceiveData` state instead.
    /// You should avoid this, since this will leave the controller waiting until it times out.
    pub fn no_reply(&mut self, _token: StateToken) -> StateToken {
        self.reset()
    }
}

/// "Receive data from bus" state.
#[derive(Debug)]
pub struct ReceiveData<'node> {
    node: &'node mut Node,
}

impl<'node> ReceiveData<'node> {
    fn from_state(node: &'node mut Node) -> Self {
        if node.state != InternalState::Recv {
            node.buffer.clear();
        }
        node.set_state(InternalState::Recv);
        Self { node }
    }

    /// Feed data into the internal buffer, and try to parse the buffer afterwards.
    ///
    /// A state transition will occur if a complete command has been received,
    /// or if a protocol error requires a response to be sent.
    pub fn receive_data(self, data: &[u8]) -> StateToken {
        self.node.buffer.write(data);
        self.parse_buffer();
        StateToken(PhantomData)
    }

    fn parse_buffer(self) -> NodeState<'node> {
        use CommandToken::{
            InvalidPayload, ReadAgain, ReadNext, ReadParameter, ReadPrevious, WriteParameter,
        };

        let buffer = &mut self.node.buffer;

        let (token, read_again_param) = loop {
            match parse_command(buffer.as_ref()) {
                (0, _) => return self.need_data(),
                (consumed, token) => {
                    buffer.consume(consumed);
                    // Take the read again parameter from our state. It would be invalid
                    // to use it for later tokens, that's why it's extracted in the loop.
                    let read_again_param = self.node.read_again_param.take();

                    // We're done parsing when the buffer is empty
                    if buffer.len() == 0 {
                        break (token, read_again_param);
                    }
                }
            };
        };

        match token {
            ReadParameter(address, parameter) if self.for_us(address) => {
                ReadParam::from_state(self.node, address, parameter).into()
            }
            WriteParameter(address, parameter, value) if self.for_us(address) => {
                WriteParam::from_state(self.node, address, parameter, value).into()
            }
            ReadAgain | ReadNext | ReadPrevious if read_again_param.is_some() => {
                let (addr, last_param) = read_again_param.unwrap();
                match match token {
                    ReadPrevious => last_param.prev(),
                    ReadNext => last_param.next(),
                    _ => Some(last_param),
                } {
                    Some(param) => ReadParam::from_state(self.node, addr, param).into(),
                    None => SendData::from_byte(self.node, EOT).into(),
                }
            }
            InvalidPayload(address) if address == self.node.address => self.send_nak(),
            _ => self.need_data(), // This matches NeedData, and read/write to other addresses
        }
    }

    fn send_byte(self, byte: u8) -> NodeState<'node> {
        SendData::from_byte(self.node, byte).into()
    }

    fn need_data(self) -> NodeState<'node> {
        self.into()
    }

    fn send_nak(self) -> NodeState<'node> {
        self.send_byte(NAK)
    }

    fn for_us(&self, address: Address) -> bool {
        self.node.address == address || self.node.address == 0
    }
}

/// "Transmit data on the bus" state.
///
/// Call [`send_data()`](Self::send_data()) to get a reference to the data to be transmitted,
/// and then call [`data_sent()`](Self::data_sent()) when the data has been successfully transmitted.
#[derive(Debug)]
pub struct SendData<'node> {
    node: &'node mut Node,
}

impl<'node> SendData<'node> {
    /// SendData::from_state expects that the node buffer already has been prepared
    fn from_state(node: &'node mut Node) -> Self {
        node.set_state(InternalState::Send);
        Self { node }
    }

    fn from_byte(node: &'node mut Node, byte: u8) -> Self {
        let buf = &mut node.buffer;
        buf.clear();
        buf.push(byte);
        Self::from_state(node)
    }

    /// Returns the data to be sent on the bus, and changes the state to "receive data".
    pub fn send_data(&self) -> &[u8] {
        self.node.buffer.as_ref()
    }

    /// Indicate that the response data has been transmitted successfully, and move to the "receive data" state.
    pub fn data_sent(self) -> StateToken {
        self.node.set_state(InternalState::Recv);
        self.node.buffer.get_ref_and_clear();
        StateToken(PhantomData)
    }
}

/// The "read command received" state. The bus controller expects a reply with the current
/// value of the specified parameter.
#[derive(Debug)]
pub struct ReadParam<'node> {
    node: &'node mut Node,
    address: Address,
    parameter: Parameter,
}

impl<'node> ReadParam<'node> {
    fn from_state(node: &'node mut Node, address: Address, parameter: Parameter) -> Self {
        node.set_state(InternalState::Read { address, parameter });
        Self {
            node,
            address,
            parameter,
        }
    }

    /// Send a response to the master with the value of
    /// the parameter in the read request.
    pub fn send_reply_ok(self, value: Value) -> StateToken {
        self.node.read_again_param = Some((self.address, self.parameter));

        let data = &mut self.node.buffer;
        data.clear();

        data.push(STX);
        data.write(&self.parameter.to_bytes());
        data.write(&value.to_bytes());
        data.push(ETX);
        data.push(bcc(&data.as_ref()[1..]));

        SendData::from_state(self.node);
        StateToken(PhantomData)
    }

    /// Inform the master that the parameter in the request is invalid.
    pub fn send_invalid_parameter(self) -> StateToken {
        SendData::from_byte(self.node, EOT);
        StateToken(PhantomData)
    }

    /// Inform the bus master that the read request failed
    /// for some reason other than invalid parameter number.
    pub fn send_read_failed(self) -> StateToken {
        SendData::from_byte(self.node, NAK);
        StateToken(PhantomData)
    }

    /// Do not send any reply to the master. Transition to the idle `ReceiveData` state instead.
    /// You really shouldn't do this, since this will leave the master waiting until it times out.
    pub fn no_reply(self) -> StateToken {
        ReceiveData::from_state(self.node);
        StateToken(PhantomData)
    }

    /// Get the address the request was sent to.
    pub const fn address(&self) -> Address {
        self.address
    }

    /// The parameter whose value is to be returned.
    pub const fn parameter(&self) -> Parameter {
        self.parameter
    }
}

/// "Write command received" state. The bus controller wants to change the value
/// of the specified parameter.
#[derive(Debug)]
pub struct WriteParam<'node> {
    node: &'node mut Node,
    address: Address,
    parameter: Parameter,
    value: Value,
}

impl<'node> WriteParam<'node> {
    fn from_state(
        node: &'node mut Node,
        address: Address,
        parameter: Parameter,
        value: Value,
    ) -> Self {
        node.set_state(InternalState::Write {
            address,
            parameter,
            value,
        });
        Self {
            node,
            address,
            parameter,
            value,
        }
    }

    /// Inform the bus controller that the parameter value was successfully updated.
    pub fn write_ok(self) -> StateToken {
        SendData::from_byte(self.node, ACK);
        StateToken(PhantomData)
    }

    /// The parameter or value is invalid, or something else is preventing
    /// us from setting the parameter to the given value.
    pub fn write_error(self) -> StateToken {
        SendData::from_byte(self.node, NAK);
        StateToken(PhantomData)
    }

    /// Do not send any reply to the bus controller. Transition to the idle `ReceiveData` state instead.
    /// You should avoid this, since this will leave the controller waiting until it times out.
    pub fn no_reply(self) -> StateToken {
        ReceiveData::from_state(self.node);
        StateToken(PhantomData)
    }

    /// The address the write request was sent to.
    pub const fn address(&self) -> Address {
        self.address
    }

    /// The parameter to be written.
    pub const fn parameter(&self) -> Parameter {
        self.parameter
    }

    /// The new value for the parameter.
    pub const fn value(&self) -> Value {
        self.value
    }
}