# `Kuroneko.Gadget`
[🔗](https://github.com/cocoa-xu/kuroneko_gadget/blob/v0.5.0/lib/kuroneko/gadget.ex#L1)

The USB side of a KVM: the functions the target computer sees, on a USB
gadget in configfs.

The system sets the gadget up at boot, often with a network function,
and binds it to the device controller. This process adds functions to it
and changes them:

    Kuroneko.Gadget.configure([:keyboard, :mouse, {:storage, luns: 2}])

## Functions

Linux sorts gadget functions by driver, and so does this library: each
driver is a module of `Kuroneko.Gadget.Function`, whose instances go in
the functions as `{Module, name: "x", ...}` with the module's options.

  * `Kuroneko.Gadget.HID` - keyboards, mice, game controllers, by their
    report descriptors
  * `Kuroneko.Gadget.MassStorage` - drives that hold image files
  * `Kuroneko.Gadget.NCM` - a network adapter
  * `Kuroneko.Gadget.UAC2` - a sound card
  * `Kuroneko.Gadget.ACM` - a serial port
  * `Kuroneko.Gadget.FunctionFS` - a function written in Elixir

A KVM's functions have shorthands, instances of these:

  * `:keyboard` - a boot keyboard
  * `:mouse` - the absolute pointer: `{:mouse, mode: mode}` makes it an
    `:absolute` mouse (the default), a `:stylus` (a pen, for Android and
    iPadOS) or a `:touch` screen
  * `:relative_mouse` - a boot mouse that moves by steps, which BIOS
    setups and games take
  * `:storage` - drives, one by default: `{:storage, luns: 3}` has three
  * `:network` - the USB network, see "The network" below
  * `:microphone` and `:speaker` - the two directions of a sound card,
    with its format: `{:microphone, channels: 1, rates: [44_100, 48_000]}`

`Kuroneko.Gadget.Input` types and points with the keyboard and mice, and
`Kuroneko.Gadget.MassStorage` puts images in the drives.

Each function has a name, its kind's by default (`"keyboard"`, `"mouse"`,
`"relative_mouse"`, `"disk"`, `"usb0"`, `"audio"`), and there may be
several of a kind, each with a name of its own: `[:storage, {:storage,
name: "boot"}]` are two storage devices. Names take letters, digits, `_`
and `-`.

Each function takes endpoints of the device controller, which has few
(`endpoints/1`). With the `:endpoints` option the functions must fit, or
`configure/2` tells how many they need and how many there are.

Changing the functions takes the gadget off the bus and puts it back: the
target sees its devices unplugged and plugged in. With the functions
already there nothing happens, so starting the process again is cheap. A
change the system refuses leaves the functions as they were, and so does
an exception in a function module's `setup`, `update`, `ready` or
`teardown`.

## The network

A network function the system set up has two MAC addresses: the device's,
of its interface, and the target's, of the network adapter the target
sees. `network/1` tells them, and `set_network_addresses/2` changes them
and, with the `:persist` function of the `:network` option, keeps them
for the next boots.

The functions take the network functions in hand only when they include
a `:network`, or always with `manage_networks: true`: then `[:network,
{:network, name: "usb1"}]` keeps the system's network and adds a second,
and a list without the system's network removes it.

