
component rtfault "generate RT faults on purpose";

pin in  bit fault "cause a series of count RT faults" ;
pin in  u32 count "number of faults";
pin in  u32 delay "ms delay on fault ⁽less than 1000)";

option singleton yes;
function _;
license "GPL";
;;

#include "rtapi.h"
#if defined(BUILD_SYS_USER_DSO)
#include <time.h>
#include <stdio.h>
#endif
#include <stdbool.h>
static bool previous_fault;
static int n;

FUNCTION(_) {
    if (previous_fault ^ fault) {
	n = count;
    }
    previous_fault = fault;  
    if (n) {
#if defined(BUILD_SYS_USER_DSO)
	// printf() eventually calls write(), which will cause
	// a Xenomai domain switch

	struct timespec nap = {0, delay * 1000 * 1000};
	if (delay)
	    nanosleep(&nap, NULL);
	printf("fault # %d\n", n--);
#else
	do {
	    rtapi_delay(delay * 1000 * 1000);
	    n--;
	} while (n > 0);
	rtapi_print_msg(RTAPI_MSG_ERR, "RT delay ..\n");
#endif
    }
}
