# K230 OTA API Reference

## Overview

K230 provides an independent OTA HAL interface for streaming the `kdimg` image to the OTA device node.

- User mode HAL header file: `src/rtsmart/libs/rtsmart_hal/components/k230_ota/k230_ota.h`
- User mode HAL implementation: `src/rtsmart/libs/rtsmart_hal/components/k230_ota/k230_ota.c`
- Reference example: `src/rtsmart/examples/peripheral/ota/test_ota.c`

## Main interface

### `k230_ota_create`

```c
k230_ota_t* k230_ota_create(void);
```

Create an OTA session and open the OTA device.

- Return value: A non-empty handle is returned on success; `NULL` is returned on failure.

### `k230_ota_update`

```c
int k230_ota_update(k230_ota_t* ctx, const void* buf, size_t size);
```

Write a piece of image data to the OTA device, suitable for cyclic block calling.

- `ctx`: Session handle returned by `k230_ota_create()`
- `buf`: Data buffer to be written
- `size`: Number of bytes written
- Return value: `0` is returned on success; negative value is returned on failure

### `k230_ota_destroy`

```c
void k230_ota_destroy(k230_ota_t* ctx);
```

Destroy the OTA session, release resources and shut down the device.

### `k230_ota_write_file`

```c
int k230_ota_write_file(const char* image_path, size_t chunk_size);
```

Convenient interface: Directly write the image file into OTA devices in `chunk_size` chunks.

- `image_path`: Mirror path
- `chunk_size`: Size per write (bytes)
- Return value: `0` is returned on success; negative value is returned on failure

## Recommended usage process

1. Prepare and verify the image file (it is recommended to check the size, format and integrity first)
1. Call `k230_ota_create()` to establish a session
1. Read the image in a loop and call `k230_ota_update()` to write in blocks
1. Call `k230_ota_destroy()` to close the session
1. Restart the device for the new firmware to take effect

## Minimal example

```c
#include "k230_ota.h"
#include <fcntl.h>
#include <unistd.h>

int ota_from_file(const char *path)
{
    int fd = -1;
    int ret = -1;
    char buf[64 * 1024];
    ssize_t rd;
    k230_ota_t *ctx = NULL;

    fd = open(path, O_RDONLY, 0);
    if (fd < 0)
        return -1;

    ctx = k230_ota_create();
    if (!ctx)
        goto out;

    while ((rd = read(fd, buf, sizeof(buf))) > 0) {
        if (k230_ota_update(ctx, buf, (size_t)rd) < 0)
            goto out;
    }

    ret = (rd < 0) ? -1 : 0;

out:
    if (ctx)
        k230_ota_destroy(ctx);
    if (fd >= 0)
        close(fd);
    return ret;
}
```

## Things to note

1. Avoid power outages or forced restarts during the OTA process.
1. It is recommended to complete image verification and version check before upgrading.
1. Network download capability can be implemented in combination with [NetMgmt API documentation](./netmgmt.md).
