# Repeater Filtering and Stats

This page covers the forwarding filters and the monitoring commands added to the repeater on the `basic_filtering` branch. It lists every new command, its default, and how to read the stats.

All of these commands work over the serial console and from a remote admin login. The `set` and `get` commands for the filters are accepted by every role (repeater, room server, sensor), but only the repeater acts on them.

---

## Forwarding filters

### Channel hop limits

Limits how far group messages (`GRP_TXT` and `GRP_DATA`) on a given channel are forwarded. Each channel is identified by its 1-byte channel hash.

**Usage:**
- `get channel.hop.limits`
- `set channel.hop.limits <list>`

**Parameters:**
- `list`: comma-separated `hash:hops` pairs, with the hash in hex and the hop count in decimal (0-64). Up to 21 entries.

**Default:** `81:2` (`#wardriving` limited to 2 hops)

**Examples:**
```
set channel.hop.limits 11:6,d9:6,81:2
get channel.hop.limits
```

`get` prints the stored string, followed by one line per entry the repeater actually parsed:
```
> 11:6,d9:6,81:2
11 06
d9 06
81 02
```

**Notes:**
- A packet that has already travelled `hops` or more hops is not forwarded. A limit of `0` stops the repeater forwarding that channel at all.
- Parsing stops at the first malformed entry, but `set` still replies `OK`. Use `get` to check that every entry was parsed.
- If a hash is listed twice, the first entry is used.
- These limits only make a channel stricter. Group packets still have to pass `flood.max` (and `flood.max.data` for `GRP_DATA`).
- The changes apply immediately, without a reboot.

**Finding a channel's hash.** For a hashtag channel:
```
python3 -c 'import hashlib; k=hashlib.sha256(b"#wardriving").digest()[:16]; print(hashlib.sha256(k).hexdigest()[:2])'
```

Known hashes: Public `11`, `#test` `d9`, `#wardriving` `81`.

---

### Allow unknown channels

Controls whether group messages on channels that are not in `channel.hop.limits` are forwarded.

**Usage:**
- `get channels.allow.unknown`
- `set channels.allow.unknown <on|off>`

**Parameters:**
- `on` or `1`: forward unlisted channels (they are still subject to `flood.max`)
- `off` or `0`: drop every group message whose channel is not listed

**Default:** `on`

**Note:** Any other value (such as `true` or `yes`) is rejected with `Error, use on/off`, and the setting is left unchanged.

---

### Advert rate limit

Limits how many flood adverts the repeater forwards from each sender within a sliding time window.

**Usage:**
- `get advert.limit.max`
- `set advert.limit.max <count>`
- `get advert.limit.window`
- `set advert.limit.window <minutes>`

**Parameters:**
- `count`: adverts forwarded per sender per window (1-255)
- `minutes`: window length in minutes (0-65535). `0` turns the limiter off.

**Defaults:** `advert.limit.max` `3`, `advert.limit.window` `4320` (72 hours)

**Example:** allow 2 adverts per sender every 24 hours:
```
set advert.limit.max 2
set advert.limit.window 1440
```

**Notes:**
- Changes take effect on the next advert, without a reboot. Shrinking the window applies at once to adverts already recorded.
- The advert history is kept in RAM only and starts empty on every boot.
- History is a fixed ring of 4096 entries (512 on STM32). On a very busy mesh, or with a high `advert.limit.max`, older entries are overwritten while still inside the window, and the limit quietly loosens.
- To turn the limiter off, set `advert.limit.window 0`. `advert.limit.max` cannot be `0`.

---

## Monitoring commands

These commands are repeater-only. All of their state lives in RAM: it starts empty on every boot, and `clear stats` resets it.

### Airtime utilisation

Shows the share of time spent transmitting and receiving over the last 5, 15 and 60 minutes.

**Usage:**
- `get airtime`

**Example output:**
```
> tx 1.2/0.9/0.7% rx 8.4/6.1/5.5% (5/15/60m, 42m sampled)
```

**Reading it:**
- `tx`: time this node spent transmitting. This figure is accurate.
- `rx`: time spent receiving MeshCore packets that decoded. This is a minimum for how busy the channel is: packets that failed CRC, collisions and other users of the frequency are not counted.
- `Xm sampled`: minutes of history collected since boot or the last `clear stats`. Until a window has filled, its figure is the average over the minutes available. Everything reads `0.0%` for the first minute after either.

---

### Hop-limit drops by payload type

