# `ExCEP.Gateway.FileTransfer`

Bidirectional chunked file transfer engine per CSG CEP TS2.2 Section 6.2.

Supports both directions:
- **Pull (`FileGet`, Section 6.2.1)** — Requester sends `FileGet`, receives `FileGetResp`
  metadata (`FileCrc`, `FileSize`, `ModifyTime`), and receives & acknowledges each
  `FileDataTrans` segment until `Continue == "0"`, verifying CRC32 + size.
- **Push (`FileSend`, Section 6.2.2)** — Sender sends `FileSend`, awaits `FileSendResp`,
  then streams `FileDataTrans` chunks stop-and-wait until complete.

# `append_segment`

```elixir
@spec append_segment(map(), ExCEP.Codec.DataAsdu.t()) ::
  {:more, map()} | {:done, binary()} | {:error, atom(), term()}
```

Validates monotonic `FileSegNo` (1, 2, 3, ...) and Base64-decodes a `FileDataTrans` ASDU
into a transfer accumulator map.

Returns:
- `{:more, updated_xfer}` when `Continue == "1"`
- `{:done, content}` when `Continue == "0"` and CRC32 + size match
- `{:error, error_code, reason}` on out-of-order segment, invalid base64, or CRC/size mismatch

# `chunk_binary`

```elixir
@spec chunk_binary(binary(), pos_integer()) :: [{pos_integer(), binary(), boolean()}]
```

Splits binary `content` into chunks of `chunk_size` bytes with 1-based segment numbers
and `has_more?` boolean flags.

# `init_pull_state`

```elixir
@spec init_pull_state(String.t(), ExCEP.Codec.DataAsdu.t()) ::
  {:ok, map()} | {:error, term()}
```

Helper for `FileGet` receiver/reassembler state.
Given a `FileGetResp` ASDU, creates an initial transfer accumulator map.

# `max_file_size`

```elixir
@spec max_file_size() :: pos_integer()
```

Returns the maximum allowed transfer size in bytes (16 MiB).

# `push_binary`

```elixir
@spec push_binary(
  (ExCEP.Codec.DataAsdu.t() -&gt;
     {:ok, ExCEP.Codec.DataAsdu.t()} | {:error, term()}),
  String.t(),
  String.t(),
  binary(),
  keyword()
) :: :ok | {:error, term()}
```

Pushes `content` (binary) to a remote peer using `request_fn.(asdu) :: {:ok, resp} | {:error, reason}`.

# `serve_file_chunks`

```elixir
@spec serve_file_chunks(
  (ExCEP.Codec.DataAsdu.t() -&gt;
     {:ok, ExCEP.Codec.DataAsdu.t()} | {:error, term()}),
  String.t(),
  String.t(),
  binary(),
  keyword()
) :: :ok | {:error, term()}
```

Streams `content` chunks in response to a peer's `FileGet` after `FileGetResp` has been sent.
Uses stop-and-wait per-segment confirmation (`FileDataTrans` -> `FileDataTransResp`).

# `verify_file`

```elixir
@spec verify_file(binary(), term(), term()) :: :ok | {:error, term()}
```

Verifies reassembled file content against expected `FileCrc` and `FileSize` metadata.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
