# CoAP Endpoint

> For the complete documentation index, see [llms.txt](https://help.1nce.com/llms.txt).

## CoAP Overview

The CoAP Endpoint `coap://coap.os.1nce.com:5683` hosts a POST endpoint on the server root path (`/`) or on the `/data` path if device firmware for some reason cannot send to the root path. The endpoint supports both normal, non-translatable messages and translatable messages by using the Energy Saver, with a safe payload size of up to 1024 bytes.

The POST endpoint takes an optional query parameter (or Location-Query) `t` to provide the MQTT topic used for forwarding this message to an MQTT broker (e.g., `coap://coap-service:5683/?t=topicName` or `coap://coap-service:5683/data?t=topicName`). The Location-Query is limited to 255 characters by the CoAP protocol, hence the topic name itself can only contain up to 253 characters (`t` and `=` also count as characters). The topic name can only contain alphanumeric characters, underscores, and forward slashes (no two slashes in a row). If these constraints are violated, a Bad Request (4.00) will be returned.

If a targeted device could not be found or is in a non-active status, the CoAP service will return an Unauthorized (4.01) response and no further processing of the message will take place.

## CoAP Communication

While using UDP protocol for transport, the CoAP protocol offers reliable communication by using a message confirmation mechanism. Each CoAP request has to be acknowledged by the server, so that the client can be sure that the message was processed:

<div style={{textAlign: 'center'}}>
![CoAP reliable messaging](/img/1nce-os/1nce-os-device-integrator/device-integrator-coap/001.png)
</div>

There are a few key moments that allow reliable communication:

1. To maximize the chance that the message succeeds even in a lossy network environment, CoAP has a retransmission mechanism. The client re-sends the Confirmable message (`CON`) until the Acknowledgement (`ACK`) is received or the *exchange lifetime* has ended. The total exchange lifetime (`EXCHANGE_LIFETIME`) is the time from starting to send a Confirmable message to the time when an acknowledgment is no longer expected.\
   By default, the `EXCHANGE_LIFETIME` value is `247 seconds`.
2. CoAP messages contain a *Message ID* (also known as `MID`) to detect duplicates due to retransmissions. The Message ID has to be unique during the `EXCHANGE_LIFETIME`, so the client's endpoint should be able to specify a unique `MID` value if messages are being sent often enough. Most high-level CoAP clients manage `MID` uniqueness internally, but for low-level clients like the *Quectel BG95* modem, it can be specified in the AT command as `msgID`:

```text
AT+QCOAPHEADER=<clientID>,<msgID>,<mode>[,<TKL>,<token>]
```

There are two examples of the retransmission situation in a single exchange lifetime:

* The client's `CON` message did not reach the server. The client resends the same `CON` message with the same `MID`.
* The server's `ACK` message did not reach the client. The client resends the same `CON` message with the same `MID` (because there was no acknowledgment). The server responds with the same `ACK` because it sees the already-processed `MID` and does not process the request again.

## DTLS Encryption for CoAP

<div style={{textAlign: 'center'}}>
![CoAP DTLS Support](/img/1nce-os/1nce-os-device-integrator/device-integrator-coap/a180cb3-image_4.png)
</div>

Ensuring data is securely sent from a device to 1NCE OS is an important part of gaining customer trust. To provide this secure connection, 1NCE OS has implemented a DTLS layer in the CoAP communication from the device to 1NCE OS. This allows the device to securely send its data without the possibility of messages being read or modified along the way. The diagram above describes this process. First, when the device is ready to onboard itself, it calls the CoAP bootstrapping endpoint. This retrieves the necessary DTLS credentials to onboard securely and initialize the CoAP connection using a PSK.

To utilize DTLS encryption with 1NCE OS, a pre-shared key (PSK) is essential for securing data. This key encrypts and decrypts transmitted data. Devices can connect securely using CoAP with DTLS by accessing the endpoint `coaps://coap.os.1nce.com:5684` or `coaps://coap.os.1nce.com:5684/data`. To retrieve the PSK, send a GET request to `coap://coap.os.1nce.com:5683/bootstrap`. This endpoint will return an existing key, or if none is available, it will generate and provide a new one. Additionally, you can manually set the PSK (in plaintext or HEX format):

* Through the 1NCE OS API endpoint described in [API Explorer](/api/1nce-os/create-pre-shared-device-key/).
* In the 1NCE OS portal Device Integrator when [testing the CoAP endpoint](/docs/1nce-os/1nce-os-device-integrator/device-integrator-test-endpoints#testing-the-endpoint).

### DTLS Bootstrapping Information

The pre-shared key is valid indefinitely. If the bootstrapping is called 5 or more minutes after the last time bootstrapping was called and the pre-shared key was not set previously by the user, the pre-shared key will be regenerated with a new value.

| Name           | Type   | Description                                                         |
| :------------- | :----- | :------------------------------------------------------------------ |
| clientIdentity | string | The ICCID of the device SIM                                         |
| preSharedKey   | string | A pre-shared key the device can use to authenticate itself on DTLS  |
| coapsEndpointUrl | string | The CoAPS endpoint URL for DTLS-encrypted communication           |

**Example response:**

```text
8988280666000000000,aB3dEf7hIjKlMnOp,coaps://coap.os.1nce.com:5684
```

For a complete runnable example of sending CoAP messages (with optional DTLS), see the [CoAP Code Examples](/docs/1nce-os/1nce-os-device-integrator/device-integrator-coap-testing/#sending-coap-messages-post) page.

## Location Endpoint

The Location Endpoint at path `/location` allows IoT devices to retrieve their last known geographic position. The device is identified using the [SIM-as-an-Identity](/docs/1nce-os/1nce-os-device-authenticator/#sim-as-an-identity) principle and supports only the GET method. Non-GET requests receive a CoAP 4.05 (Method Not Allowed) response.

The endpoint is accessible via:

- Plain CoAP: `coap://coap.os.1nce.com:5683/location`
- DTLS-encrypted CoAPS: `coaps://coap.os.1nce.com:5684/location`

### Response Format

A successful request returns a CoAP 2.05 (Content) response with Content-Format set to text/plain. The response body is formatted as CSV with a comma (`,`) delimiter and line-feed (`\n`) line ending. The first row is a header line with column names.

**Response information model:**

| Name | Type | Description |
| :--- | :--- | :---------- |
| Longitude | string (decimal degree numeric) | Geographic longitude of the device |
| Latitude | string (decimal degree numeric) | Geographic latitude of the device |
| Source | string | Identifier of the location source (e.g., [GPS](/docs/1nce-os/1nce-os-device-locator/#gps-location), [CellTower](/docs/1nce-os/1nce-os-device-locator/#cell-tower-location)) |
| SampleTime | string (integer EPOCH seconds) | Timestamp of the location measurement in seconds since 1970-01-01 UTC |

**Example response:**

```text
Longitude,Latitude,Source,SampleTime
13.404954,52.520008,GPS,1700000000
```

### Authentication

The device is authenticated by source IP address lookup. The CoAP server resolves the device identity from the requesting IP address. Devices can access the Location Endpoint via plain CoAP (`coap://coap.os.1nce.com:5683/location`) or securely via DTLS-encrypted CoAPS (`coaps://coap.os.1nce.com:5684/location`) using a PSK obtained from the `/bootstrap` endpoint.

For details on obtaining PSK credentials for DTLS encryption, see the [DTLS Encryption for CoAP](#dtls-encryption-for-coap) section.

If the source IP address does not match any registered device, the endpoint returns CoAP 4.01 (Unauthorized).

### Response Codes

The following table lists all response codes returned by the Location Endpoint:

| Code | Description | Payload |
| :--- | :---------- | :------ |
| 2.05 | Content — Successful response with CSV location data | CSV location data |
| 4.00 | Bad Request — Invalid request | Empty |
| 4.01 | Unauthorized — Device not recognized | Empty |
| 4.03 | Forbidden — Access denied | Empty |
| 4.04 | Not Found — No location data available for the device | Empty |
| 4.05 | Method Not Allowed — Non-GET request sent to the endpoint | Empty |
| 5.02 | Bad Gateway — Service temporarily unavailable | Empty |
| 5.04 | Gateway Timeout — Service did not respond in time | Empty |

All error responses (4.xx and 5.xx) return an empty payload.

For runnable examples of retrieving device location (plain CoAP and DTLS), see the [CoAP Code Examples](/docs/1nce-os/1nce-os-device-integrator/device-integrator-coap-testing/#retrieving-device-location-get) page.

## CoAP Endpoint Information

Base URL: `coap.os.1nce.com`\
Protocol: CoAP(s)\
Supported Paths:

- `/` or `/data` — for telemetry data
- `/bootstrap` — for DTLS bootstrapping
- `/location` — for device location retrieval (GET only)

### Response Codes

| Code | Description | Payload |
| :--- | :---------- | :------ |
| 2.04 | Changed — Telemetry data accepted (`/` and `/data`) | Empty |
| 2.05 | Content — Successful response | `/bootstrap`: CSV with clientIdentity, preSharedKey, coapsEndpointUrl; `/location`: CSV with Longitude, Latitude, Source, SampleTime |
| 4.00 | Bad Request — Invalid request | Empty |
| 4.01 | Unauthorized — Device not recognized | Empty |
| 4.03 | Forbidden — Access denied | Empty |
| 4.04 | Not Found — No data available for the device | Empty |
| 4.05 | Method Not Allowed — Unsupported method for the path | Empty |
| 5.00 | Internal Server Error | Empty |
| 5.02 | Bad Gateway — Service temporarily unavailable | Empty |
| 5.04 | Gateway Timeout — Service did not respond in time | Empty |

## Features & Limitations

### Features

- Reliable messaging via CoAP confirmable messages with retransmission
- DTLS encryption for secure data transport using pre-shared keys
- Telemetry data forwarding to MQTT brokers via topic query parameter
- Device location retrieval via GET `/location` (plain CoAP and DTLS)
- Automatic device authentication via [SIM-as-an-Identity](/docs/1nce-os/1nce-os-device-authenticator/#sim-as-an-identity)

### Limitations

The main limitation of DTLS is the use of the UDP protocol. The major drawbacks of using UDP are having to deal with packet reordering, loss of datagrams, and data larger than the size of a datagram network packet.
