Common tasks
The things nearly every camera application does — set the exposure and the
gain, trigger, crop, bin, fix the frame rate, save a configuration — have a
method each on Camera. They work with the names cameras actually use: a
camera that predates the current feature naming standard (SFNC 2) calls its
exposure ExposureTimeAbs or ExposureTimeRaw and its gain GainRaw, and
the same call handles it.
Everything here runs against the fake camera, no hardware needed:
cargo run -p viva-genicam --example common_tasks
cargo run -p viva-genicam --example common_tasks -- --legacy # the older names
Features by type
get_integer, get_float, get_bool, get_enum, get_string and their
set_ counterparts read and write a feature as its own type. get and set
remain for text — a command line, a configuration file:
// Each feature as its own type; `get` and `set` remain for text.
let width: i64 = camera.get_integer("Width")?;
camera.set_integer("Width", width / 2)?;
let format: String = camera.get_enum("PixelFormat")?;
println!(
"Width {} -> {}, {format}",
width,
camera.get_integer("Width")?
);
A category has no value and a command is not set: get on one, or set on
the other, is an error. Run a command with execute_command, or with
execute_and_wait, which also waits for the camera to report it finished —
asking it as often as the command’s <PollingTime> says, where it has one.
Values the camera changes on its own
A value read once is kept until something the camera’s XML links to it is
written — unless the XML says otherwise. A temperature, an exposure under
auto exposure, a status bit change on the camera with nothing to announce
it, and the XML says so with <Cachable>NoCache</Cachable>: such a feature
is read from the camera every time. A <PollingTime> says how long a value
may be shown before it is read again; after that, the next read asks the
camera. After a write to a WriteAround feature — a float register’s default
— the next read shows what the camera stored, a gain it rounded, say.
A display that shows many features asks what to read again rather than reading everything:
// DeviceTemperature is `NoCache` in the camera's XML: every read asks the
// camera. Its `<PollingTime>` says how often a display should.
let every = camera
.nodemap()
.polling_time("DeviceTemperature")
.unwrap_or(std::time::Duration::from_secs(1));
println!("{} °C", camera.get_float("DeviceTemperature")?);
// A viewer keeps the generation it drew, and reads again what changed
// since: what a write touched, and what `poll` found due.
let mut drawn = camera.generation();
for _ in 0..3 {
tokio::time::sleep(every).await;
camera.poll();
let (changed, now) = camera.changed_since(drawn);
if changed.iter().any(|name| name == "DeviceTemperature") {
println!("{} °C", camera.get_float("DeviceTemperature")?);
}
drawn = now;
}
// A value the camera changed in a way its XML does not describe:
camera.execute_command("TimestampLatch")?;
camera.invalidate("GevTimestampValue");
println!("latched at {}", camera.get_integer("GevTimestampValue")?);
changed_since names every feature whose value may have changed since a
generation: written, or invalidated because something it depends on was.
poll adds those whose polling time has passed. invalidate and
invalidate_all are for a change the XML does not describe; Python has
those two as cam.invalidate(name) and cam.invalidate_all(). Viva Studio
re-reads the features on screen this way.
Exposure and gain
// ExposureTime, else ExposureTimeAbs, else ExposureTimeRaw: the helper
// says which it wrote, and in which unit.
let exposure = camera.set_exposure_time(10_000.0)?;
println!(
"exposure: {} = {} {}",
exposure.name,
camera.exposure_time()?,
exposure.unit.as_deref().unwrap_or("(device units)")
);
// Gain, else GainRaw, on the control GainSelector selects where there is one.
if camera.resolve(StandardFeature::GainSelector).is_ok() {
camera.select_gain("All")?;
}
let gain = camera.set_gain(6.0)?;
println!("gain: {} = {}", gain.name, camera.gain()?);
Each helper tries the names in order and uses the first the camera declares,
then says which one that was, with its unit. ExposureTime and
ExposureTimeAbs are in microseconds and Gain in decibels; ExposureTimeRaw
and GainRaw are in the camera’s own units, so the value you write means what
that camera’s manual says it means.
Region of interest and binning
// Offsets to zero, then the size, then the offsets: the order that
// reaches any region the sensor allows.
camera.set_roi(Roi {
x: 64,
y: 32,
width: 320,
height: 240,
})?;
println!("roi: {:?}", camera.roi()?);
camera.set_binning(1, 1)?;
A width’s maximum shrinks as its offset grows, so the order of the writes
decides whether a region can be reached at all; set_roi gets it right
whichever way the region moves. A value off the feature’s increment is refused
before anything is written, with the nearest values that would be accepted.
Frame rate
// Turns AcquisitionFrameRateEnable on first, where the camera has one.
let rate = camera.set_frame_rate(25.0)?;
println!("frame rate: {} = {} Hz", rate.name, camera.frame_rate()?);
disable_frame_rate lets the camera choose again.
User sets
// Select, execute, and wait for the camera to finish.
camera.save_user_set("UserSet1")?;
camera.load_user_set("Default")?;
camera.set_default_user_set("UserSet1")?;
set_default_user_set chooses the set the camera loads at power-up.
Saving and restoring a configuration
A user set lives in the camera. To keep a configuration on the host — to version it, or to copy it onto another camera of the same model — save it to a file:
// Every feature the camera's XML marks streamable, each selected one
// under every entry of its selector; the file's comments say what was
// left out and why.
let saved = camera.save_features(&mut std::fs::File::create(&path)?)?;
println!("saved {} values to {}", saved.values.len(), path.display());
// Later — on this camera or another of the same model:
let report = camera.load_features(&mut std::fs::File::open(&path)?)?;
for warning in &report.warnings {
eprintln!("warning: {warning}"); // saved from another model, say
}
for failure in &report.failures {
eprintln!("not written: {failure}"); // `Feature[Selector=Entry] = value: why`
}
What is saved is what the camera’s XML marks <Streamable>. A feature behind
a selector — TriggerMode behind TriggerSelector, Gain behind
GainSelector — is saved once for each of the selector’s entries, and under
each entry of a selector that selects that selector in turn; the selectors
are put back as they were. A feature that is not available, or locked,
is left out with a comment saying why; save while the camera is not acquiring,
or what acquisition locks (Width, PixelFormat) is left out.
Check the reported saved-value count. Some devices mark no features streamable and produce a successful save with zero values; that file cannot restore their settings. Record the features and selector states you intend to change explicitly on such a device.
A load writes in the order the camera needs, whatever the order of the file:
a selector before what it selects, ExposureAuto before the ExposureTime it
locks, BinningHorizontal before the Width it rescales. A write that fails
is tried once more after the others, because some features bound each other
(Width and OffsetX). Whatever still fails is in the report, with its
reason, and the rest is written. A file saved from another camera model loads
too, with a warning.
The file is text, one feature per line, in the layout GenApi’s reference implementation writes:
# {05D8C294-F295-4dfb-9D01-096BD04049F4}
# ModelName = VivaCam_Fake
Width 320
TriggerMode {TriggerSelector=FrameStart} Off
From the command line: viva-camctl save --ip <CAMERA-IP> --out camera.txt
and viva-camctl load --ip <CAMERA-IP> --file camera.txt
(the command line); from Python, cam.save_features(path) and
cam.load_features(path).
Triggers
let mut frames = camera.open_stream(StreamOptions::new())?;
camera.enable_trigger("FrameStart", "Software")?;
// Sets TLParamsLocked too: Width and PixelFormat are locked until the stop.
camera.acquisition_start()?;
for _ in 0..3 {
camera.trigger_software()?;
let frame = frames.next_frame().await?.ok_or("the stream ended")?;
println!("triggered frame {}x{}", frame.width, frame.height);
}
camera.acquisition_stop()?;
camera.disable_trigger("FrameStart")?;
acquisition_start sets TLParamsLocked where the camera has it, so features
that would change the size of a frame — Width, PixelFormat — are locked
while it streams; acquisition_stop clears it.
When the camera lacks a feature
A camera that declares none of a feature’s names says so, naming every name it tried:
the camera has no exposure time: it declares none of ExposureTime, ExposureTimeAbs, ExposureTimeRaw
camera.resolve(StandardFeature::ExposureTime) asks without writing anything.
Without an async runtime
A program with no async runtime uses viva_genicam::blocking to discover and
open a camera. The camera it returns is the ordinary Camera: everything
above works on it unchanged, and frames come from next_frame_blocking.
cargo run -p viva-genicam --example blocking_grab # the fake camera
cargo run -p viva-genicam --example blocking_grab -- 192.168.1.20 # a real one
// Each call blocks for its timeout.
let timeout = Duration::from_millis(500);
let device = match address {
Some(ip) => blocking::discover_ip(ip, timeout)?.ok_or("that camera did not answer")?,
// Loopback included, for the fake camera.
None => blocking::discover_with(timeout, &DiscoveryOptions::new().include_loopback(true))?
.into_iter()
.find(|device| device.ip.is_loopback())
.ok_or("no camera found")?,
};
// The camera carries a small runtime of its own, shut down on drop.
let mut camera = blocking::connect(&device)?;
// Executes UserSetLoad and waits for the camera to finish; any command
// waits the same way with `execute_and_wait_blocking`.
camera.load_user_set("Default")?;
camera.set_exposure_time(5_000.0)?;
let mut frames = camera.open_stream(StreamOptions::new())?;
camera.acquisition_start()?;
for _ in 0..5 {
match frames.next_frame_blocking(Duration::from_secs(2))? {
Some(frame) => println!(
"frame {}x{} {:?}, {} bytes",
frame.width,
frame.height,
frame.pixel_format,
frame.payload.len()
),
None => break,
}
}
camera.acquisition_stop()?;
The camera brings a small runtime of its own — one thread that keeps its control channel alive — and stops it when the camera is dropped. The async API works from a current-thread Tokio runtime as well.