owlps/owlps-positioning/src/outputudpsocket.cc

99 lines
1.9 KiB
C++
Raw Normal View History

#include "outputudpsocket.hh"
2011-03-15 15:27:42 +01:00
#include "request.hh"
#include "resultlist.hh"
#include "posexcept.hh"
#include <owlps.h>
2011-03-15 15:27:42 +01:00
#include <sstream>
#include <cstdio> // For perror()
2011-03-15 15:27:42 +01:00
using namespace std ;
/* *** Constructors *** */
OutputUDPSocket::OutputUDPSocket(const string &_remote_host,
const uint_fast16_t _remote_port):
remote_host(_remote_host), remote_port(_remote_port)
2011-03-15 15:27:42 +01:00
{
if (! init_socket())
throw error_opening_output_file("UDP socket") ;
}
2011-03-15 15:27:42 +01:00
OutputUDPSocket::~OutputUDPSocket()
2011-03-15 15:27:42 +01:00
{
close_socket() ;
2011-03-15 15:27:42 +01:00
}
/* *** Operations *** */
/**
* @return \em true if the socket were successfully opened.
* @return \em false in case of error.
*/
bool OutputUDPSocket::init_socket()
{
sockfd = owl_create_udp_trx_socket(remote_host.c_str(), remote_port,
&server_info, &client_info) ;
return sockfd >= 0 ;
}
/**
* Normally, the socket is closed automatically by the destructor. Use
* this if you want to close the socket prematurely.
* #sockfd is set to -1, even in case of error.
* @return \em true if the socket were successfully closed or were not
* opened.
* @return \em false in case of error.
*/
bool OutputUDPSocket::close_socket()
2011-03-15 15:27:42 +01:00
{
if (sockfd >= 0)
{
if (close(sockfd))
{
perror("Cannot close UDP socket") ;
return false ;
}
2011-03-15 15:27:42 +01:00
sockfd = -1 ;
}
2011-03-15 15:27:42 +01:00
return true ;
2011-03-15 15:27:42 +01:00
}
void OutputUDPSocket::write(const Result &result)
2011-03-15 15:27:42 +01:00
{
send_data(result.to_csv()) ;
2011-03-15 15:27:42 +01:00
}
void OutputUDPSocket::write(const ResultList &results)
2011-03-15 15:27:42 +01:00
{
if (! results.empty())
send_data(results.to_csv()) ;
2011-03-15 15:27:42 +01:00
}
/**
* Sends the text buffer 'data'.
*/
void OutputUDPSocket::send_data(const string &data)
{
ssize_t nsent = sendto(sockfd, data.c_str(), data.size(), 0,
(struct sockaddr *) &server_info,
sizeof(server_info)) ;
if (nsent != static_cast<ssize_t>(data.size()))
perror("Error sending result data") ;
}