00001 
00002 
00003 
00004 
00005 
00006 
00007 
00008 
00009 
00010 
00011 
00012 
00013 
00014 
00015 
00016 
00017 
00018 
00019 
00020 
00021 
00022 #include <errno.h>
00023 #include <sys/types.h>
00024 #include <sys/socket.h>
00025 #include <netdb.h>
00026 #include <netinet/in.h>
00027 #include <string>
00028 
00029 #include "gpsd_position.hh"
00030 
00031 using namespace std;
00032 
00033 
00034 GPSDPosition::GPSDPosition(char* host, int port) throw(DeviceError) :
00035     socket_fd(-1), gpsd_host(host), gpsd_port(port)
00036 {
00037     struct sockaddr_in address;
00038     if( (socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
00039         throw DeviceError(string("Error creating TCP socket: ") + strerror(errno));
00040     }
00041     struct hostent* he;
00042     if(!(he = gethostbyname(gpsd_host))) {
00043         throw DeviceError(string("Invalid address for GPS daemon: ") + gpsd_host);
00044     }
00045     memset(&address, 0, sizeof(address));
00046     address.sin_port=htons(gpsd_port);
00047     address.sin_family=AF_INET;
00048     address.sin_addr=*((struct in_addr *)he->h_addr);
00049     if( connect(socket_fd, (struct sockaddr *)&address, sizeof(address)) == -1)
00050 {
00051         char port_s[16];
00052         sprintf(port_s, "%d", gpsd_port);
00053         throw DeviceError(string("Error connecting to GPS daemon ") + gpsd_host + ":" + port_s + ". " + strerror(errno));
00054     }
00055 }
00056 
00057 
00058 GPSDPosition::~GPSDPosition() {
00059     if ( shutdown(socket_fd, 2) < 0 ) {
00060         fprintf(stderr, "GPSDPosition: Warning: error closing socket. %s\n",  strerror(errno));
00061     }
00062 }
00063 
00064 
00065 
00066 
00067 
00068 
00069 
00070 
00071 
00072 
00073 
00074 
00075 
00076 
00077 
00078 
00079 
00080 
00081 
00082 
00083 
00084 
00085 void GPSDPosition::getPosition(double *x, double *y, double *z) throw(DeviceError) {
00086     char msg[128];
00087     int nrecvd;
00088 
00089     if(send(socket_fd, "P\n", 2, 0) != 2)
00090         throw DeviceError("Error sending command to gpsd!");
00091     nrecvd = recv(socket_fd, msg, 128, 0);
00092     sscanf(msg, "GPSD,P=%lf %lf", x, z);
00093 
00094     if(send(socket_fd, "A\n", 2, 0) != 2)
00095         throw DeviceError("Error sending command to gpsd!");
00096     nrecvd = recv(socket_fd, msg, 128, 0);
00097     sscanf(msg, "GPSD,A=%lf", y);
00098 
00099     *x *= xScale;
00100     *y *= yScale;
00101     *z *= zScale;
00102     *x += xOffset;
00103     *y += yOffset;
00104     *z += zOffset;
00105 }
00106 
00107 
00108 int GPSDPosition::getStatus() throw(DeviceError){
00109     int status;
00110     char msg[128];
00111     if(send(socket_fd, "S\n", 2, 0) != 2) {
00112         throw DeviceError("Error sending command to gpsd!");
00113         return -1;
00114     }
00115     recv(socket_fd, msg, 128, 0);
00116     sscanf(msg, "GPSD,S=%d", &status);
00117     return status;
00118 }