Skip to content

Robot Clock

Tom Tzook edited this page Nov 14, 2020 · 1 revision

Time tracking can be quite essential for robot algorithms.

API

Clock

flashlib.core introduces the Clock interface which can be used to query the current timestamp with Clock.currentTime. It is guaranteed that two subsequent calls to currentTime will produce two timestamps that are sequential so that the second timestamp is either larger or equal to the first. Whether or not it is actually larger or simply equals depends on the precision of the clock.

Acquiring a Clock

A robot code has a single unified clock, which should be used for all robot needs. The robot clock is provided from RobotControl and is universally accessible via RunningRobot.getControl().getClock().

Clock clock = RunningRobot.getControl().getClock();
Time now = clock.currentTime();

Time

The Time class is immutable and represents a timestamp with both size and units. It is both provided from a Clock but can be created manually and used in other locations.

Time.value and Time.unit allow querying the value and time unit of the timestamp.

Time.toUnit allows converting the timestamp to a different unit. For example, when wanting to access the timestamp with a specific unit, we can time.toUnit(TimeUnit.MILLISECONDS).value().

It is possible to perform basic arithmetic between two Time objects, like Time.add or Time.sub.

Time time1 = ...;
Time time2 = ...;

System.out.println(time1.add(time2));
System.out.println(time1.sub(time2));

In addition, comparing between Time objects is quite simple.

Time time1 = ...;
Time time2 = ...;

System.out.println(time1.largerThan(time2));
System.out.println(time1.largerThanOrEquals(time2));
System.out.println(time1.lessThan(time2));
System.out.println(time1.lessThanOrEquals(time2));
System.out.println(time1.equals(time2));

Using these methods, we can, for example, check intervals:

Time timeStart = ...;
Time timeNow = ...;
Time wantedInterval = ...;

Time passed = timeNow.sub(timeStart);
if (passed.largerThanOrEquals(wantedInterval)) {
    // do something
}

Creating Time

Time objects can be acquired from Clock objects. In addition, there are several factory methods which can be used to create Time objects manually:

  • Time.of(value, unit)
  • Time.milliseconds(value)
  • Time.seconds(value)
  • Time.minutes(value)

Invalid Time

An invalid time is a replacement for using null references to indicating empty or missing values. There is only one such reference: Time.INVALID. To test if a time object is valid, use Time.isValid.