API reference

Custom instrumentation uses main() to return the View tree. Here we introduce the script structure, running interface and drawing components, and provide entrances to various APIs.

Global object

CapDrive provides the following global objects directly in the instrument script, without the need to import or create them yourself. They can be read in main() and used to obtain data, adapt to the display environment, save temporary state and output logs.

object Purpose and common access methods
$data Driving data. Read the current sample through $data.current, and read the samples of the last 30 seconds of this trip through $data.history.
$env The current instrument's display environment, including available sizes, theme colors, units, language, and display mode, such as $env.width, $env.foreground.
$sessionStorage The temporary state of the current instrument instance within the current trip. Use get(key) to read and set(key, value) to save; clear when ending the trip or reloading the instrument.
console Script log. Use console.log(...), console.warn(...) and other methods to output data and diagnostic information.

$data and $env are updated by the App and are read-only inputs. This value is read each time main() is called; modifying the read copy of the data will not change the actual driving data. $ is part of the object name, use $env.width directly and does not need to be written as a function call.

Define drawing content

main() in the instrument script returns the screen described by JSX. Each JSX node is a built-in View, with attributes controlling size, color and other drawing behaviors, and nested relationships forming the final picture.

The complete script below draws a number and a row of units. VStack arranges two Text up and down, spacing sets the spacing, fontSize sets the font size, and the color is provided by the current display environment.

function main() {
  return (
    <VStack spacing={6}>
      <Text fontSize={48} color={$env.foreground}>
        78
      </Text>
      <Text fontSize={14} color={$env.accent}>
        km/h
      </Text>
    </VStack>
  );
}

The JavaScript expression can be used in JSX's {}. Replace the fixed 78 with the calculation result, and the text will change with the input; the calculation result can also be passed to attributes such as color, size, or arc angle.

$data: driving data

The fields of $data.current come from the input identifier of this instrument. Enter a local value in Instrument settings → Input bindings or select the OBD parameter and use the gear to manage definitions in Parameter configuration. The following assumes that the corresponding identifier has been defined.

Example access method Input definition and return content
$data.current.speed Basic speed input, returns { value, unit }.
$data.current.gForce Basic G value input, including longitudinal, lateral, combined and units.
$data.current.location Basic location input, including longitude, latitude and units.
$data.current.elapsed Basic recorded duration input, in seconds.
$data.current.recording Basic record status input, returning a Boolean value.
$data.current.coolant An OBD input returns { value, unit } or null after binding the vehicle parameters.
$data.current.limit Numeric input returns a number directly.
$data.current.label Text input returns a string directly.
$data.current.showUnit A switch input returns a Boolean directly.
$data.current.style A selection input returns the selected string.

$data.history covers the last 30 seconds of the current trip, ordered from oldest to newest, and the sampling field is consistent with current; fixed input uses the current configuration. The window may be empty or contain missing readings. The value of OBD may be mapped text, the type should be checked first. Zero has a different meaning than null. Full input, units and history rules.

$env: Display environment

$env describes the display area where the current instrument is located. After resizing the card, switching themes, or entering HUD, the App provides an updated environment. Calculations that rely on these values ​​should be placed in main().

Field Meaning and usage
$env.width、$env.height The available width and height of the current instrument are in screen points. Can be used to calculate font size, diameter or endpoint coordinates.
$env.foreground、$env.accent The text color and accent color of the current theme can be directly passed to color, stroke, background and other color attributes.
$env.dark Whether to use dark appearance, type is boolean.
$env.mode Display mode, value is 'instruments' or 'hud'.
$env.speedUnit Current speed display unit, value is 'km/h' or 'mph'. When the reading has its own unit, the unit of the reading is used first.
$env.language App's current language identifier, such as 'zh-Hans'.
$env.reduceMotion Whether the system has reduced dynamic effects enabled, you can adjust the repeat animation accordingly.
$env.obdDevice { id, name } for the currently connected device, or null if no device is ready.

For example, use Math.min($env.width, $env.height) to get the maximum diameter suitable for placing a perfect circle, and use $env.foreground to make the text follow the theme. Full display environment definition.

