#include "Server.h"

namespace Server
{
	struct sockaddr_rc loc_addr, rem_addr;
	char buf[1024] = { 0 };
	int s, client, bytes_read;
	socklen_t opt = sizeof rem_addr;
}

void Server::sInit()
{
	// allocate socket
	s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);

	// bind socket to port 1 of the first available 
	// local bluetooth adapter
	loc_addr.rc_family = AF_BLUETOOTH;
	loc_addr.rc_bdaddr = (bdaddr_t) { {0, 0, 0, 0, 0, 0} };
	loc_addr.rc_channel = (uint8_t)1;
	bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
}

string Server::sListen()
{
	// put socket into listening mode
	listen(s, 1);

	// accept one connection
	client = accept(s, (struct sockaddr *)&rem_addr, &opt);

	ba2str(&rem_addr.rc_bdaddr, buf);
	
	return buf;
}

string Server::sReadMessage()
{
	memset(buf, 0, sizeof(buf));
	// read data from the client
	read(client, buf, sizeof(buf));

	return buf;
}

void Server::sDisconnect()
{
	// close connection
	close(client);
	close(s);
}