mechutil 0.8.1

Utility structures and functions for mechatronics applications.
Documentation
//
// Copyright (C) 2024 Automated Design Corp. All Rights Reserved.
// Created Date: 2024-02-02 17:05:27
// -----
// Last Modified: 2024-02-27 16:08:46
// Modified By: Thomas C. Bitsky Jr.
// -----
//
//

use std::time::{Duration, SystemTime};

/// Timer on Delay structure
pub struct Ton {
    start_time: SystemTime,
    end_time: SystemTime,
    pub preset_ms: u64,
}

/// Methods for the Ton struct
impl Ton {
    /// Constructor
    pub fn new() -> Ton {
        Ton {
            start_time: SystemTime::now(),
            end_time: SystemTime::now(),
            preset_ms: 0,
        }
    }

    /// Start the timer. Sets start_time and calculates the end_time
    pub fn start(&mut self) {
        self.start_time = SystemTime::now();
        let dur = Duration::from_millis(self.preset_ms);
        self.end_time = SystemTime::now() + dur;
    }

    /// Returns true if the preset time has elapsed since start.
    pub fn is_done(&self) -> bool {
        return self.preset_ms > 0 && (SystemTime::now() >= self.end_time);
    }

    /// Returns the elapsed milliseconds since start.
    pub fn elapsed(&self) -> u64 {
        match SystemTime::now().duration_since(self.start_time) {
            Ok(n) => return n.as_millis() as u64,
            Err(_) => return 0,
        }
    }
}