From f5f125b988da2067617a57a76a1c22d8176ff8ec Mon Sep 17 00:00:00 2001
From: Ingo Ruhnke <grumbel@gmx.de>
Date: Tue, 25 Jan 2011 03:10:47 +0100
Subject: [PATCH] Cleaned up stdout output somewhat

---
 TODO                                |  7 ++++
 src/chatpad.cpp                     |  2 +-
 src/controller_config_set.cpp       |  2 -
 src/dummy_message_processor.cpp     |  2 +-
 src/helper.cpp                      | 13 ++++---
 src/helper.hpp                      |  2 +-
 src/linux_uinput.cpp                | 21 +++++-----
 src/log.hpp                         |  2 +-
 src/uinput.cpp                      |  4 +-
 src/xbox360_controller.cpp          | 28 ++++++--------
 src/xbox360_wireless_controller.cpp | 31 +++++++--------
 src/xbox_controller.cpp             | 16 ++++----
 src/xboxdrv_daemon.cpp              | 59 +++++++++++++++++++----------
 src/xboxdrv_daemon.hpp              |  1 +
 14 files changed, 103 insertions(+), 87 deletions(-)

diff --git a/TODO b/TODO
index 6c50cce..3fb5cb3 100644
--- a/TODO
+++ b/TODO
@@ -42,6 +42,13 @@ $ dput my-ppa ../xboxdrv_0.7.0-1~lucid1_source.changes
 Stuff to do before 0.7.0 release:
 =================================
 
+* log levels:
+
+  debug: only shown when --debug is given
+  info:  shown when --verbose is given
+  warn:  shown by default
+  error: shown by default
+
 * figure out a good place to set the LEDs off when Xboxdrv is quit,
   just doing it in the destructor causes trouble
 
