Rust EtherCAT: How to set DC application time from system clock

Here’s how you can set the Distributed Clocks (DC) application time in a Rust EtherCAT application using the ethercat crate.

ethercat_time.rs
use chrono::TimeZone;
use std::time::{SystemTime, UNIX_EPOCH, Duration};

// requires `chrono = "0.4"` in Cargo.toml
let epoch_2000_secs = chrono::Utc.ymd(2000, 1, 1).and_hms(0, 0, 0).timestamp() as u64;
let epoch_2000 = UNIX_EPOCH + Duration::from_secs(epoch_2000_secs);
let app_time_ns = SystemTime::now()
    .duration_since(epoch_2000)? // Result<Duration, _>
    .as_nanos() as u64;
// Set it for the EtherCAT master
master.set_application_time(app_time_ns)?;

This code ensures that, as per the EtherCAT specification, the application time is set relative to the epoch starting on 2000-01-01, not the Unix epoch at 1970-01-01.

Corresponding Cargo.toml dependency:

Cargo.toml
[dependencies]
chrono = "0.4"
ethercat = "*"

Check out similar posts by category: Rust, EtherCAT