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
//! General low-level receiver for all data units, covering frame synchronization up to
//! symbol decoding.

use baseband::decode::{Decoder, Decider};
use baseband::sync::{SyncCorrelator, SyncDetector, SymbolThresholds, sync_threshold};
use error::{P25Error, Result};
use message::nid;
use message::status::{StreamSymbol, StatusDeinterleaver};
use stats::{Stats, HasStats};

use self::State::*;
use self::StateChange::*;

/// Low-level receiver for decoding samples into symbols and deinterleaving status
/// symbols.
#[derive(Copy, Clone)]
struct SymbolReceiver {
    /// Symbol decoder.
    decoder: Decoder,
    /// Data/Status symbol deinterleaver.
    status: StatusDeinterleaver,
}

impl SymbolReceiver {
    /// Create a new `SymbolReceiver` using the given symbol decoder.
    pub fn new(decoder: Decoder) -> SymbolReceiver {
        SymbolReceiver {
            decoder: decoder,
            status: StatusDeinterleaver::new(),
        }
    }

    /// Feed in a baseband symbol, possibly producing a data or status symbol.
    pub fn feed(&mut self, s: f32) -> Option<StreamSymbol> {
        match self.decoder.feed(s) {
            Some(dibit) => Some(self.status.feed(dibit)),
            None => None,
        }
    }
}


/// An event seen by the low-level receiver.
#[derive(Debug)]
pub enum ReceiverEvent {
    /// Data or status symbol.
    Symbol(StreamSymbol),
    /// Decoded NID information.
    NetworkId(nid::NetworkId),
}

/// Internal state of the state machine.
enum State {
    /// Lock onto frame synchronization.
    Sync(SyncDetector),
    /// Decode NID.
    DecodeNID(SymbolReceiver, nid::NidReceiver),
    /// Decode data and status symbols.
    DecodePacket(SymbolReceiver),
    /// Flush pads at end of packet.
    FlushPads(SymbolReceiver),
}

/// Action the state machine should take.
enum StateChange {
    /// Change to the given state.
    Change(State),
    /// Propagate the given event.
    Event(ReceiverEvent),
    /// Change to the given state and propagate the given event.
    EventChange(ReceiverEvent, State),
    /// Propagate the given error.
    Error(P25Error),
    /// No action necessary.
    NoChange,
}

impl State {
    /// Initial synchronization state.
    pub fn sync() -> State { Sync(SyncDetector::new()) }

    /// Initial NID decode state.
    pub fn decode_nid(decoder: Decoder) -> State {
        DecodeNID(SymbolReceiver::new(decoder), nid::NidReceiver::new())
    }

    /// Initial symbol decode state.
    pub fn decode_packet(recv: SymbolReceiver) -> State { DecodePacket(recv) }

    /// Initial flush padding state.
    pub fn flush_pads(recv: SymbolReceiver) -> State { FlushPads(recv) }
}

/// State machine for low-level data unit reception.
///
/// The state machine consumes baseband samples and performs the following steps common to
/// all data units:
///
/// 1. Track average power of input signal
/// 2. Lock onto frame synchronization
/// 3. Deinterleave status symbols
/// 4. Decode NID information
/// 5. Decode dibit symbols until stopped
pub struct DataUnitReceiver {
    /// Current state.
    state: State,
    /// Tracks input signal power and frame synchronization statistics.
    corr: SyncCorrelator,
    /// Tracks thresholds for symbol decisions.
    symthresh: SymbolThresholds,
    stats: Stats,
}

impl DataUnitReceiver {
    /// Create a new `DataUnitReceiver` in the initial reception state.
    pub fn new() -> DataUnitReceiver {
        DataUnitReceiver {
            state: State::sync(),
            corr: SyncCorrelator::new(),
            symthresh: SymbolThresholds::new(),
            stats: Stats::default(),
        }
    }

    /// Flush any remaining padding symbols at the end of the current packet, and reenter
    /// the frame synchronization state afterwards.
    pub fn flush_pads(&mut self) {
        match self.state {
            DecodePacket(recv) => self.state = State::flush_pads(recv),
            Sync(_) => {},
            _ => panic!("not decoding a packet"),
        }
    }

    /// Force the receiver into frame synchronization.
    pub fn resync(&mut self) { self.state = State::sync(); }

    /// Determine the next action to take based on the given sample.
    fn handle(&mut self, s: f32) -> StateChange {
        // Continuously track the input signal power.
        let (corrpow, sigpow) = self.corr.feed(s);

        match self.state {
            Sync(ref mut sync) => if sync.detect(corrpow, sync_threshold(sigpow)) {
                let history = self.corr.history();
                let (p, m, n) = self.symthresh.thresholds(&history);

                println!("pos:{} mid:{} neg:{}", p, m, n);

                Change(State::decode_nid(Decoder::new(Decider::new(p, m, n))))
            } else {
                NoChange
            },
            DecodeNID(ref mut recv, ref mut nidrecv) => {
                let dibit = match recv.feed(s) {
                    Some(StreamSymbol::Data(d)) => d,
                    Some(s) => return Event(ReceiverEvent::Symbol(s)),
                    None => return NoChange,
                };

                match nidrecv.feed(dibit) {
                    Some(Ok(nid)) => {
                        self.stats.merge(nidrecv);
                        EventChange(ReceiverEvent::NetworkId(nid),
                                    State::decode_packet(*recv))
                    },
                    Some(Err(e)) => Error(e),
                    None => NoChange,
                }
            },
            DecodePacket(ref mut recv) => match recv.feed(s) {
                Some(x) => Event(ReceiverEvent::Symbol(x)),
                None => NoChange,
            },
            FlushPads(ref mut recv) => match recv.feed(s) {
                // According to the spec, the stream is padded until the next status
                // symbol boundary.
                Some(StreamSymbol::Status(_)) => Change(State::sync()),
                _ => NoChange,
            },
        }
    }

    /// Feed in a baseband symbol, possibly producing a receiver event. Return
    /// `Some(Ok(event))` for any normal event, `Some(Err(err))` for any error, and `None`
    /// if no event occurred.
    pub fn feed(&mut self, s: f32) -> Option<Result<ReceiverEvent>> {
        match self.handle(s) {
            Change(state) => {
                self.state = state;
                None
            },
            Event(event) => Some(Ok(event)),
            EventChange(event, state) => {
                self.state = state;
                Some(Ok(event))
            },
            Error(err) => Some(Err(err)),
            NoChange => None,
        }
    }
}

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