#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/io.h>

#define SERVER_IP "192.9.201.8"
#define TICK 10000000
enum {LEFT, MIDDLE, RIGHT};

int main()
{
    RT_TASK *server, *client;
    int priority = 0, stack_size = 4096, msg_size = 0;
    struct sockaddr_in addr;
    unsigned int server_node, server_port, msg = 1, r;
    RTIME a, b, diff;

    client = rt_task_init(nam2num("client"), priority,
                          stack_size, msg_size);
    assert(client != 0);
    inet_aton(SERVER_IP, &addr.sin_addr);
    server_node = addr.sin_addr.s_addr;
    while((server_port = rt_request_port(server_node)) <= 0 &&
           server_port != -EINVAL);
    server = RT_get_adr(server_node, server_port, "servr");
    assert(server != 0);
    iopl(3);
    rt_set_oneshot_mode();
    start_rt_timer(0);
    rt_make_hard_real_time();
    while(1) {
        outb(0x0, 0x200); 
        a = rt_get_cpu_time_ns();
        while(inb(0x200) & 1);
        b = rt_get_cpu_time_ns();
        diff = b - a;
        if(diff < 130000) msg = LEFT;
        else if (diff > 320000) msg = RIGHT;
        else msg = MIDDLE;
        RT_send(server_node, server_port, server, msg);
        rt_sleep(nano2count(TICK));
    }
    rt_make_soft_real_time();
    stop_rt_timer();
    rt_task_delete(client);
}
