Skip to content

Kotlin SDK

adamo-android is the Adamo SDK for Android, in Kotlin. An app can operate a robot (video, audio, control, state) or be the robot (camera, microphone, control, recording). The networking is the same Rust code as the Python, Rust and C SDKs; Kotlin adds coroutines, Flows, typed messages and Android’s own codecs.

Package com.adamohq.sdk. Requires Android 9 (API 28). The AAR includes native code for arm64-v8a and x86_64; an app needs neither Rust nor the NDK.

The AAR is built from adamo-tech/adamo and attached to each SDK release on GitHub Releases as adamo-android-<version>-maven.tar.gz, a Maven repository holding the AAR, its POM and sources. Unpack it into your project:

Terminal window
mkdir -p libs/adamo && tar -xzf adamo-android-<version>-maven.tar.gz -C libs/adamo
settings.gradle.kts
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("libs/adamo") }
}
}
// app/build.gradle.kts
dependencies {
implementation("com.adamohq:adamo-android:<version>")
}

The release also carries the bare adamo-android-<version>.aar, for builds that add org.jetbrains.kotlinx:kotlinx-coroutines-android themselves. To build from source, see the README.

The library declares the INTERNET permission. Your app declares and requests CAMERA and RECORD_AUDIO if it streams them.

  • Every suspend function and Flow is safe to call from the main dispatcher. Blocking work runs on Dispatchers.IO.
  • close() and the methods named …Blocking block. Call them off the main thread.
  • Flows are cold. Each collector owns a subscription that closes when collection ends, and a flow completes normally if its session is closed. Nothing published before collection starts is replayed.
  • Closing a Session closes every publisher, subscription, token, store and track opened from it. close() is idempotent everywhere.
  • Cancelling a coroutine does not abort a request already on the wire. Receive loops notice cancellation within 250 ms.
  • Keys are relative to the organization: robot/topic, never adamo/<org>/….
  • The SDK’s own diagnostics go to logcat under the tag adamo.

Failures from the SDK throw AdamoException, with the SDK’s explanation as its message and a category:

enum class ErrorCategory { AUTH, NETWORK, TIMEOUT, INVALID, VIDEO, AUDIO, FFI, INTERNAL, NOT_IMPLEMENTED, UNKNOWN }

Using a closed object throws IllegalStateException. Invalid Kotlin arguments throw IllegalArgumentException.


A connection to an Adamo organization.

val session = Session.connect(apiKey)
try {
session.put("arm/notes", "hello".toByteArray())
session.subscribe("arm/state/**").collect { sample ->
println("${sample.key}: ${sample.payload.decodeToString()}")
}
} finally {
withContext(NonCancellable + Dispatchers.IO) { session.close() }
}
FunctionUse
Session.connect(apiKey, protocol = Protocol.QUIC)An operator or application.
Session.connectDirect(apiKey, robot)As connect, then moves onto a direct path to robot when it offers one. Falls back to the relay; check isDirect.
Session.connectLocal(address, pairingKey)Straight to a robot on the local network. No account or internet.
Session.openRobot(apiKey, protocol, directFor, direct)A robot’s session. Prefer Robot.open.
Session.listenLocal(robot, options)An offline robot session that operators join with connectLocal.

Protocol is QUIC, TCP or UDP. LocalOptions(port, pairingKey, stunServers) configures listening; every field is optional.

PropertyMeaning
organizationThe organization the session belongs to.
isDirectTrue when the session reaches the robot directly rather than through a relay.
localPairingKey, localPortSet when the session listens for local operators. Never send the key to a cloud API.
localRobotThe robot a direct session is connected to.
isClosedTrue after close().
suspend fun put(key: String, payload: ByteArray, priority: Int = Priority.DATA,
express: Boolean = false, compression: Boolean = true)
suspend fun get(key: String, timeout: Duration = 1.seconds): List<Sample>
fun subscribe(key: String): Flow<Sample>
suspend fun openSubscriber(key: String): Subscriber
suspend fun publisher(key: String, priority: Int = Priority.DATA, express: Boolean = false,
reliable: Boolean = false, compression: Boolean = true): Publisher

subscribe accepts * and ** wildcards. A Publisher is cheaper than put for a key written repeatedly; it has put(payload) and putBlocking(payload). A Subscriber is a pull subscription with receive(timeout): Sample?.