Example: Working with data and display environments

Select the speed in the meter settings. The following script reads the current speed, calculates the font size based on the card width and height, uses theme colors, and displays the units provided by the readout. A horizontal line is displayed when velocity is missing; a valid zero is displayed as 0.

function main() {
  const speed = $data.current.speed;
  const fontSize = Math.min(64, $env.width * 0.25, $env.height * 0.5);

  return (
    <VStack spacing={6}>
      <Text fontSize={fontSize} color={$env.foreground}>
        {speed?.value == null ? '—' : Math.round(speed.value)}
      </Text>
      <Text fontSize={14} color={$env.accent}>
        {speed?.unit ?? $env.speedUnit}
      </Text>
    </VStack>
  );
}

When the data is updated, the new speed will be used for the next call; when the card size or theme changes, the font size and color will use the new environment values. If you need to accumulate peak values ​​and other states in the same trip, you can continue to use $sessionStorage; if you need to check the actual input, you can use console.log('speed', speed) to output the log during debugging.

Screen update

When the current input, input definition or display environment changes, CapDrive provides the latest $data and $env, executes the entire file in the new local scope, and then calls the main() defined this time. Top-level calculations are also re-executed, and ordinary variables are not retained across times. Identical inputs are skipped; only the latest pending input is retained in processing. History window maintenance and internal sample time changes alone do not trigger execution; explicitly defined time input changes do.

There is no fixed frequency for scripts; actual updates depend on input and processing time. Use $sessionStorage for state retained between calls; use animations for attribute transition, which is executed independently by the drawing end. main() should be completed synchronously to avoid continuous loops or blocking waits.

Related operating interfaces

main()
Script entry. Read this input and synchronously return the View, array or empty content to be drawn.
animations
Set transition behaviors such as duration, curve, and repetition for the attribute changes of View.
Color / Gradient
Construct color, HDR color, linear gradient, radial gradient, and angular gradient.
Import and share
Understand the configuration, scripts, resources and export methods of the instrument package.

Draw components

Organize screens through containers and place text, graphics, and data views into them. The following lists all built-in View by purpose; each component page explains usage, properties, default behavior and combination examples.

Content

Display readings, units, icons and pictures, or use a titled meter content area.

Layout

Arrange multiple View, allocate remaining space, and construct horizontal, vertical, stacked, and scale layouts.

Graphics

Draw ticks, progressions, lines, and custom outlines, and control appearance with properties like background, stroke, and angle.

Rectangle

Draws a rectangle with optional rounded corners for use with backgrounds, progress bars, and borders. background fills the interior, stroke strokes, lineWidth and strokePosition control the width and position of the stroke.

Circle

Draws a perfect circle or arc within the available area, suitable for circular progress and meter scales. The diameter takes the smaller value of width and center. startAngle and sweepAngle control the display range. When the entire circle is closed, the background can be filled.

Ellipse

Draws an ellipse or elliptical arc within a given width and height. Elliptical scales or decorative outlines can be formed by starting angle, sweep angle, fill and stroke.

Arc

Draw an elliptical arc according to the starting angle and sweeping angle, suitable for scale arcs and progress display. The border is determined by width and height. The width, endpoint and position of the stroke are configurable, and the background is allowed to fill when fully closed.

Line

Draws a straight line between two endpoints in local coordinates. Suitable for indicator lines, ticks and dividers, you can set the color, width, dash and endpoint styles.

Polyline

Draw a polyline by connecting a set of points in sequence. closed can connect the last point and the first point to form a closed contour, and allows filling; the coordinates use the number of points in the current View.

Path

Build paths with commands such as move, line, quad, cubic, arc, and close. Suitable for customizing pointers, curves and combined outlines, and setting fill rules and strokes.

Combinations and Materials

Apply global effects to combined content, or paint a frosted glass material surface.

Charts and Maps

Plot data series into curves and histograms, or display locations and routes.

Type and declaration files

Common types centrally define structures such as dimensions, margins, transforms, strokes, animations, and chart data. The editor provides type hints for the same API, and declaration files can also be downloaded for use by external editors.

Shared types

capdrive.d.ts