// Just deal with mice...
// This seems to be just about the minimum code required to notice the
// mouse being connected and disconnected and process all the mouse
// events. Should be able to only enable the mouse output when a mouse
// input is connected to avoid trouble with uploading new code.

#include "USBHost_t36.h"

USBHost myusb;
USBHIDParser hid(myusb);
bool hid_active = false;
MouseController mouse(myusb);

uint32_t last_buttons=0;

void ProcessMouseData() {
  uint32_t cur_buttons;
  int cur_x;
  int cur_y;
  int cur_wheel;
  int cur_wheelh;

  if (mouse.available()) {
    cur_buttons = mouse.getButtons();
    if (cur_buttons != last_buttons) {
       Serial.printf("Buttons changed from 0x%x to 0x%x\n",
                     last_buttons,cur_buttons);
       last_buttons = cur_buttons;
    }
    cur_x = mouse.getMouseX();
    if (cur_x != 0) {
       Serial.printf("X moved %d\n",cur_x);
    }
    cur_y = mouse.getMouseY();
    if (cur_y != 0) {
       Serial.printf("Y moved %d\n",cur_y);
    }
    cur_wheel = mouse.getWheel();
    if (cur_wheel != 0) {
       Serial.printf("Wheel moved %d\n",cur_wheel);
    }
    cur_wheelh = mouse.getWheelH();
    if (cur_wheelh != 0) {
       Serial.printf("Wheelh moved %d\n",cur_wheelh);
    }
    mouse.mouseDataClear();
  }
}

void setup()
{
  Serial1.begin(2000000);
  while (!Serial && millis() < 3000) ; // wait for Arduino Serial Monitor
  Serial.println("\n\nUSB Host Testing");
  myusb.begin();
}

void loop()
{
  myusb.Task();

  if ((bool)hid != hid_active) {
     hid_active = ! hid_active;
     if (hid_active) {
        Serial.printf("Device %x:%x - connected\n", hid.idVendor(),
                       hid.idProduct());
        const uint8_t *psz = hid.manufacturer();
        if (psz && *psz) Serial.printf("  manufacturer: %s\n", psz);
        psz = hid.product();
        if (psz && *psz) Serial.printf("  product: %s\n", psz);
        psz = hid.serialNumber();
        if (psz && *psz) Serial.printf("  Serial: %s\n", psz);
     } else {
        Serial.println("Device disconnected.");
     }
  }
  ProcessMouseData();
}