## Options

  * `:functions` - the functions to have, none by default. Or
    `{module, function, args}` that returns them, called each time the
    process starts: a restart by its supervisor then sets up those saved
    last, a user's settings say
  * `:name` - the name to register, `Kuroneko.Gadget` by default
  * `:gadget` - the gadget's configfs directory, `default_gadget/0` by
    default
  * `:udc_class` - where the device controllers are, `/sys/class/udc` by
    default
  * `:replug_ms` - how long `replug/2` keeps the gadget off the bus, 1500
    by default
  * `:endpoints` - the controller's endpoints besides endpoint 0, such as
    `%{in: 7, out: 7}`; not checked without it
  * `:max_packet` - the largest packets the controller takes for the
    `:microphone` and the `:speaker`, `%{microphone: 1024, speaker: 1024}`
    by default, the most high speed carries
  * `:names` - what the target calls the functions: `:audio` (the sound
    card), `:microphone`, `:speaker`, and `:storage` (the drives) as
    `{vendor, product, revision}`; the kernel's names by default
  * `:manage_networks` - whether the network functions are always this
    process's, so that functions without one remove them all; by default
    only when the functions include one
  * `:network` - the system's network function:
    * `:function` - its configfs directory, `"ncm.usb0"` by default
    * `:default_addresses` - the addresses `:default` stands for in
      `set_network_addresses/2`, and those the system's network takes
      when it is created anew
    * `:persist` - a function that keeps addresses for the next boots: it
      takes those `set_network_addresses/2` was given, as a map with
      `:device_address`, `:host_address` or both, each an address or
      `:default`, and returns `:ok` or `{:error, reason}`

Board libraries give these for their boards, such as
`NanoKVMGo.USB.gadget_options/1` for the Sipeed NanoKVM-Go.

# `configfs_error`

```elixir
@type configfs_error() :: {:configfs, Path.t(), File.posix()}
```

A configfs or sysfs operation that failed, and the path it failed on.

# `connection_state`

```elixir
@type connection_state() ::
  :not_attached
  | :attached
  | :powered
  | :reconnecting
  | :unauthenticated
  | :default
  | :addressed
  | :configured
  | :suspended
  | :unknown
```

The state of the USB connection, see `connection/1`.

# `endpoints`

```elixir
@type endpoints() :: %{in: non_neg_integer(), out: non_neg_integer()}
```

# `function_spec`

```elixir
@type function_spec() ::
  kind() | {kind(), keyword()} | module() | {module(), keyword()}
```

A function to have: a kind or a module, alone or with options, `:name` among them.

# `instance`

```elixir
@type instance() :: %{
  :kind =&gt; kind() | module(),
  :name =&gt; String.t(),
  optional(atom()) =&gt; term()
}
```

A function on the gadget: its kind and name, and what the kind tells. A
module's function has its settings; a network, its interface and
addresses (see `instances/1`).

# `kept_addresses`

```elixir
@type kept_addresses() :: %{
  optional(:device_address | :host_address) =&gt;
    Kuroneko.Gadget.NCM.address() | :default
}
```

Addresses to keep for the next boots, see the `:network` option.

# `kind`

```elixir
@type kind() ::
  :keyboard
  | :mouse
  | :relative_mouse
  | :storage
  | :network
  | :microphone
  | :speaker
  | :audio
```

A built-in kind of function, a shorthand for an instance of a module.

# `network`

```elixir
@type network() :: %{
  interface: String.t() | nil,
  device_address: Kuroneko.Gadget.NCM.address(),
  host_address: Kuroneko.Gadget.NCM.address(),
  default_addresses: Kuroneko.Gadget.NCM.addresses() | nil
}
```

The USB network, see `network/1`.

# `network_setting`

```elixir
@type network_setting() ::
  {:device_address, Kuroneko.Gadget.NCM.address() | :default}
  | {:host_address, Kuroneko.Gadget.NCM.address() | :default}
  | {:persist, boolean()}
```

What `set_network_addresses/2` takes.

# `option`

```elixir
@type option() ::
  {:functions, [function_spec()] | {module(), atom(), [term()]}}
  | {:name, GenServer.name() | nil}
  | {:gadget, Path.t()}
  | {:udc_class, Path.t()}
  | {:replug_ms, non_neg_integer()}
  | {:endpoints, endpoints()}
  | {:max_packet, %{optional(:microphone | :speaker) =&gt; pos_integer()}}
  | {:names, keyword()}
  | {:manage_networks, boolean()}
  | {:network, keyword()}
```

# `speed`

