#!/usr/bin/python
import string
import time
import bluetooth
import sys


bd_addr = "98:D3:31:B2:35:33" #itade address
port = 1

sampleTime = 1
numSamples = 5
lastTemp = 0


def connect():
    while(True):    
        try:
            gaugeSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
            gaugeSocket.connect((bd_addr, port))
            print 'Connected'
            break;
        except bluetooth.btcommon.BluetoothError as error:
            gaugeSocket.close()
            print "Could not connect: ", error, "; Retrying in 10s..."
            time.sleep(10)
    return gaugeSocket;

def recv_timeout(the_socket,timeout=2000):
    #make socket non blocking
    the_socket.setblocking(0)
     
    #total data partwise in an array
    total_data=[];
    data='';
     
    #beginning time
    begin=time.time()
    while 1:
        #if you got some data, then break after timeout
        if total_data and time.time()-begin > timeout:
            print "if you got some data, then break after timeout"
            break
         
        #if you got no data at all, wait a little longer, twice the timeout
        elif time.time()-begin > timeout*2:
            print "if you got no data at all, wait a little longer, twice the timeout"
            break
         
        #recv something
        try:
            data = the_socket.recv(8192)
            print "ricevuto qualcosa %s" % data
            if data:
                total_data.append(data)
                print len(total_data)
                if len(total_data)==2:
                  print "sono qui"
                  break;
                #change the beginning time for measurement
                begin=time.time()
                
            else:
                #sleep for sometime to indicate a gap
                time.sleep(0.1)
        except:
            pass
    print "esco"
    #join all parts to make final string
    return ''.join(total_data)
 



gaugeSocket = connect()
while(True):
    try:
        print sys.argv[1]
        gaugeSocket.send(sys.argv[1])
        print 'Sent data'
        #data = gaugeSocket.recv(1024)
        #print len(data)
        #print 'received [%s]' % data
        print recv_timeout(gaugeSocket)
        break

    except bluetooth.btcommon.BluetoothError as error:
        print "Caught BluetoothError: ", error
        time.sleep(5)
        gaugeSocket = connect()
        pass

gaugeSocket.close()