Sample has key, payload, isDelete and timestampUs (the publisher’s fabric-clock send time, when it stamped one).

Priority holds the constants REAL_TIME (250), INTERACTIVE_HIGH (220), INTERACTIVE_LOW (190), DATA_HIGH (150), DATA (100), DATA_LOW (80) and BACKGROUND (20).

suspend fun robots(): List<String>
suspend fun videoTracks(robot: String): List<String>
suspend fun videoTrackInfo(robot: String, track: String, timeout: Duration = 3.seconds): VideoTrackInfo?
suspend fun audioTracks(robot: String): List<String>
suspend fun depthTracks(robot: String): List<String>

robots() names the robots online now. A VideoTrackInfo is what the robot says about a track: codec (h264 or av1), width, height, fps, stereo (both eyes side by side in one frame), stereoEye (left or right when the eyes are two tracks) and encoder.

suspend fun alive(key: String): LivelinessToken
suspend fun announceControl(robot: String, controller: String, sessionId: String): LivelinessToken
suspend fun liveTokens(pattern: String): List<String>
fun liveliness(pattern: String, history: Boolean = true): Flow<LivelinessEvent>

announcePresence(robot, userId, displayName) shows this operator in the robot’s viewer list, operators(robot) follows who is viewing, and controlHolders(robot) who holds control.

announceControl marks controller as in control of robot until the token is closed, the way the operate page does when it takes control. Pass "policy" for a policy, otherwise the operator’s user id. LivelinessEvent has key and alive.

suspend fun relays(): List<String>
suspend fun relayRtt(): Duration?
suspend fun measureRtt(robot: String, timeout: Duration = 1.seconds): Duration
fun latency(robot: String): Flow<LatencyStats>
suspend fun connectionInfo(): ConnectionInfo?
suspend fun certificateHealth(): CertificateHealth?

relays() names the relays the session is connected to, such as fra. DNS picks the relay from where the device’s traffic appears to come from, so a roaming SIM or a VPN can land a device far from where it is; compare relays() with relayRtt() when latency is higher than expected.

measureRtt throws a timeout AdamoException when the robot does not answer. LatencyStats has regime (STABLE, DEGRADING, VOLATILE, RECOVERING), jitterHintMs, rttVariationMs, targetBitrateKbps, lossRate, queuingDelayMs and timestampMs.

suspend fun sendControl(robot: String, channel: String, message: ControlMessage,
format: ControlFormat = ControlFormat.JSON, priority: Int = Priority.REAL_TIME)
fun control(robot: String, channel: String, maxAge: Duration? = 1.seconds): Flow<ControlSample>
suspend fun openControl(robot: String, channel: String, maxAge: Duration? = 1.seconds): ControlSubscription
suspend fun sendRumble(robot: String, rumble: Rumble)
fun rumble(robot: String): Flow<Rumble>

To hold control the way the operate page does, use a lease, and send high-rate streams through a declared publisher:

val lease = session.takeControl("arm", userId = userId, displayName = "Sam")
lease.steer(videoReceiver) // this operator's reception steers loss protection
val head = session.controlPublisher("arm", "json/xr/head/pose", ControlFormat.COMPACT)
// each tracking frame:
head.sendBlocking(ControlMessage.PoseStamped(position, orientation, stamp))
// when the operator lets go:
lease.release()

takeControl tells the robot who acquired control, sends the heartbeat robots treat as a lease once a second, and holds the token the operate page and the data service read. release() sends the release and stops the heartbeat.

sendControl is the operator side and control the robot side. A channel is the part of the key below <robot>/control/, such as json/joy, and may use wildcards. See Control messages.

suspend fun stateStore(robot: String): StateStore
suspend fun taskRunner(robot: String): TaskRunner
suspend fun log(robot: String, message: String, level: String = "info")
suspend fun setPose(robot: String, x: Double, y: Double, z: Double, frame: String = "map", heading: Double? = null)
suspend fun startInference(robot: String, policy: String, arguments: JSONObject = JSONObject(),
regions: List<String> = emptyList()): Inference

StateStore has set(key, value) for bytes, strings and JSONObject, get(key): ByteArray? and delete(key). Operators read a robot’s state with get(Adamo.stateTopic(robot, key)) and follow it with subscribe(Adamo.stateTopicAll(robot)).

TaskRunner has select(taskSetId, name, subtasks), advance() and reset().

