component timev2 "Time on in Hours, Minutes, Seconds";

description
"""
Time

When the time.N.start bit goes true the cycle timer resets and starts
to time until time.N.start goes false. If you connect time.N.start to
halui.is-running as a cycle timer it will reset during a pause. See
the example connections below to keep the timer timing during a pause.

Time returns the hours, minutes, and seconds that time.N.start is true.

Sample pyVCP code to display the hours:minutes:seconds.

<pyvcp>
  <hbox>
  <label>
    <text>"Cycle Time"</text>
    <font>("Helvetica",14)</font>
  </label>
  <u32>
      <halpin>"time-hours"</halpin>
      <font>("Helvetica",14)</font>
      <format>"2d"</format>
  </u32>
  <label>
    <text>":"</text>
    <font>("Helvetica",14)</font>
  </label>
  <u32>
      <halpin>"time-minutes"</halpin>
      <font>("Helvetica",14)</font>
      <format>"2d"</format>
  </u32>
  <label>
    <text>":"</text>
    <font>("Helvetica",14)</font>
  </label>
  <u32>
      <halpin>"time-seconds"</halpin>
      <font>("Helvetica",14)</font>
      <format>"2d"</format>
  </u32>
  </hbox>
</pyvcp>

In your post-gui.hal file you might use the following to connect it up

 loadrt time
 loadrt not
 addf time.0 servo-thread
 addf not.0 servo-thread
 net prog-running not.0.in <= halui.program.is-idle
 net cycle-timer time.0.start <= not.0.out
 net cycle-seconds pyvcp.time-seconds <= time.0.seconds
 net cycle-minutes pyvcp.time-minutes <= time.0.minutes
 net cycle-hours pyvcp.time-hours <= time.0.hours

The start pin will start or restart the counter cumulatively

The zero pin will zero the counter for a fresh count
attach to a momentary push button
""";

author "John Thornton - adapted by ArcEye to instcomp";

license "GPL";

// Input Pins
pin_ptr in bit start = 0 "Timer On";
pin_ptr in bit zero = 0 "Timer On";

// Output Pins
pin_ptr out u32 seconds = 0 "Seconds";
pin_ptr out u32 minutes = 0 "Minutes";
pin_ptr out u32 hours = 0 "Hours";

// Global Variables
variable long totalnsecs = 0;
variable hal_bit_t old_start = false;

function _;

;;

#include "rtapi_math.h"

FUNCTION(_)
{
long lperiod = fa_current_period(fa);
hal_u32_t totalsecs;

    if(gb(zero)){
	// cater for restart	
	totalnsecs = totalsecs = 0; 
	su(seconds, 0);
	su(minutes, 0);
	su(hours, 0);
    }

    if(gb(start) && !old_start) 
		totalsecs = 0;

    if(gb(start)){
        totalnsecs += lperiod;
        totalsecs = (hal_u32_t)(totalnsecs / 1e9);

        su(seconds, totalsecs % 60);
        su(minutes, (totalsecs / 60) % 60);
        su(hours, totalsecs / 3600);
        }
    old_start = gb(start);

return 0;

}