Counts flood packets rejected by any of the hop limits, grouped by payload type. The hop limits are `flood.max`, `flood.max.unscoped`, the per-type `flood.max.*` limits and the 1/2/3-byte hash limits. There is one counter per payload type, not one per limit: a group text dropped by `flood.max` and one dropped by a per-type limit both add to `grptxt`.

**Usage:**
- `get payload.drops`

**Example output:**
```
> advert:812 grptxt:240 path:31 req:4
```

**Notes:**
- Only types with at least one drop are shown. If nothing has been dropped, it prints `> none`.
- Type names: `req resp txt ack advert grptxt grpdata anon path trace multi ctrl raw`. The unused types 0x0C-0x0E show as `0c`, `0d`, `0e`.
- There is no separate total for `flood.max` or any other single limit. To see how many packets one limit is stopping, compare the counts before and after changing that limit.

---

### Filter drops

Counts flood packets rejected by each of the other forwarding filters.

**Usage:**
- `get filter.drops`

**Example output:**
```
> region:15 chan.hops:230 chan.unknown:0 loop:7 advert.rate:96
```

| Counter | Counts packets dropped because |
|---|---|
| `region` | the transport code is unknown, or the region does not allow wildcard flood |
| `chan.hops` | a group packet reached its channel hop limit |
| `chan.unknown` | the channel is not listed and `channels.allow.unknown` is off |
| `loop` | loop detection fired |
| `advert.rate` | the sender went over the advert rate limit |

**Notes:**
- The filters run in order, and each packet is counted only by the first one that drops it. Together, `payload.drops` and `filter.drops` account for every flood packet the repeater declined to forward.
- Packets that are not forwarded because forwarding is switched off (`set repeat off`), and direct-routed packets, are not counted.

---

### Packet pool

Shows how full the repeater's packet buffer pool is, and how many packets were lost because it ran out. The repeater has 32 packet buffers, shared by packets waiting out their receive delay (`rxdelay`), packets waiting to be sent, newly received packets, and packets the repeater creates itself.

**Usage:**
- `get pool`

**Example output:**
```
> free:27/32 min.free:9 rx.drops:0 alloc.fails:0
```

| Field | Meaning |
|---|---|
| `free` | buffers free right now, out of the pool size |
| `min.free` | fewest free buffers seen since boot or the last `clear stats` |
| `rx.drops` | received packets thrown away because no buffer was free |
| `alloc.fails` | packets the repeater tried to create itself (adverts, ACKs, replies) but couldn't, because no buffer was free |

**Notes:**
- `min.free` near `0` means the repeater is close to losing packets, even if `rx.drops` is still `0`.
- Received packets dropped this way are lost before they are scored or checked, so they don't appear in `payload.drops` or `filter.drops`.
- A high `rxdelay` holds weakly received packets in the pool for longer, so on a busy mesh it pushes `min.free` lower. Comparing `get pool` over a busy period at different `rxdelay` values shows whether it matters on your mesh.
- `alloc.fails` also sets bit 0 of `errors` in `stats-core`, as before.

---

### Transmit deferrals

Shows how often the repeater had to wait before sending, because the channel was busy or because it had used up its airtime budget.

**Usage:**
- `get tx.defers`

**Example output:**
```
> busy.receiving:142 forced.sends:0 dc.exhausted:0 dc.timeleft:1800s
```

| Field | Meaning |
|---|---|
| `busy.receiving` | times a send was put off because the radio was busy receiving. The repeater retries 120-480 ms later, so one packet can add several. |
| `forced.sends` | times the channel was busy at every check for 4 seconds and the repeater sent anyway |
| `dc.exhausted` | times sending was held back because the duty-cycle (airtime) budget ran low. Counted once per hold, not once per check. |
| `dc.timeleft` | transmit time left in the duty-cycle budget right now, in seconds |

**Notes:**
- The airtime budget is set by the `af` setting (`get af` / `set af`). At the default of `1.0` the repeater may transmit up to 50% of the time, measured over a one-hour window, so the budget is at most 1800 s. `dc.exhausted` stays at `0` unless the repeater has been transmitting very heavily for a long time.
- A rising `busy.receiving` count means the channel is crowded: the repeater keeps finding someone else on air when it wants to send. Compare it with the `rx` figure in `get airtime`.
- `forced.sends` should normally be `0`. The repeater checks the channel every 120-480 ms while it waits, and a forced send means it found the channel busy at every check for 4 seconds. That takes back-to-back traffic, constant interference on the frequency, or a radio stuck in receive. Forced sends also set bit 1 of `errors` in `stats-core`, as before.