To watch a robot: logs(robot) is its log lines, pose(robot) its position reports and stateChanges(robot) each state key as it changes, all as flows; state(robot, key) reads one value now.

Inference has id, status(), setTask(task, timeout) to hand a running policy a new task, and stop().


This device acting as a robot: it is announced as online, answers operators’ round-trip probes, sends the heartbeat viewers draw the media path from, and tells the data service what to record. There is no run(); the robot is live from open until close.

val robot = Robot.open(apiKey, name = "phone")
val track = SurfaceVideoTrack(robot.video("main", 1280, 720, fps = 60, stateDirectory = context.filesDir))
// Point a Camera2 or CameraX output, or an EGL context, at track.inputSurface.
robot.control("json/**").collect { command ->
when (val message = command.message) {
is ControlMessage.Joy -> drive(message.axes)
is ControlMessage.Keyboard -> if (message.isDown) press(message.key)
else -> {}
}
}
FunctionUse
Robot.open(apiKey, name, protocol, recording, direct)A robot in the organization that owns apiKey.
Robot.openLocal(name, options)A robot on the local network with no account. Operators use Session.connectLocal with this device’s address and robot.session.localPairingKey.

With direct (the default), the robot also listens for viewers on its own network, as robots built with the other SDKs do. A viewer on the same Wi-Fi then reaches it without a relay in between. Pass direct = null to use the relay only.

recording is a Recording. Robot.open uses the default, which records while a human or a policy is in control; pass Recording.OFF to record only on startRecording().

MemberMeaning
name, sessionThe robot’s name, and its connection for your own keys.
control(channel, maxAge), openControl(channel, maxAge)Control from operators.
video(track, width, height, fps, bitrateKbps, minBitrateKbps, maxBitrateKbps, stateDirectory)A VideoPublisher.
audio(track, options, stateDirectory)An AudioPublisher.
depth(track, width, height, options, fps, bitrateKbps, stateDirectory)A DepthTrack.
stateStore(), taskRunner(), log(message, level), setPose(…)As on Session, for this robot.
inference(policy, arguments, regions)Runs a hosted policy against this robot.
sendRumble(rumble)Asks the operator’s gamepad to rumble.
startRecording(), stopRecording()Record from now until stopped, whoever is in control.

stateDirectory is durable app-private storage, such as context.filesDir. It keeps frame sequence numbers across restarts.


ControlMessage is a sealed interface. Every type has the JSON shape the browser and the other SDKs use.

TypeFields
Joyaxes, buttons, stamp
JoystickCommandsequenceId, axes, buttons, stamp
Keyboardkey, code, action (down or up), stamp; isDown
MousemotionXTotal, motionYTotal, position, buttonMask, wheelTotal, horizontalWheelTotal, stamp
JointStatenames, positions, velocity, effort, stamp, frameId
PoseStampedposition, orientation, stamp, frameId
PoseArrayposes, stamp, frameId
Booldata, stamp
XrFramehead, left, right, resumed, stamp; controller(hand)
OperatorControlversion, active, event, operator, timestampMs
Safetystate, reason, stamp; isOk; Safety.forState(state)
OperatorLayoutlayout, stamp
Rawvalue: any other JSON or MessagePack value, as sent

message.encode(format) returns the bytes to publish and ControlMessage.decode(payload, channel) reads any format. ControlFormat is JSON, MSGPACK or COMPACT; the compact form is fixed-point and exists for joystick, pose, boolean and XR messages.

A ControlSample has channel, key, message, payload (the bytes as they arrived) and timestampUs.

control drops messages older than maxAge once the fabric clock is synchronized; pass null to accept any age. When a collector falls behind, the oldest queued messages are discarded rather than delivered late. ControlSubscription.stats() counts what was received, delivered, stale, undecodable and dropped.


Video is H.264, encoded and decoded by the device’s own codecs.

val receiver = session.videoReceiver("arm", "main")
VideoPlayer(receiver, surfaceView.holder.surface).run() // until cancelled

VideoPlayer(receiver, surface, info, onFrame) decodes onto a Surface with the device’s hardware decoder, showing each frame as soon as it decodes and requesting a keyframe after a late or broken frame. Pass the track’s VideoTrackInfo so the decoder is opened for its codec (H.264 or AV1) and size.

