/*-
 * Copyright (c) 2003 Takanori Watanabe
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 */

/*
 * Based on the information at 
 * http://cathand.org/development/usb.html
 */

#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <dev/usb/usb.h>
#include <getopt.h>

#define DEFAULT_USB_DEVICE "/dev/ugen0"
#define USB_VIBE_SET_STRENGTH 1
#define MAX_VIB 0xff
#define USB_VENDOR_ASCII  0x0b49
#define USB_PRODUCT_ASCII_TRANCEVIBRATOR 0x064f

usage(char *argv[])
{
	fprintf(stderr, "Usage: %s [-s] [-f device] [strength]\n", argv[0]);
	exit(-1);
}

int 
main(int argc, char *argv[])
{
	int             fd, ch;
	struct usb_ctl_request req;
	usb_device_descriptor_t udd;
	char           *udev = DEFAULT_USB_DEVICE;
	int             strength = MAX_VIB;
	while ((ch = getopt(argc, argv, "sf:")) != -1) {
		switch (ch) {
		case 's':
			strength = 0;
			break;
		case 'f':
			udev = optarg;
			break;
		case '?':
		default:
			usage(argv);
		}
	}
	if (argc != optind) {
		strength = atoi(argv[optind]);
		if (strength > MAX_VIB) {
			strength = MAX_VIB;
		}
	}
	/**/
	fd = open(udev, O_RDWR);
	if (fd == -1) {
		err(1, "%s", udev);
	}
	if (ioctl(fd, USB_GET_DEVICE_DESC, &udd) == -1) {
		err(2, "%s", udev);
	}
	if ((UGETW(udd.idVendor) != USB_VENDOR_ASCII) ||
	    (UGETW(udd.idProduct) != USB_PRODUCT_ASCII_TRANCEVIBRATOR)) {
		errx(3, "Vendor No Match");
	}
	
	bzero(&req, sizeof(req));
	req.ucr_request.bmRequestType = UT_WRITE_VENDOR_INTERFACE;
	req.ucr_request.bRequest = USB_VIBE_SET_STRENGTH;
	USETW(req.ucr_request.wValue, strength);
	ioctl(fd, USB_DO_REQUEST, &req);
	return 0;
}