```elixir
@type speed() ::
  :low_speed
  | :full_speed
  | :high_speed
  | :super_speed
  | :super_speed_plus
  | :unknown
```

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `configure`

```elixir
@spec configure(GenServer.server(), [function_spec()]) :: :ok | {:error, term()}
```

Sets up these functions and removes the others of this process. Network
functions are among them when the list has a `:network`; without one, the
network the system set up stays as it is.

    Kuroneko.Gadget.configure([:keyboard, :mouse, {:storage, luns: 3}])
    Kuroneko.Gadget.configure([:keyboard, :storage, {:storage, name: "boot"}])
    Kuroneko.Gadget.configure([:network, {:network, name: "usb1"}, :keyboard])

# `connection`

```elixir
@spec connection(keyword()) ::
  {:ok, %{state: connection_state(), speed: speed(), controller: String.t()}}
  | {:error, term()}
```

The USB connection to the target: the state the target has put the
device in, the speed and the device controller.

  * `:configured` - the target uses the functions
  * `:suspended` - the target sleeps, or has suspended the port
  * `:not_attached` - no computer at the other end of the cable
  * `:attached`, `:powered`, `:default`, `:addressed` - on the way to
    `:configured`

    Kuroneko.Gadget.connection()
    #=> {:ok, %{state: :configured, speed: :high_speed, controller: "8000000.usb"}}

`{:error, :no_udc}` without a controller bound to the gadget. Takes the
`:gadget` and `:udc_class` options.

# `default_gadget`

```elixir
@spec default_gadget(Path.t()) :: Path.t()
```

The gadget the functions go on when none is given: the only gadget in the
`configfs` gadget directory, `/sys/kernel/config/usb_gadget` by default, else one named
`kuroneko` there.

# `endpoints`

```elixir
@spec endpoints([function_spec()]) :: {:ok, endpoints()} | {:error, term()}
```

The endpoints functions take:

    iex> Kuroneko.Gadget.endpoints([:keyboard, :mouse, {:storage, luns: 4}, :network])
    {:ok, %{in: 5, out: 2}}
    iex> Kuroneko.Gadget.endpoints([:keyboard, Kuroneko.Gadget.ACM])
    {:ok, %{in: 3, out: 1}}

# `endpoints_in_use`

```elixir
@spec endpoints_in_use(GenServer.server()) :: %{
  in: non_neg_integer(),
  out: non_neg_integer(),
  have: endpoints() | nil
}
```

The endpoints the gadget's functions take now, the network functions
this process leaves alone among them, and those the controller has (the
`:endpoints` option, `nil` without it):

    Kuroneko.Gadget.endpoints_in_use()
    #=> %{in: 7, out: 3, have: %{in: 7, out: 7}}

# `function_dir`

```elixir
@spec function_dir(kind() | module(), keyword()) :: Path.t()
```

The configfs directory of a function: a kind's, such as `:keyboard`, or a
module's. Takes `:name`, the kind's or the module's default name without
it, and `:gadget`.

    Kuroneko.Gadget.function_dir(:storage, name: "boot")
    #=> "/sys/kernel/config/usb_gadget/kuroneko/functions/mass_storage.boot"

# `functions`

```elixir
@spec functions(GenServer.server()) :: [kind() | module()]
```

The kinds of the functions of this process on the gadget, each once: a
sound card as its `:microphone`, its `:speaker` or both, a module's
function as its module.

# `instances`

```elixir
@spec instances(GenServer.server()) :: [instance()]
```

The functions on the gadget that this process knows:

    [%{kind: :network, name: "usb0", interface: "usb0",
       device_address: "9e:9f:51:11:f7:b2", host_address: "7a:78:1f:1f:1d:dd"},
     %{kind: :keyboard, name: "keyboard"},
     %{kind: :mouse, name: "mouse", mode: :absolute},
     %{kind: :storage, name: "disk", luns: 2},
     %{kind: :audio, name: "audio", microphone: %{channels: 2, rates: [48_000], sample_bits: 16}, speaker: nil},
     %{kind: Kuroneko.Gadget.ACM, name: "serial", settings: %{}}]

