/**
 * Simple example for controlling M&S USB Missile launcher
 *
 * Copyright (C) Ian Jeffray 2005, all rights reserved.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include "missile-control-lib.h"

#define USB_TIMEOUT 1000 /* milliseconds */

typedef enum
{
    missile_stop  = 0,
    missile_left  = 1,
    missile_right = 2,
    missile_up    = 4,
    missile_down  = 8,
    missile_fire  = 16
}
missile_command;

static void missile_do( missile_usb *control, int cmd )
{
    int a, b, c, d, e;

    /* Two fixed-format initiator packets appear to be required */

    if (missile_usb_sendcommand(control, 'U', 'S', 'B', 'C', 0, 0, 4, 0 ))
    {
        perror("missile_usb_sendcommand failed");
        return;
    }

    if (missile_usb_sendcommand(control, 'U', 'S', 'B', 'C', 0, 64, 2, 0 ))
    {
        perror("missile_usb_sendcommand failed");
        return;
    }

    /* Now the actual movement command! */

    a = cmd & missile_left ? 1 : 0;
    b = cmd & missile_right ? 1 : 0;
    c = cmd & missile_up ? 1 : 0;
    d = cmd & missile_down ? 1 : 0;
    e = cmd & missile_fire ? 1 : 0;
    if (missile_usb_sendcommand64(control, 0, a, b, c, d, e, 8, 8 ))
    {
        perror("missile_usb_sendcommand failed");
        return;
    }
}

int main(void)
{
    missile_usb *control;

    if (missile_usb_initialise() != 0)
    {
        fprintf(stderr, "missile_usb_initalise failed\n");
        exit(EXIT_FAILURE);
    }

    control = missile_usb_create(0 /*debug*/, USB_TIMEOUT);
    if (control == NULL)
    {
        fprintf(stderr, "unable to create missile launcher usb handle\n");
        exit(EXIT_FAILURE);
    }

    if (missile_usb_finddevice(control, 0) != 0)
    {
        fprintf(stderr, "unable to find usb missile launcher device\n");
        exit(EXIT_FAILURE);
    }

    /* Now we're ready.  Move the thing around, and FIRE! */

    missile_do(control, missile_left);
    sleep(2);
    missile_do(control, missile_right);
    sleep(1);
    missile_do(control, missile_right|missile_down);
    sleep(1);
    missile_do(control, missile_left|missile_down);
    sleep(1);
    missile_do(control, missile_right);
    sleep(1);
    missile_do(control, missile_up);
    sleep(2);
    missile_do(control, missile_stop);
    sleep(1);

    missile_do(control, missile_fire);
    sleep(1);
    missile_do(control, missile_stop);
    sleep(1);

    /* Clean up */

    missile_usb_destroy(control);

    missile_usb_finalise();

    return EXIT_SUCCESS;
}