It reports where a frame’s time went: arrivalMs (robot capture to arriving here, the network’s share), decodeMs (time in the decoder), framesHeldByDecoder (0 when each frame comes out before the next goes in) and captureToRenderMs (robot capture to handing the decoded frame to the surface), all on the fabric clock. It also has framesReceived, receivedKbps, framesRendered, framesDropped and decoderName. onFrame is called for each displayed frame with a FrameTiming: captureTimeUs, arrivalMs, decodeMs, captureToRenderMs and sequence.

The surface does not have to be a view. Make a Surface from a SurfaceTexture, give it to the player, and draw that texture in your OpenGL scene or OpenXR layer; onFrame tells you a new frame is ready, so call updateTexImage() on your render thread. For stereo, read VideoTrackInfo.stereo (both eyes in one frame, left half and right half) or play the left and right tracks with two players.

val texture = SurfaceTexture(textureId)
val info = session.videoTrackInfo("arm", "main")
val player = VideoPlayer(session.videoReceiver("arm", "main"), Surface(texture), info) { timing ->
frameReady.set(true) // then texture.updateTexImage() on the GL thread
}
scope.launch { player.run() }

On a Snapdragon phone, 720p streams from NVENC and VAAPI robots decode in about 5 ms with no frames held back. The step after that, from decoded frame to lit pixels, is one or two display refreshes.

To decode yourself, collect receiver.accessUnits(). An AccessUnit has payload (Annex-B bytes for one frame), captureTimeUs, sequence and keyframe. Start from a keyframe, and call receiver.requestKeyframe() after dropping a frame. receiver.counters() returns transport counters, and setFeedbackControlOwner(controller, sessionId) names the operator whose reception steers the sender’s loss protection.

val publisher = robot.video("main", 1280, 720, fps = 60, stateDirectory = context.filesDir)
val track = SurfaceVideoTrack(publisher)

SurfaceVideoTrack(publisher, timestamps, onError) encodes whatever is drawn on inputSurface and publishes it. It follows the SDK’s bitrate targets and keyframe requests by itself, and when the network cannot keep up it drops queued frames and restarts from a keyframe rather than adding latency. captureToSendMs reports how long frames take from capture to the network, and framesDropped how many were discarded.

To run your own encoder, call publisher.sendBlocking(accessUnit, captureTimeUs) with complete Annex-B access units, the first IDR including SPS and PPS, from one thread. Each call returns VideoStats. When stats.bitrateCommandId is set, apply stats.targetBitrateKbps to the encoder and call publisher.reportBitrateResult(id, error) before the next send, also when the encoder refuses. Send an IDR when stats.requestKeyframe is set.

  • A phone camera holds about three frames between the sensor and the encoder, whatever the capture settings, so frame rate is the lever. On a Galaxy Z Fold, sensor to network is about 100 ms at 30 fps and 66 ms at 60 fps. The hardware encoder itself adds about 10 ms.
  • Frames are stamped from the camera’s own timestamps and moved onto the Adamo fabric clock, so a viewer’s latency figure includes the camera and encoder and excludes any error in the phone’s clock.
  • On the same Wi-Fi, viewers reach a robot directly. On mobile data the stream goes through a relay, and carriers block the direct path.

session.xrTeleop(robot) sends head and controller tracking to a robot the way the operate page’s VR mode does, on the same channels and with the same bytes, so a robot cannot tell a native headset app from the web one.

val lease = session.takeControl("arm", userId = userId)
val teleop = session.xrTeleop("arm")
// once per rendered frame, from the render thread:
teleop.submit(XrInput(head, left = XrHandInput(gripPose, buttons, axes), right = rightHand, visible = hasFocus))
// when your own menu opens:
teleop.pause()
  • Nothing is sent until the operator releases both grips and then squeezes both. Grips already held cannot start it.
  • Losing focus (visible = false) or pause() stops it until the next release-and-squeeze.
  • The first frame after a resume carries the clutch signal, and poses are rebased so they continue from the last ones sent rather than jumping to where the hands drifted.
  • At most 60 frames a second are sent, and the operator’s safety state twice a second.

XrHandInput uses WebXR’s xr-standard layout so indices mean what they mean on the operate page: buttons are trigger, grip, touchpad, thumbstick click, A or X, B or Y; axes are touchpad x and y, then thumbstick x and y with up negative (OpenXR reports up positive, so negate it). teleop.state is WAITING_FOR_GRIPS or ACTIVE.

