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
pub mod i2c;
pub mod spi;

#[cfg(test)]
pub mod mock_i2c_port;

use core::ops::Shl;

use embedded_hal::blocking::delay::DelayMs;

use crate::debug_println;

/// A method of communicating with the sensor
pub trait SensorInterface {
    /// Interface error type
    type SensorError;

    /// give the sensor interface a chance to set up
    fn setup(&mut self, delay_source: &mut impl DelayMs<u8>) -> Result<(), Self::SensorError>;

    /// Write the whole packet provided
    fn write_packet(&mut self, packet: &[u8]) -> Result<(), Self::SensorError>;

    /// Read the next packet from the sensor
    /// Returns the size of the packet read (up to the size of the slice provided)
    fn read_packet(&mut self, recv_buf: &mut [u8]) -> Result<usize, Self::SensorError>;

    /// Send a packet and receive the response immediately
    fn send_and_receive_packet(
        &mut self,
        send_buf: &[u8],
        recv_buf: &mut [u8],
    ) -> Result<usize, Self::SensorError>;
}

pub use self::i2c::I2cInterface;
pub use self::spi::SpiInterface;

pub(crate) const PACKET_HEADER_LENGTH: usize = 4;
pub(crate) const MAX_CARGO_DATA_LENGTH: usize = 32766 - PACKET_HEADER_LENGTH;

struct SensorCommon {}

impl SensorCommon {
    fn parse_packet_header(packet: &[u8]) -> usize {
        const CONTINUATION_FLAG_MASK: u16 = 0x80;
        const CONTINUATION_FLAG_CLEAR: u16 = !(CONTINUATION_FLAG_MASK);
        if packet.len() < PACKET_HEADER_LENGTH {
            return 0;
        }
        //Bits 14:0 are used to indicate the total number of bytes in the body plus header
        //maximum packet length is ... PACKET_HEADER_LENGTH
        let raw_pack_len: u16 =
            (packet[0] as u16) + ((packet[1] as u16) & CONTINUATION_FLAG_CLEAR).shl(8);

        let mut packet_len: usize = raw_pack_len as usize;
        if packet_len > MAX_CARGO_DATA_LENGTH {
            // we sometimes get garbage packets of [0xFF, 0xFF, 0xFF, 0xFF]
            packet_len = 0; //PACKET_HEADER_LENGTH;
        }

        if 0 == packet_len && 0 != raw_pack_len {
            debug_println!(
                "pph: {:?} {} -> {}",
                &packet[..PACKET_HEADER_LENGTH],
                raw_pack_len,
                packet_len
            );
        } else {
            // hprintln!("pph: {:?} {} ", &packet[..PACKET_HEADER_LENGTH], packet_len).unwrap();
        }

        //let is_continuation:bool = (packet[1] & 0x80) != 0;
        //let chan_num =  packet[2];
        //let seq_num =  packet[3];
        packet_len
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::ops::Shr;

    #[test]
    fn test_parse_packet_header() {
        let short_packet: [u8; 2] = [13, 15];
        let size = SensorCommon::parse_packet_header(&short_packet);
        assert_eq!(0, size, "truncated packet header should have length zero");

        let long_packet_len: usize = 1024;
        let mut raw_packet: [u8; PACKET_HEADER_LENGTH] = [
            (long_packet_len & 0xFF) as u8,
            long_packet_len.shr(8) as u8,
            0,
            0,
        ];
        let size = SensorCommon::parse_packet_header(&raw_packet);
        assert_eq!(size, long_packet_len, "verify > 255 packet length");

        //now set the continuation flag
        raw_packet[1] = 0x80 | raw_packet[1];
        let size = SensorCommon::parse_packet_header(&raw_packet);
        assert_eq!(size, long_packet_len, "verify continuation packet");

        let short_packet_len: usize = 36;
        raw_packet = [
            (short_packet_len & 0xFF) as u8,
            short_packet_len.shr(8) as u8,
            0,
            0,
        ];
        let size = SensorCommon::parse_packet_header(&raw_packet);
        assert_eq!(size, short_packet_len, "verify short packet");

        raw_packet[1] = 0x80 | raw_packet[1];
        let size = SensorCommon::parse_packet_header(&raw_packet);
        assert_eq!(size, short_packet_len, "verify short packet continuation");

        // first (uncontinued) packet
        raw_packet = [20 as u8, 1 as u8, 0, 0];
        let size = SensorCommon::parse_packet_header(&raw_packet);
        assert_eq!(size, 276, "verify > 255 packet length");

        //from actual received packet
        raw_packet = [19 as u8, 129 as u8, 0, 1];
        let size = SensorCommon::parse_packet_header(&raw_packet);
        assert_eq!(size, 275, "verify > 255 packet length");
    }
}