#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import usb
import time
import daemon
import socket

VENDOR_ID = 0x1130;
PRODUCT_ID = 0x0202;
CONFIG_NO = 1;
INTERFACE_NO = 0;
INTERFACES_NUM = 2;

REQTYPE = 0xA1;
REQ = 0x1;
VAL = 0x300;
GET_SIZE = 8;
TIMEOUT = 100;

SERVER = "localhost"
SERVER_TCP_PORT = 6666


class DeviceDescriptor(object) :
    def __init__(self, vendor_id, product_id, interface_id) :
        self.vendor_id = vendor_id
        self.product_id = product_id
        self.interface_id = interface_id

    def getDevice(self) :
        """
        Return the device corresponding to the device descriptor if it is
        available on a USB bus.  Otherwise, return None.  Note that the
        returned device has yet to be claimed or opened.
        """
        buses = usb.busses()
        for bus in buses :
            for device in bus.devices :
                if device.idVendor == self.vendor_id :
                    if device.idProduct == self.product_id :
                        return device
        return None


class PanicButton(object):
    
    def __init__(self):
        # Get the button
        button = DeviceDescriptor(VENDOR_ID, PRODUCT_ID, None).getDevice()

        if not button:
            print "Cannot find USB Panic Button"
            sys.exit(1)

        # Open the USB Device
        handle = button.open()
        
        # Detach any kernel drivers
        for i in range(INTERFACES_NUM):
            try:
                handle.detachKernelDriver(i)
            except usb.USBError, e:
                if "No data available" not in str(e):
                    raise
        
        # Get the right interface
        handle.setConfiguration(CONFIG_NO)
        handle.claimInterface(INTERFACE_NO)
        self.handle = handle


    def pressed(self):
        # Send the "eh up" message
        pressed =  self.handle.controlMsg(REQTYPE, REQ, GET_SIZE, VAL, 0, TIMEOUT)[0]
        return bool(pressed)
        
with daemon.DaemonContext():
  while 1:
    if PanicButton().pressed():
      print "!!! PANIC !!!"
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    # create a TCP socket
      s.connect((SERVER, SERVER_TCP_PORT)) 	# connect to server on the port
      s.send("mario:  [margherita_big]\n") 	# send the data
      data = s.recv(1024)                 	#receive up to 1K bytes
      print data
      s.close()					#close the socket
      success = str.strip(data)
      time.sleep(0.02)