---

## Quick reference

| Command | Values | Default |
|---|---|---|
| `set channel.hop.limits <list>` | `hash:hops,...`, up to 21 entries, hops 0-64 | `81:2` |
| `set channels.allow.unknown <v>` | `on`/`off` (or `1`/`0`) | `on` |
| `set advert.limit.max <n>` | 1-255 | `3` |
| `set advert.limit.window <m>` | 0-65535 minutes, `0` = off | `4320` |
| `get airtime` | | |
| `get payload.drops` | | |
| `get filter.drops` | | |
| `get pool` | | |
| `get tx.defers` | | |
| `clear stats` | also resets the airtime history, both drop counters, the pool stats and the transmit deferral counts | |

Every `set` command has a matching `get`. Settings are saved in `prefs.json`. A repeater upgraded from a build without them starts with the defaults above.

---

## Changed defaults

These apply to new devices, or after the storage is erased. A device that already has saved settings keeps them.

| Setting | New default | Upstream default |
|---|---|---|
| Radio preset (all firmware) | USA/Canada: `910.525,62.5,7,5` | EU/UK narrow: `869.618,62.5,8,5` |
| `loop.detect` (repeater) | `strict` | `off` |
| `path.hash.mode` (repeater) | `2` (3-byte hashes) | `0` (1-byte) |
| `multi.acks` (repeater) | `1` | `0` |

To apply them to an existing repeater:
```
set radio 910.525,62.5,7,5
set loop.detect strict
set path.hash.mode 2
set multi.acks 1
reboot
```

---

## Code changes and fixes

For anyone reviewing the branch.

**New features**
- **Advert limits made configurable:** `AdvertLimiter::allow()` now takes the max and window as arguments. The prefs `advert_limit_max` and `advert_limit_window` are saved as `adv_lim_max` and `adv_lim_win`. The `ADVERT_LIMIT_MAX_PER_WINDOW` and `ADVERT_LIMIT_WINDOW_MINS` defines were removed, and `ADVERT_LIMIT_CACHE_SIZE` remains.
- **Airtime tracking:** the new `examples/simple_repeater/AirtimeWindow.h` keeps 60 one-minute slots of TX and RX airtime, about 500 bytes of RAM. `MyMesh::loop()` feeds it each minute of uptime from the Dispatcher's airtime counters.
- **Drop counters:** `hop_limit_drops[16]` and `filter_drops` were added in `MyMesh`, incremented in `allowPacketForward()`. `isFloodHopLimitExceeded()` in `RoutingPolicy.h` is unchanged.
- **Pool stats:** `Dispatcher` (shared by all firmware) now counts receive-side pool drops and failed `obtainNewPacket()` calls, and tracks the low-water mark of free buffers. Before, a receive-side drop was only a debug message, and a failed allocation only set the `ERR_EVENT_FULL` bit. `resetStats()` clears all three. The repeater's pool size is now the `PACKET_POOL_SIZE` define in `MyMesh.cpp`.
- **Transmit deferrals:** `Dispatcher::checkSend()` counts each busy-channel retry, and each send forced out after 4 seconds of busy channel. Airtime-budget holds are counted once per hold, using a flag that clears when a send starts. All three reset with `resetStats()`.
- **Where the commands are handled:** `get airtime`, `get payload.drops`, `get filter.drops`, `get pool` and `get tx.defers` are handled in `MyMesh::handleCommand()` before CommonCLI, so they don't affect the room server or sensor.

**Bug fixes**
- **`channels.allow.unknown` parsing:** it used `atoi`, so `true` or `on` set it to `0` and silently stopped unknown channels being forwarded. It now accepts only `on`/`off`/`1`/`0`. `get` prints `on`/`off` and matches the full command name.
- **Default channel hop limits never set:** the default `"81:..."` string was copied with `strlen()` of the empty destination buffer, so nothing was copied. It now uses `sizeof()`.
- **Room server and sensor builds:** `parseChannelHopLimits()` and `showChannelHopLimits()` were pure virtual in `CommonCLICallbacks`, so the room server and sensor didn't compile. They now have empty default bodies.
- **Room server `allowPacketForward()`:** a check on the removed `flood_min_path_bytes` field and an extra closing brace were removed. The function had been ending before its `return true;`.

Verified by building `Heltec_v3_repeater`, `Heltec_v3_room_server` and `Heltec_v3_sensor`. Not yet tested on hardware.
