#include <stdio.h>
#include <rtai_lxrt.h>
#include <rtai_netrpc.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/io.h>
#include <pthread.h>
#include <signal.h>

RTIME on_time[3] = {200000, 500000, 900000};
RTIME off_time[3];
RTIME total_time = 1000000;
volatile int curr_brightness = 0, stop = 0;
void handler(int n)
{
    stop = 1;
}
void *pwm_task(void *t)
{
    RT_TASK *task;
    task = rt_task_init(nam2num("pwm"), 0, 4096, 0);
    assert(task != 0);
    iopl(3);
    mlockall(MCL_CURRENT|MCL_FUTURE);
    rt_make_hard_real_time();
    while (!stop) {
        outb(0xff, 0x378);
        rt_sleep(on_time[curr_brightness]);
        outb(0x0, 0x378);
        rt_sleep(off_time[curr_brightness]);
    }
    rt_make_soft_real_time();
    rt_task_delete(task);
}

int main()
{
    RT_TASK *server, *client;
    pthread_t t1;
    int priority = 0, stack_size = 4096, msg_size = 0;
    unsigned int msg, i;
    RTIME period, a, b;
    signal(SIGINT, handler);
    server = rt_task_init(nam2num("servr"), priority,
                              stack_size, msg_size);
    assert(server != 0);
    rt_set_oneshot_mode();
    start_rt_timer(0);
    for(i = 0; i < 3; i++) {
        off_time[i] = nano2count(total_time - on_time[i]);
        on_time[i] = nano2count(on_time[i]);
    }
    pthread_create(&t1, 0, pwm_task, 0);
    while(!stop) {
        rt_receive(0, &msg);
        curr_brightness = msg;
    }
    pthread_join(t1, 0);
    stop_rt_timer();
    rt_task_delete(server);
}
