#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>

#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/rfcomm.h>

int btopen( const char* addr, int chan )
{
	struct sockaddr_rc remote_addr, local_addr;
	bdaddr_t bdaddr;
	int s, r;

	str2ba(addr, &bdaddr);
	if ((s = socket(PF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM)) < 0) {
		perror("socket()");
		return -1;
	}

	memset(&local_addr, 0, sizeof(local_addr));
	local_addr.rc_family = AF_BLUETOOTH;
	bacpy(&local_addr.rc_bdaddr, BDADDR_ANY);
	if (bind(s, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0) {
		perror("bind()");
		close(s);
		return -1;
	}

	if ( fcntl( s, F_SETFL, fcntl( s, F_GETFL ) | O_NONBLOCK ) < 0 )
		perror("fcntl()");

	memset(&remote_addr, 0, sizeof(remote_addr));
	remote_addr.rc_family = AF_BLUETOOTH;
	bacpy(&remote_addr.rc_bdaddr, &bdaddr);
	remote_addr.rc_channel = chan;
	if ( r = connect(s, (struct sockaddr *)&remote_addr, sizeof(remote_addr)) < 0)
		perror("connect()");
	
	//here returns -1 with EAGAIN (11) = Resource temporarily unavailable
	//EINPROGRESS is expected???

	return s;
}

int main( int argc, char** argv )
{
	int fd, r;
	fd_set wfds;
	socklen_t optlen;

	if ( argc < 3 )
	{
		printf("Use: bluetalk <address> <channel>\n");
		exit( 1 );
	}
	printf("Opening socket...\n");	
	if ( ( fd = btopen( argv[1], atoi( argv[2] ) ) ) < 0 )
		exit(1);

	printf("Waiting for open completion...\n");
	r = select(fd + 1, NULL, &wfds, NULL, &tv);
	if (r<0){
		perror("select()");
		close(fd);
		exit(1);
	}
	else
		printf("success\n");

	//check if connect() succeded
	getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&r, &optlen);	
	//here  r=0 in case of success or r=errno otherwise
	printf("len=%d, r=%d\n", optlen, r);

	printf("Closing socket...\n");
	close( fd );

	return 0;
}