diff --git a/src/chatpad.cpp b/src/chatpad.cpp
index 257e69d..7a5091b 100644
--- a/src/chatpad.cpp
+++ b/src/chatpad.cpp
@@ -220,7 +220,7 @@ Chatpad::read_thread()
       {
         if (m_debug)
         {
-          log_info << "[chatpad] read: " << len << "/5: data: " << std::flush;
+          log_info << "read: " << len << "/5: data: " << std::flush;
           for(int i = 0; i < len; ++i)
           {
             log_info << boost::format("0x%02x ") % int(data[i]);
diff --git a/src/controller_config_set.cpp b/src/controller_config_set.cpp
index 0850913..c8fd81f 100644
--- a/src/controller_config_set.cpp
+++ b/src/controller_config_set.cpp
@@ -49,8 +49,6 @@ ControllerConfigSet::create(UInput& uinput, int slot, bool extra_devices, const
     }
 #endif
   }
-  
-  log_info << "UInput finish" << std::endl;
 
   return m_config;
 }
diff --git a/src/dummy_message_processor.cpp b/src/dummy_message_processor.cpp
index 0072777..c613aef 100644
--- a/src/dummy_message_processor.cpp
+++ b/src/dummy_message_processor.cpp
@@ -28,7 +28,7 @@ DummyMessageProcessor::DummyMessageProcessor()
 void
 DummyMessageProcessor::send(const XboxGenericMsg& msg, int msec_delta)
 {
-  //log_info << msg << std::endl;
+  log_info << msg << std::endl;
 }
 
 /* EOF */
diff --git a/src/helper.cpp b/src/helper.cpp
index d5c41bc..9f9e07f 100644
--- a/src/helper.cpp
+++ b/src/helper.cpp
@@ -25,15 +25,16 @@
 #include <sys/time.h>
 #include <sys/ioctl.h>
 
-void print_raw_data(std::ostream& out, uint8_t* data, int len)
+std::string raw2str(uint8_t* data, int len)
 {
-  std::cout << "len: " << len 
-            << " data: ";
-      
+  std::ostringstream out;
+  out << "len: " << len 
+      << " data: ";
+  
   for(int i = 0; i < len; ++i)
-    std::cout << boost::format("0x%02x ") % int(data[i]);
+    out << boost::format("%02x ") % int(data[i]);
 
-  std::cout << std::endl;
+  return out.str();
 }
 
 std::string to_lower(const std::string &str)
diff --git a/src/helper.hpp b/src/helper.hpp
index 5c6c00c..89c0516 100644
--- a/src/helper.hpp
+++ b/src/helper.hpp
@@ -21,7 +21,7 @@
 
 #include <boost/function.hpp>
 
-void print_raw_data(std::ostream& out, uint8_t* buffer, int len);
+std::string raw2str(uint8_t* buffer, int len);
 std::string to_lower(const std::string &str);
 bool is_number(const std::string& str);
 
diff --git a/src/linux_uinput.cpp b/src/linux_uinput.cpp
index b079311..f3c08b6 100644
--- a/src/linux_uinput.cpp
+++ b/src/linux_uinput.cpp
@@ -23,8 +23,9 @@
 #include <fcntl.h>
 
 #include "evdev_helper.hpp"
-#include "log.hpp"
 #include "force_feedback_handler.hpp"
+#include "log.hpp"
+#include "raise_exception.hpp"
 
 LinuxUinput::LinuxUinput(DeviceType device_type, const std::string& name_, uint16_t vendor_, uint16_t product_) :
   m_device_type(device_type),
@@ -43,7 +44,7 @@ LinuxUinput::LinuxUinput(DeviceType device_type, const std::string& name_, uint1
   ff_callback(),
   needs_sync(true)
 {
-  log_info << name << " " << vendor << ":" << product << std::endl;
+  log_debug << name << " " << vendor << ":" << product << std::endl;
 
   std::fill_n(abs_lst, ABS_CNT, false);
   std::fill_n(rel_lst, REL_CNT, false);
@@ -96,7 +97,7 @@ LinuxUinput::~LinuxUinput()
 void
 LinuxUinput::add_abs(uint16_t code, int min, int max, int fuzz, int flat)
 {
-  log_info << "add_abs: " << abs2str(code) << " (" << min << ", " << max << ") " << name << std::endl;
+  log_debug << "add_abs: " << abs2str(code) << " (" << min << ", " << max << ") " << name << std::endl;
 
   if (!abs_lst[code])
   {
@@ -120,7 +121,7 @@ LinuxUinput::add_abs(uint16_t code, int min, int max, int fuzz, int flat)
 void
 LinuxUinput::add_rel(uint16_t code)
 {
-  log_info << "add_rel: " << rel2str(code) << " " << name << std::endl;
+  log_debug << "add_rel: " << rel2str(code) << " " << name << std::endl;
 
   if (!rel_lst[code])
   {
@@ -139,7 +140,7 @@ LinuxUinput::add_rel(uint16_t code)
 void
 LinuxUinput::add_key(uint16_t code)
 {
-  log_info << "add_key: " << key2str(code) << " " << name << std::endl;
+  log_debug << "add_key: " << key2str(code) << " " << name << std::endl;
 
   if (!key_lst[code])
   {
@@ -225,7 +226,7 @@ LinuxUinput::finish()
   user_dev.id.vendor  = vendor;
   user_dev.id.product = product;
 
-  log_info << "'" << user_dev.name << "' " << user_dev.id.vendor << ":" << user_dev.id.product << std::endl;
+  log_debug << "'" << user_dev.name << "' " << user_dev.id.vendor << ":" << user_dev.id.product << std::endl;
 
   if (ff_bit)
     user_dev.ff_effects_max = ff_handler->get_max_effects();
@@ -240,19 +241,17 @@ LinuxUinput::finish()
     }
     else
     {
-      log_info << "write return value: " << write_ret << std::endl; 
+      log_debug << "write return value: " << write_ret << std::endl; 
     }
   }
 
   // FIXME: check that the config isn't empty and give a more
   // meaningful message when it is
 
-  log_info << "finish" << std::endl;
+  log_debug << "finish" << std::endl;
   if (ioctl(fd, UI_DEV_CREATE))
   {
-    std::ostringstream out;
-    out << "LinuxUinput: Unable to create UINPUT device: '" << name << "': " << strerror(errno);
-    throw std::runtime_error(out.str());
+    raise_exception(std::runtime_error, "unable to create uinput device: '" << name << "': " << strerror(errno));
   }
 
   m_finished = true;
diff --git a/src/log.hpp b/src/log.hpp
index 37daa39..4705d7d 100644
--- a/src/log.hpp
+++ b/src/log.hpp
@@ -38,7 +38,7 @@ std::string log_pretty_print(const std::string& str);
 #define log_error (std::cout << log_pretty_print(__PRETTY_FUNCTION__) << ": ")
 
 /** extra verbose debugging messages */
-#define log_debug (std::cout << log_pretty_print(__PRETTY_FUNCTION__) << ": ")
+#define log_debug if (true); else (std::cout << log_pretty_print(__PRETTY_FUNCTION__) << ": ")
 
 #endif
 
diff --git a/src/uinput.cpp b/src/uinput.cpp
index 9375936..837cf8a 100644
--- a/src/uinput.cpp
+++ b/src/uinput.cpp
@@ -90,7 +90,7 @@ UInput::create_uinput_device(uint32_t device_id)
   }
   else
   {
-    log_info << "create device: " << device_id << std::endl;
+    log_debug << "create device: " << device_id << std::endl;
     LinuxUinput::DeviceType device_type = LinuxUinput::kGenericDevice;
     std::ostringstream dev_name;
     dev_name << "Xbox Gamepad (userspace driver)";
@@ -119,7 +119,7 @@ UInput::create_uinput_device(uint32_t device_id)
     boost::shared_ptr<LinuxUinput> dev(new LinuxUinput(device_type, dev_name.str(), 0x0000, 0x0000));
     uinput_devs.insert(std::pair<int, boost::shared_ptr<LinuxUinput> >(device_id, dev));
 
-    std::cout << "Creating uinput device: device_id: " << device_id << ", dev_name: " << dev_name.str() << std::endl;
+    log_debug << "created uinput device: " << device_id << " - '" << dev_name.str() << "'" << std::endl;
 
     return dev.get();
   }
diff --git a/src/xbox360_controller.cpp b/src/xbox360_controller.cpp
index 50043f4..9ff068a 100644
--- a/src/xbox360_controller.cpp
+++ b/src/xbox360_controller.cpp
@@ -41,15 +41,13 @@ Xbox360Controller::Xbox360Controller(libusb_device* dev_,
   m_headset()
 {
   find_endpoints();
-  if (false)
-  {
-    std::cout << "EP(IN):  " << endpoint_in << std::endl;
-    std::cout << "EP(OUT): " << endpoint_out << std::endl;
-  }
-
+  
+  log_debug << "EP(IN):  " << endpoint_in << std::endl;
+  log_debug << "EP(OUT): " << endpoint_out << std::endl;
+  
   int ret = libusb_open(dev, &handle);
 
-  if (0)
+  if (0) // not needed I guess
   {
     int err;
     if ((err = libusb_set_configuration(handle, 0)) < 0)
@@ -62,7 +60,7 @@ Xbox360Controller::Xbox360Controller(libusb_device* dev_,
 
   if (ret != LIBUSB_SUCCESS)
   {
-    throw std::runtime_error("Error opening Xbox360 controller");
+    raise_exception(std::runtime_error, "libusb_open() failed: " << usb_strerror(ret));
   }
   else
   {
@@ -235,13 +233,10 @@ Xbox360Controller::read(XboxGenericMsg& msg, bool verbose, int timeout)
   }
   else if (len == 3 && data[0] == 0x08 && data[1] == 0x03)
   {
-    if (!g_options->quiet)
-    {
-      if (data[2] == 0x00)
-        std::cout << "Headset: none";
-      else if (data[2] == 0x02)
-        std::cout << "Headset: none";
-    }
+    if (data[2] == 0x00)
+      log_info << "headset: none" << std::endl;
+    else if (data[2] == 0x02)
+      log_info << "headset: none" << std::endl;
   }
   else if (len == 20 && data[0] == 0x00 && data[1] == 0x14)
   {
@@ -251,8 +246,7 @@ Xbox360Controller::read(XboxGenericMsg& msg, bool verbose, int timeout)
   }
   else
   {
-    std::cout << "Unknown: ";
-    print_raw_data(std::cout, data, len);
+    log_debug << "unknown: " << raw2str(data, len) << std::endl;
   }
 
   return false;
diff --git a/src/xbox360_wireless_controller.cpp b/src/xbox360_wireless_controller.cpp
index 0308d8d..c49dc8b 100644
--- a/src/xbox360_wireless_controller.cpp
+++ b/src/xbox360_wireless_controller.cpp
@@ -45,17 +45,16 @@ Xbox360WirelessController::Xbox360WirelessController(libusb_device* dev_, int co
   const int ret = libusb_open(dev, &handle);
   if (ret != LIBUSB_SUCCESS)
   {
-    throw std::runtime_error("Xbox360WirelessController: Error opening Xbox360 controller");
+    raise_exception(std::runtime_error, "libusb_open() failed: " << usb_strerror(ret));
   }
   else
   {
     int err = usb_claim_n_detach_interface(handle, interface, try_detach);
     if (err != 0) 
     {
-      std::ostringstream out;
-      out << "Error couldn't claim the USB interface: " << usb_strerror(err) << std::endl
-          << "Try to run 'rmmod xpad' and then xboxdrv again or start xboxdrv with the option --detach-kernel-driver.";
-      throw std::runtime_error(out.str());
+      raise_exception(std::runtime_error,
+                      "Error couldn't claim the USB interface: " << usb_strerror(err) << std::endl <<
+                      "Try to run 'rmmod xpad' and then xboxdrv again or start xboxdrv with the option --detach-kernel-driver.");
     }
   }
 }
@@ -121,25 +120,25 @@ Xbox360WirelessController::read(XboxGenericMsg& msg, bool verbose, int timeout)
   { // Connection Status Message
     if (data[1] == 0x00) 
     {
-      std::cout << "Connection status: nothing" << std::endl;
+      log_info << "Connection status: nothing" << std::endl;
     } 
     else if (data[1] == 0x80) 
     {
-      std::cout << "Connection status: controller connected" << std::endl;
+      log_info << "Connection status: controller connected" << std::endl;
       set_led(led_status);
     } 
     else if (data[1] == 0x40) 
     {
-      std::cout << "Connection status: headset connected" << std::endl;
+      log_info << "Connection status: headset connected" << std::endl;
     }
     else if (data[1] == 0xc0) 
     {
-      std::cout << "Connection status: controller and headset connected" << std::endl;
+      log_info << "Connection status: controller and headset connected" << std::endl;
       set_led(led_status);
     }
     else
     {
-      std::cout << "Connection status: unknown" << std::endl;
+      log_info << "Connection status: unknown" << std::endl;
     }
   }
   else if (len == 29)
@@ -155,8 +154,8 @@ Xbox360WirelessController::read(XboxGenericMsg& msg, bool verbose, int timeout)
                 % int(data[12])
                 % int(data[13])).str();
       battery_status = data[17];
-      std::cout << "Serial: " << serial << std::endl;
-      std::cout << "Battery Status: " << battery_status << std::endl;
+      log_info << "Serial: " << serial << std::endl;
+      log_info << "Battery Status: " << battery_status << std::endl;
     }
     else if (data[0] == 0x00 && data[1] == 0x01 && data[2] == 0x00 && data[3] == 0xf0 && data[4] == 0x00 && data[5] == 0x13)
     { // Event message
@@ -167,7 +166,7 @@ Xbox360WirelessController::read(XboxGenericMsg& msg, bool verbose, int timeout)
     else if (data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x00 && data[3] == 0x13)
     { // Battery status
       battery_status = data[4];
-      std::cout << "Battery Status: " << battery_status << std::endl;
+      log_info << "Battery Status: " << battery_status << std::endl;
     }
     else if (data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x00 && data[3] == 0xf0)
     {
@@ -176,8 +175,7 @@ Xbox360WirelessController::read(XboxGenericMsg& msg, bool verbose, int timeout)
     }
     else
     {
-      std::cout << "Unknown: ";
-      print_raw_data(std::cout, data, len);
+      log_debug << "unknown: " << raw2str(data, len) << std::endl;
     }
   }
   else if (len == 0)
@@ -186,8 +184,7 @@ Xbox360WirelessController::read(XboxGenericMsg& msg, bool verbose, int timeout)
   }
   else
   {
-    std::cout << "Unknown: ";
-    print_raw_data(std::cout, data, len);
+    log_debug << "unknown: " << raw2str(data, len) << std::endl;
   }
 
   return false;
diff --git a/src/xbox_controller.cpp b/src/xbox_controller.cpp
index 52cadd8..13d9ced 100644
--- a/src/xbox_controller.cpp
+++ b/src/xbox_controller.cpp
@@ -22,6 +22,7 @@
 #include <stdexcept>
 #include <string.h>
 
+#include "log.hpp"
 #include "usb_helper.hpp"
 #include "raise_exception.hpp"
 #include "xboxmsg.hpp"
@@ -36,7 +37,7 @@ XboxController::XboxController(libusb_device* dev_, bool try_detach) :
   int ret = libusb_open(dev, &handle);
   if (ret != LIBUSB_SUCCESS)
   {
-    throw std::runtime_error("Error opening Xbox360 controller");
+    raise_exception(std::runtime_error, "libusb_open() failed: " << usb_strerror(ret));
   }
   else
   {
@@ -44,10 +45,9 @@ XboxController::XboxController(libusb_device* dev_, bool try_detach) :
     int err = usb_claim_n_detach_interface(handle, 0, try_detach);
     if (err != 0) 
     {
-      std::ostringstream out;
-      out << "Error couldn't claim the USB interface: " << strerror(-err) << std::endl
-          << "Try to run 'rmmod xpad' and then xboxdrv again or start xboxdrv with the option --detach-kernel-driver.";
-      throw std::runtime_error(out.str());
+      raise_exception(std::runtime_error,
+                      "Error couldn't claim the USB interface: " << strerror(-err) << std::endl <<
+                      "Try to run 'rmmod xpad' and then xboxdrv again or start xboxdrv with the option --detach-kernel-driver.");
     }
   }
 }
@@ -143,10 +143,8 @@ XboxController::read(XboxGenericMsg& msg, bool verbose, int timeout)
     return false;
   }
   else if (ret != LIBUSB_SUCCESS)
-  { // Error
-    std::ostringstream str;
-    str << "USBError: " << ret << "\n" << usb_strerror(ret);
-    throw std::runtime_error(str.str());
+  {
+    raise_exception(std::runtime_error, "libusb_interrupt_transfer() failed: " << usb_strerror(ret));
   }
   else if (len == 20 && data[0] == 0x00 && data[1] == 0x14)
   {
diff --git a/src/xboxdrv_daemon.cpp b/src/xboxdrv_daemon.cpp
index 33dd89f..b76b922 100644
--- a/src/xboxdrv_daemon.cpp
+++ b/src/xboxdrv_daemon.cpp
@@ -80,7 +80,9 @@ XboxdrvDaemon::cleanup_threads()
 
   if (count > 0)
   {
-    log_info << "cleaned up " << count << " thread(s)" << std::endl;
+    log_info << "cleaned up " << count << " thread(s), free slots: " 
+             << get_free_slot_count() << "/" << m_controller_slots.size()
+             << std::endl;
   }
 }
 
@@ -124,11 +126,7 @@ XboxdrvDaemon::process_match(const Options& opts, UInput* uinput, struct udev_de
           if (find_xpad_device(vendor, product, &dev_type))
           {
             // 3) Launch thread to handle the device
-            log_info << "Found a valid Xboxdrv controller: " << busnum_str << ":" << devnum_str 
-                     << " -- "
-                     << boost::lexical_cast<int>(busnum_str) << ", "
-                     << boost::lexical_cast<int>(devnum_str)
-                     << std::endl;
+            log_info << "controller detected at " << busnum_str << ":" << devnum_str << std::endl;
            
             try 
             {
@@ -145,7 +143,7 @@ XboxdrvDaemon::process_match(const Options& opts, UInput* uinput, struct udev_de
         }
         catch(const std::exception& err)
         {
-          std::cout << "[XboxdrvDaemon] child thread lauch failure: " << err.what() << std::endl;
+          log_error << "child thread lauch failure: " << err.what() << std::endl;
         }
       }
     }
@@ -161,7 +159,7 @@ XboxdrvDaemon::run(const Options& opts)
   }
   catch(const std::exception& err)
   {
-    log_error << "fatal exception in XboxdrvDaemon::run(): " << err.what() << std::endl;
+    log_error << "fatal exception: " << err.what() << std::endl;
   }
 }
 
@@ -188,7 +186,7 @@ XboxdrvDaemon::run_real(const Options& opts)
   std::auto_ptr<UInput> uinput;
   if (!opts.no_uinput)
   {
-    if (!opts.quiet) std::cout << "Starting with uinput" << std::endl;
+    log_info << "starting with UInput" << std::endl;
 
     uinput.reset(new UInput());
 
@@ -202,11 +200,12 @@ XboxdrvDaemon::run_real(const Options& opts)
   }
   else
   {
-    if (!opts.quiet)
-      std::cout << "Starting without uinput" << std::endl;
+    log_info << "starting without UInput" << std::endl;
   }
 
-  { // create controller slots
+  if (uinput.get())
+  {
+    // create controller slots
     int slot_count = 0;
 
     for(Options::ControllerSlots::const_iterator controller = opts.controller_slots.begin(); 
@@ -225,6 +224,11 @@ XboxdrvDaemon::run_real(const Options& opts)
     // the device creation
     uinput->finish();
   }
+  else
+  {
+    // just create some empty controller slots
+    m_controller_slots.resize(opts.controller_slots.size());
+  }
 
   // Setup udev monitor and enumerate
   m_monitor = udev_monitor_new_from_netlink(m_udev, "udev");
@@ -393,13 +397,6 @@ XboxdrvDaemon::launch_xboxdrv(UInput* uinput, const XPadDevice& dev_type, const
     }
     else
     {
-      std::cout << "[XboxdrvDaemon] launching " << boost::format("%03d:%03d")
-        % static_cast<int>(busnum) 
-        % static_cast<int>(devnum)
-                << std::endl;
-
-      log_info << "found a free slot: " << (it - m_controller_slots.begin()) << std::endl;
-
       std::auto_ptr<XboxGenericController> controller = XboxControllerFactory::create(dev_type, dev, opts);
 
       std::auto_ptr<MessageProcessor> message_proc;
@@ -414,8 +411,32 @@ XboxdrvDaemon::launch_xboxdrv(UInput* uinput, const XPadDevice& dev_type, const
       std::auto_ptr<XboxdrvThread> thread(new XboxdrvThread(message_proc, controller, opts));
       thread->start_thread(opts);
       it->thread = thread.release();
+
+      log_info << "launched XboxdrvThread for " << boost::format("%03d:%03d")
+        % static_cast<int>(busnum) 
+        % static_cast<int>(devnum)
+               << " in slot " << (it - m_controller_slots.begin())
+               << ", free slots: " 
+               << get_free_slot_count() << "/" << m_controller_slots.size()
+               << std::endl;
     }
   }
 }
 
+int
+XboxdrvDaemon::get_free_slot_count() const
+{
+  int slot_count = 0;
+
+  for(ControllerSlots::const_iterator i = m_controller_slots.begin(); i != m_controller_slots.end(); ++i)
+  {
+    if (i->thread == 0)
+    {
+      slot_count += 1;
+    }
+  }
+
+  return slot_count;
+}
+
 /* EOF */
diff --git a/src/xboxdrv_daemon.hpp b/src/xboxdrv_daemon.hpp
index 29d436b..8f24bed 100644
--- a/src/xboxdrv_daemon.hpp
+++ b/src/xboxdrv_daemon.hpp
@@ -86,6 +86,7 @@ private:
   void launch_xboxdrv(UInput* uinput,
                       const XPadDevice& dev_type, const Options& opts, 
                       uint8_t busnum, uint8_t devnum);
+  int get_free_slot_count() const;
   
 private:
   XboxdrvDaemon(const XboxdrvDaemon&);