#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include "qxwz_ids_log.h"
#include "qxwz_gpsd_adpt.h"
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
#define TAG "GPSD"
typedef struct qxGpsdAdpt {
int pts_fd;
void *private_data;
}qxGpsdAdpt;
QXWZ_IDS_PUBLIC(qxGpsdAdpt*) qxwz_gpsdadpt_create()
{
ENTER();
char *name;
int res;
FILE *pts_fp;
int flags;
char cmd_buf[256]={0};
//char *cmd_format="export GPSD_SOCKET=/var/run/gpsd.sock;gpsdctl add %s";
char *cmd_format="gpsdctl add %s";
pthread_mutex_lock(&g_lock);
qxGpsdAdpt * p = (qxGpsdAdpt *)malloc(sizeof(qxGpsdAdpt));
if (!p) {
QXLOGE(TAG,"memory error \n");
goto err1;
}
memset(p,0,sizeof(*p));
p->pts_fd=posix_openpt(O_RDWR|O_NOCTTY);
if(p->pts_fd){
res = grantpt(p->pts_fd);
if (res != 0){
QXLOGE(TAG,"grantpt() error \n");
}
res = unlockpt(p->pts_fd);
if (res != 0){
QXLOGE(TAG,"unlockpt() error \n");
}
flags = fcntl(p->pts_fd, F_GETFL, 0);
fcntl(p->pts_fd, F_SETFL, flags | O_NONBLOCK);
name=ptsname(p->pts_fd);
if(name){
QXLOGD(TAG,"ptsname() :%s \n",name);
}
res = chmod(name,0666);
if (res != 0){
QXLOGE(TAG,"chmod() error:%s \n",strerror(errno));
}
sprintf(cmd_buf,cmd_format,name);
QXLOGD(TAG,"cmd_buf:%s \n",cmd_buf);
pts_fp = popen(cmd_buf,"r");
fclose(pts_fp );
}
pthread_mutex_unlock(&g_lock);
QXLOGI(TAG,"Leave success \n");
LEAVE();
return p;
err1:
pthread_mutex_unlock(&g_lock);
QXLOGI(TAG,"Leave failed \n");
return NULL;
}
QXWZ_IDS_PUBLIC(int) qxwz_gpsdadpt_post_data(qxGpsdAdpt *handle,char *buf,int len)
{
ENTER();
ssize_t ret;
if(!handle ||!buf){
QXLOGE(TAG,"invalid handle \n");
return -1;
}
#if 1
//if((strstr(buf,"GGA"))|| (strstr(buf,"RMC"))|| (strstr(buf,"TXT"))) {
ret = write(handle->pts_fd, buf, len);
if(ret < 0){
QXLOGE(TAG,"loss :%d \n",len);
}
// }
#endif
// QXLOGD(TAG,"ret:%ld \n",ret);
LEAVE();
return 0;
}
QXWZ_IDS_PUBLIC(void) qxwz_gpsdadpt_destroy(qxGpsdAdpt *handle)
{
ENTER();
if(!handle){
QXLOGE(TAG,"invalid handle \n");
return ;
}
if(handle->pts_fd){
close(handle->pts_fd);
}
// gpsdctl del %s
free(handle);
//todo
LEAVE();
}