The repository’s xr-sample is a complete headset app built this way: OpenXR for tracking, and the video as a compositor layer fed directly by the decoder.


Audio is Opus on the wire and interleaved signed 16-bit PCM in your code.

// Listen to a robot.
AudioPlayer(session.audioReceiver("arm", "mic")).run()
// Stream this device's microphone.
val microphone = MicrophoneTrack(robot.audio("mic", stateDirectory = context.filesDir))
ClassUse
session.audioTracks(robot)Names of the audio tracks a robot is publishing.
AudioReceiverDecoded frames after reordering and loss recovery: frames(), receive(timeout), stats().
AudioPlayer(receiver, usage)Plays a receiver on the device’s audio output.
AudioPublishersend(samples, captureTimeUs) and sendBlocking(…) take PCM in chunks of any length.
MicrophoneTrack(publisher, source, onError)Captures the microphone into a publisher. Needs RECORD_AUDIO.

AudioOptions(sampleRate, channels, frameDuration, bitrateKbps, application, inbandFec, dtx) defaults to 48 kHz mono, 10 ms frames and 48 kbps. Sample rates are 8000, 12000, 16000, 24000 and 48000 Hz. An AudioFrame has samples, sampleRate, channels, sequence, captureTimeUs and concealed.


Depth tracks carry 16-bit depth images as phase-coded H.264, the same coding the other SDKs use, so a depth track from a phone is viewable wherever depth tracks are.

val track = robot.depth("tof", 320, 240, DepthOptions(depthFor = "main"), stateDirectory = context.filesDir)
track.send(depthMillimetres) // ShortArray of width × height unsigned samples; 0 is invalid
val receiver = session.depthReceiver("arm", "tof")
receiver.frames().collect { frame -> println(frame[160, 120]) } // millimetres

DepthOptions(depthFor, intrinsics, extrinsics, maxDepthMm, rangeMm, depthScaleMm, edgeErosion, temporalFilter, spatialSmoothing): depth is good to a couple of centimetres up to maxDepthMm (4096 by default), and rangeMm extends the range beyond it. A DepthFrame has depthMm, width, height, captureTimeUs and sequence.


What the data service records for a robot.

Robot.open(apiKey, "phone", recording = Recording(
controllers = setOf(Recording.Controller.HUMAN),
mode = Recording.Mode.Interventions(preRoll = 5.seconds, postRoll = 2.seconds),
format = Recording.Format.MCAP,
))

Recording(controllers, mode, minDuration, maxDuration, maxSizeBytes, topics, recordAudio, format, tags). mode is Episodes, Continuous or Interventions, each with a frameRate of Raw, Max(gop) or Fixed(rate, gop). Continuous also takes a postRoll and an idleTimeout: a teleoperator’s time in control after their last input is left out once it passes (2 minutes by default), and null keeps it. format is RRD or MCAP. tags are put on every recording.

Recordings.open(apiKey) lists and fetches what was recorded: list(filter), download(recordings, directory) and read(recording, ranges) for byte ranges of one file.


Dataset.build(apiKey, recordings, export, decoders) builds a dataset on Adamo from recordings, and Training.start(apiKey, baseModel, …) runs fine-tuning on it: forwardBackward(dataset, batchSize), optimStep(AdamParams(learningRate)), saveWeights(path) and saveState(path). Close the run when done; compute is billed while it exists.


Process-wide helpers.

MemberMeaning
Adamo.versionVersion of the SDK the library was built from.
Adamo.fabricNowUs()Time on the Adamo fabric clock, in microseconds.
Adamo.fabricSynced()Whether a session has synchronized the fabric clock with its relay.
Adamo.stateTopic(robot, key), Adamo.stateTopicAll(robot)Keys for reading and following a robot’s state.
Adamo.heartbeatTopic(robot)The key a robot’s heartbeat is published on.
Adamo.doctor(apiKey, timeoutMs)The connectivity checks adamo doctor runs, as a list of DoctorCheck(status, message, remedy). Blocks; call it off the main thread.

ROS 2 bridging, V4L2 and GStreamer attachment, and the software and desktop-GPU encoders and decoders are Linux and macOS facilities. On Android the camera, microphone and codecs are the platform’s own, which is what SurfaceVideoTrack, MicrophoneTrack, VideoPlayer and AudioPlayer use.