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.
TextDisplay reading, units or descriptive text. The font, font size, alignment, line wrapping and truncation can be set; the content is uniformly converted to a string, and empty values are displayed as empty.
SymbolUse SF Symbols to draw system icons, such as speedometer, thermometer. The symbol font size, font weight and coloring method can be set. Whether the specific symbol is available depends on the device system.
ImageDisplays an image from a gauge resource, such as a logo, decorative background, or tile texture. source Use the resource name to set the scaling, cropping, or repeating method to the available sizes.
CardContentProvides an instrument structure with title, right content, and body text. The text renderer will get contentSize minus the title and margins, which can be used to arrange figures, graphs, or charts.
Layout
Arrange multiple View, allocate remaining space, and construct horizontal, vertical, stacked, and scale layouts.
HStackArrange the subtitles View from left to right, suitable for horizontal combinations of icons and numbers, numbers and units, etc. spacing sets the adjacent spacing, alignment sets the top and bottom or text baseline alignment within this line.
VStackArrange the subtitles View from top to bottom, suitable for the vertical combination of titles, main numbers and units. spacing sets the adjacent spacing, and alignment sets the left and right alignment within this column.
ZStackStack multiple View in the same area, suitable for background, scale and center readings. The children View are drawn sequentially, and alignment sets their common alignment position within the container.
SpacerAllocate remaining space in Stack to push content on both sides or reserve elastic distance for content. minLength sets the minimum length, explicit width or height can fix the size in the corresponding direction.
RadialLayoutDistribute scales, numbers, or symbols around a circle. radius controls the distance from the center to the layout center of View, and startAngle and sweepAngle control the distribution range.
RepeatedLayoutPeriodically duplicates a pattern in the cropping window, suitable for continuously moving scales and compasses. period sets the repeat interval, value and anchor determine where the current value is aligned.
Graphics
Draw ticks, progressions, lines, and custom outlines, and control appearance with properties like background, stroke, and angle.
RectangleDraws 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.
CircleDraws 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.
EllipseDraws 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.
ArcDraw 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.
LineDraws 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.
PolylineDraw 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.
PathBuild 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.
GroupCombine multiple View into a whole, uniformly applying transparency, rotation or other special effects. The child View follows the arrangement rules of the outer container, and the special effects are applied to the entire set of synthesized results.
MaterialDraw the surface of frosted glass material, which can be overlapped with text and graphics to form a content area. type currently supports frosted, style controls the material thickness; the visible effect depends on the content behind it.
Charts and Maps
Plot data series into curves and histograms, or display locations and routes.
LineChartPlot the data series with actual x/y values as a curve. Suitable for trends such as speed and time, supports coordinate ranges, axes and labels; missing y values will break line segments.
BarChartPlot each data item as a bar, suitable for comparing categorical values. It can be arranged horizontally or vertically, set numerical ranges, category labels and numerical labels, and supports positive and negative values.
MapDisplay maps, locations and routes within the meter. Camera center, orientation, zoom and map style can be set, using path to provide route points; following the user's location requires valid positioning data.
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.