# CoAP

The Constrained Application Protocol (CoAP) is a lightweight web transfer protocol (RFC 7252) designed for constrained nodes and networks. OpenGate **operates exclusively as a CoAP listening server**, receiving incoming request messages (e.g. for data collection or operational responses) sent by devices.

> **Note:** OpenGate does not initiate outbound CoAP requests to external CoAP servers running on devices. All CoAP communications must be initiated by the device towards OpenGate.

## Endpoints

OpenGate listens for CoAP requests on both unencrypted UDP and secure DTLS ports.

| Scheme | Port | Transport / Security | Example URI |
|---|---|---|---|
| `coap://` | `5683` | Unencrypted (UDP) | `coap://api.opengate.es:5683/{meter_id}/{path}` |
| `coaps://` | `30013` | DTLS (Datagram Transport Layer Security) | `coaps://api.opengate.es:30013/{meter_id}/{path}` |

## URI structure and south criteria

All CoAP URIs targeted by devices must place the device's unique identifier (`{meter_id}`) at the beginning of the URL path:

```bash
coap://api.opengate.es:5683/{meter_id}/{path}
coaps://api.opengate.es:30013/{meter_id}/{path}
```

- `{meter_id}`: The unique OpenGate identifier of the device.
- `{path}`: The resource path matched against the `south criteria` in your connector functions.

For example, a connector function configured with `south criteria` = `"coaps://data"` will match requests sent to either `coap://api.opengate.es:5683/{meter_id}/data` or `coaps://api.opengate.es:30013/{meter_id}/data`.

Each manufacturer or device implementation defines its own specific paths (`{path}`) and payload formats (JSON, binary, etc.), which are translated into OpenGate data structures by corresponding connector functions.

## Authentication

Every CoAP request sent to OpenGate must include API key authentication (`X-ApiKey`). In CoAP, authentication is delivered as a **custom CoAP Option**:

| Property | Value |
|---|---|
| **CoAP Option Number** | `2502` |
| **Value Format** | A string containing your OpenGate API key |
| **Requirement** | **Required** |

Requests received without CoAP Option `2502` or with an invalid API key will be rejected by OpenGate as unauthorized.

## Message processing and connector functions

Incoming CoAP requests are evaluated against configured [connector functions](../connector_functions/):

1. **Routing:** The request scheme (`coap://` or `coaps://`) and URI path are matched against the `south criteria` defined in your connector functions.
2. **Execution:** The matching connector function processes the request payload (such as JSON, binary data, etc).
3. **Response:** OpenGate returns a CoAP response to the device. To customize the status code, content format, or body of the response sent back to the device, use the [CoAP JavaScript API](../connector_functions/protocol_apis/coap/).

{{% children sort="weight" %}}