A network's interface is `nil` before the gadget first connects.

# `network`

```elixir
@spec network(GenServer.server()) :: {:ok, network()} | {:error, term()}
```

The USB network the system set up (the `:network` option's function): the
device's interface and its address, the address of the target's end, and
the addresses `:default` stands for (`nil` without them).

    Kuroneko.Gadget.network()
    #=> {:ok, %{interface: "usb0", device_address: "9e:9f:51:11:f7:b2",
    #=>         host_address: "02:12:34:56:78:9a", default_addresses: nil}}

# `replug`

```elixir
@spec replug(GenServer.server()) :: :ok | {:error, term()}
```

Takes the gadget off the USB bus and puts it back, so that the target
finds its devices anew, as if they had been unplugged. A computer reads
what kind of drive a mass storage logical unit is only then. A gadget on
no device controller stays as it is. `{:error, :noproc}` without the
process.

# `set_network_addresses`

```elixir
@spec set_network_addresses(GenServer.server(), [network_setting()]) ::
  :ok | {:error, term()}
```

Gives the USB network other addresses, MAC addresses or `:default`:

  * `:device_address` - the device's
  * `:host_address` - the target's

One left out stays as it is. The gadget leaves the bus and comes back, and
the device's interface goes away and comes back with its address. The
`:network` option's `:persist` function keeps the addresses for the next
boots, unless `persist: false`.

    Kuroneko.Gadget.set_network_addresses(host_address: "02:12:34:56:78:9a")
    Kuroneko.Gadget.set_network_addresses(device_address: :default, host_address: :default)

Refused: an address that is not one (`{:invalid_address, key, value}`)
or is a multicast address (`{:multicast_address, key, value}`), and the
same address at both ends (`:same_addresses`). Addresses set but not kept
give `{:error, {:not_kept, reason}}`.

# `start_link`

```elixir
@spec start_link([option()]) :: GenServer.on_start()
```

Starts the process and sets up the functions. See the module documentation
for the options; invalid ones raise `ArgumentError`.

# `subscribe`

```elixir
@spec subscribe(GenServer.server()) :: {:ok, [kind() | module()]}
```

Sends the caller `{Kuroneko.Gadget, {:functions, kinds}}` each time the
kinds of the functions change, as `functions/1` gives them, until it
unsubscribes or exits. Returns the kinds now. The message comes before
the reply to the `configure/2` that changed them.

# `unsubscribe`

```elixir
@spec unsubscribe(GenServer.server()) :: :ok
```

Stops the messages of `subscribe/1`.

# `validate`

```elixir
@spec validate([function_spec()], [option()]) :: :ok | {:error, term()}
```

Checks functions without setting them up: whether `configure/2` would take
them from a process started with these options (`:max_packet`, `:names`
and `:endpoints` count; `configure/2` also counts the network functions
it leaves alone).

    iex> Kuroneko.Gadget.validate([:keyboard, {:microphone, channels: 1, rates: [44_100]}])
    :ok
    iex> Kuroneko.Gadget.validate([{:speaker, sample_bits: 20}])
    {:error, {:invalid_sample_bits, :speaker, 20}}
    iex> Kuroneko.Gadget.validate([{:storage, luns: 17}])
    {:error, {:invalid_luns, 17}}
    iex> Kuroneko.Gadget.validate([:storage, {:storage, name: "boot"}, :microphone],
    ...>   endpoints: %{in: 2, out: 2})
    {:error, {:not_enough_endpoints, %{need: %{in: 3, out: 2}, have: %{in: 2, out: 2}}}}

# `validate_network_addresses`

```elixir
@spec validate_network_addresses(GenServer.server(), [network_setting()]) ::
  :ok | {:error, term()}
```

Checks addresses as `set_network_addresses/2` would, without setting them.

---

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