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
//! Network ID (NID), Network Access Code (NAC), and Data Unit utilities.

use bits::Dibit;
use buffer;
use coding::bch;
use error::{Result, P25Error};
use stats::{Stats, HasStats};

/// "Digital squelch" NAC field of the NID.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum NetworkAccessCode {
    /// Default P25 NAC.
    Default,
    /// Allows receiver to unsquelch on any NAC (shouldn't be transmitted.)
    ReceiveAny,
    /// Allows repeater to unsquelch/retransmit any NAC (shouldn't be transmitted.)
    RepeatAny,
    /// Custom NAC.
    Other(u16),
}

impl NetworkAccessCode {
    /// Parse 12 bits into a NAC.
    pub fn from_bits(bits: u16) -> NetworkAccessCode {
        use self::NetworkAccessCode::*;

        assert!(bits >> 12 == 0);

        match bits {
            0x293 => Default,
            0xF7E => ReceiveAny,
            0xF7F => RepeatAny,
            _ => Other(bits),
        }
    }

    /// Convert NAC to a 12-bit word.
    pub fn to_bits(self) -> u16 {
        use self::NetworkAccessCode::*;

        match self {
            Default => 0x293,
            ReceiveAny => 0xF7E,
            RepeatAny => 0xF7F,
            Other(bits) => bits,
        }
    }
}

/// Data unit of associated packet.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DataUnit {
    /// Voice header packet.
    VoiceHeader,
    /// Simple terminator packet.
    VoiceSimpleTerminator,
    /// Terminator packet with link control word.
    VoiceLCTerminator,
    /// Link control voice frame group.
    VoiceLCFrameGroup,
    /// Crypto control voice frame group.
    VoiceCCFrameGroup,
    /// Confirmed/Unconfirmed data packet
    DataPacket,
    /// Trunking signalling packet.
    TrunkingSignaling,
}

impl DataUnit {
    /// Parse 4 bits into a data unit type.
    pub fn from_bits(bits: u8) -> Option<DataUnit> {
        use self::DataUnit::*;

        assert!(bits >> 4 == 0);

        match bits {
            0b0000 => Some(VoiceHeader),
            0b0011 => Some(VoiceSimpleTerminator),
            0b1111 => Some(VoiceLCTerminator),
            0b0101 => Some(VoiceLCFrameGroup),
            0b1010 => Some(VoiceCCFrameGroup),
            0b1100 => Some(DataPacket),
            0b0111 => Some(TrunkingSignaling),
            _ => None,
        }
    }

    /// Convert data unit to 4-bit word.
    pub fn to_bits(self) -> u8 {
        use self::DataUnit::*;

        match self {
            VoiceHeader => 0b0000,
            VoiceSimpleTerminator => 0b0011,
            VoiceLCTerminator => 0b1111,
            VoiceLCFrameGroup => 0b0101,
            VoiceCCFrameGroup => 0b1010,
            DataPacket => 0b1100,
            TrunkingSignaling => 0b0111,
        }
    }
}

/// NID word associated with each P25 packet.
#[derive(Copy, Clone, Debug)]
pub struct NetworkId {
    /// NAC field.
    pub access_code: NetworkAccessCode,
    /// DUID field.
    pub data_unit: DataUnit,
}

impl NetworkId {
    /// Create an NID word from the given NAC and data unit.
    pub fn new(access_code: NetworkAccessCode, data_unit: DataUnit) -> NetworkId {
        NetworkId {
            access_code: access_code,
            data_unit: data_unit,
        }
    }

    /// Parse NID from the given 16-bit word.
    pub fn from_bits(bits: u16) -> Option<NetworkId> {
        match DataUnit::from_bits(bits as u8 & 0b1111) {
            Some(du) => Some(NetworkId::new(NetworkAccessCode::from_bits(bits >> 4), du)),
            None => None,
        }
    }

    /// Convert NID to 16-bit representation.
    pub fn to_bits(&self) -> u16 {
        (self.access_code.to_bits() as u16) << 4 | self.data_unit.to_bits() as u16
    }

    /// Encode NID into a byte sequence.
    pub fn encode(&self) -> [u8; 8] {
        let bits = self.to_bits();
        let e = bch::encode(bits);

        [
            (e >> 56) as u8,
            (e >> 48) as u8,
            (e >> 40) as u8,
            (e >> 32) as u8,
            (e >> 24) as u8,
            (e >> 16) as u8,
            (e >> 8) as u8,
            e as u8,
        ]
    }
}

/// State machine that attempts to parse a stream of dibits into an NID word.
pub struct NidReceiver {
    /// Buffered dibits.
    dibits: buffer::Buffer<buffer::NidStorage>,
    stats: Stats,
}

impl HasStats for NidReceiver {
    fn stats(&mut self) -> &mut Stats { &mut self.stats }
}

impl NidReceiver {
    /// Create a new `NidReceiver` with an empty buffer.
    pub fn new() -> NidReceiver {
        NidReceiver {
            dibits: buffer::Buffer::new(buffer::NidStorage::new()),
            stats: Stats::default(),
        }
    }

    /// Feed in a data symbol, possibly producing a decoded NID. Return `Some(Ok(nid))` if
    /// an NID was successfully parsed, `Some(Err(err))` if an unrecoverable error
    /// occurred, and `None` for no event.
    pub fn feed(&mut self, dibit: Dibit) -> Option<Result<NetworkId>> {
        let buf = match self.dibits.feed(dibit) {
            Some(buf) => *buf,
            None => return None,
        };

        let data = match bch::decode(buf) {
            Some((data, err)) => {
                self.stats.record_bch(err);
                data
            },
            None => return Some(Err(P25Error::BchUnrecoverable)),
        };

        match NetworkId::from_bits(data) {
            Some(nid) => Some(Ok(nid)),
            None => Some(Err(P25Error::UnknownNid)),
        }
    }
}