该代码实现的功能有:
1,参数解析
2,获取不同序列号下的温度
3,连接客户端
4,向服务器发送相关消息
5,获取时间
6,查询数据库中的信息并发送到服务器
7.回调查询打印数据库里的信息
/*********************************************************************************
* Copyright: (C) 2023 yangjian<YJyangjian183@gmail.com>
* All rights reserved.
*
* Filename: fun.c
* Description: This file function
*
* Version: 1.0.0(2023年10月05日)
* Author: yangjian <YJyangjian183@gmail.com>
* ChangeLog: 1, Release initial version on "2023年10月05日 15时24分34秒"
*
********************************************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
#include <getopt.h>
#include "fun.h"
#include <sqlite3.h>
#include "logger.h"
int Getdatafrommain(int argc, char *argv[], struct Constants *constants)
{
int opt;
constants->port = -1;
constants->time = -1;
constants->servip = NULL;
constants->help =NULL;
static struct option long_options[] =
{
{"port", required_argument, 0, 'p'},
{"time", required_argument, 0, 't'},
{"ip", required_argument, 0, 'i'},
{"help",required_argument,0, 'h'},
{0, 0, 0, 0}
};
while ((opt = getopt_long(argc, argv, "p:t:i:h:", long_options, NULL)) != -1)
{
switch (opt)
{
case 'p':
constants->port = atoi(optarg); // 将参数转换为整数
break;
case 't':
constants->time = atoi(optarg); // 将参数转换为整数
break;
case 'i':
constants->servip = strdup(optarg); // 复制参数值作为 IP 地址
break;
case '?':
default:
print_help(argv[0]);
log_message(LOG_DEBUG,__FILE__,__LINE__,"输入参数错误\n");
return 0; // 参数解析失败
}
}
return 1;
}
void print_help(char *progname)
{
printf("%s usage:\n",progname);
printf("-i(--ipaddr):server ip address\n");
printf("-p(--port):server port\n");
printf("-t(--time):how long (s) do you want send\n");
}
int MYconnect(char *servip,int port)
{
int fd=-1;
struct sockaddr_in servaddr;
int rv=-1;
printf("the server ip : %s and port : %d\n",servip,port);
fd=socket(AF_INET,SOCK_STREAM,0);
if(fd<0)
{
printf("The socket is failure:%s\n",strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"error:%s",strerror(errno));
return -1;
}
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family =AF_INET;
servaddr.sin_port = htons(port);
inet_aton(servip,&servaddr.sin_addr);
rv=connect(fd,(struct sockaddr *)&servaddr,sizeof(servaddr));
if(rv<0)
{
printf("Connect to server[%s:%d] failure:\n%s\n",servip,port,strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"error:Conect to server[%s:%d] faillure:%s",servip,port,strerror(errno));
return -2;
}
printf("connect is successfuly\n");
log_message(LOG_INFO, __FILE__,__LINE__,"connect successfuly");
return fd;
}
int Get_temp(float *temp,char* Se_nub)
{
*temp=21.2300;
strncpy(Se_nub,"12234456",sizeof(Se_nub));
return 0;
}
#if 0
int Get_temp(float *temp,char* Se_nub)
{
static char w1_path[128]="/sys/bus/w1/devices/";
DIR *dirp=NULL;
struct dirent *direntp=NULL;
char path2[64];
char buf[128];
int fd=-1;
char *ptr=NULL;
static int n=0;
if(n)
{
goto NEXT;
}
dirp=opendir(w1_path);
if(!dirp)
{
printf("Open dir:%s failure:%s",w1_path,strererrno));
log_message(LOG_ERROR, __FILE__,__LINE__,"open failure:%s",strerror(errno));
return -1;
}
while(NULL!=(direntp=readdir(dirp)))
{
if(strstr(direntp->d_name,"28-"))
{
strncpy(path2,direntp->d_name,sizeof(path2));
n=1;
}
}
if(!n)
{
printf("Can't find dir\n");
log_message(LOG_ERROR, __FILE__,__LINE__,"cant not find dir");
}
closedir(dirp);
strncat(w1_path,path2,sizeof(w1_path)-strlen(w1_path));
strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));
strcpy(Se_nub,path2);
NEXT:
if((fd=open(w1_path,O_RDONLY))<0)
{
printf("Open dir %s failure:%s\n",w1_path,strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"opendir all failure:%s",strerror(errno));
return -2;
}
memset(buf,0,sizeof(buf));
if((read(fd,buf,sizeof(buf)))<0)
{
printf("Read dir %s failure %s\n",w1_path,strerror(errno));
return -3;
}
printf("What want to path is :\n%s\n",w1_path);
printf("____________________________________\n");
printf("\n");
ptr=strstr(buf,"t=");
if(!ptr)
{
printf("Can not find temp data from buf\n");
log_message(LOG_ERROR, __FILE__,__LINE__,"can't find temp data");
return -4;
}
ptr +=2;
*temp=(atof(ptr))/1000;
close(fd);
return 0;
}
#endif
//这是发送刚刚获取的信息
int Send_data(char *buf,int fd,char * Se_nub,char* timebuf )
{
printf("this is in Send buf:%s\n",buf);
printf("this is in Send senub:%s\n",Se_nub);
printf("this is in Send timebuf:%s\n",timebuf);
uint32_t message_lengthbuf = strlen(buf);//长度
uint32_t message_lengthnub = strlen(Se_nub);
uint32_t message_lengthtime = strlen(timebuf);
message_lengthbuf = htonl(message_lengthbuf);//使用网络字节序
message_lengthnub = htonl(message_lengthnub);
message_lengthtime = htonl(message_lengthtime);
//发送消息长度
if(send(fd, &message_lengthbuf, sizeof(message_lengthbuf), 0) == -1)
{
printf("send lengthbuf data failure:%s\n",strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"send temp_length fialure:%s",strerror(errno));
return -1;
}
if(send(fd,buf,strlen(buf),0)==-1)
{
printf("send buf failure:%s\n",strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"send temp failure:%s ",strerror(errno));
return -2;
}
if(send(fd, &message_lengthnub, sizeof(message_lengthnub), 0) == -1)
{
printf("Send nuber failure:%s\n", strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"send nunber length failure:%s",strerror(errno));
return -3;
}
if(send(fd,Se_nub,strlen(Se_nub),0)==-1)
{
printf("send Se_nub failure:%s\n",strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"send nubmber failure:%s",strerror(errno));
return -3;
}
if(send(fd, &message_lengthtime, sizeof(message_lengthtime), 0) == -1)
{
printf("Send nuber failure:%s\n", strerror(errno));
log_message(LOG_ERROR, __FILE__,__LINE__,"send time length failure;%s",strerror(errno));
return -4;
}
if (send(fd, timebuf, strlen(timebuf), 0) == -1)
{
perror("Send timebuf failed\n");
log_message(LOG_ERROR, __FILE__,__LINE__,"send time failure:%s",strerror(errno));
return -5;
}
return 0;
}
//这是 获取时间的函数
struct tm *Get_nowtime()
{
struct tm *localTime;
time_t currentTime;
currentTime = time(NULL);
localTime = localtime(¤tTime);
return localTime;
}
//连接断开后保存获取的数据到sqlite3数据库中
int Save_data(char* tempbuf,char* Se_nub,char* timebuf)
{
sqlite3 *db;
sqlite3_stmt *stmt;
char *errMsg = 0;
int rc;
char insertSQL[1024];
rc=sqlite3_open("./sql_table/mydata.db",&db);
if(rc)
{
printf("sqlite_open on Save_data failed\n");
log_message(LOG_ERROR, __FILE__,__LINE__,"error:Can't open file named mydata.db");
return -1;
}
const char *createTableSQL =
"CREATE TABLE IF NOT EXISTS MyTable ("
"ID INTEGER PRIMARY KEY AUTOINCREMENT,"
"temp TEXT NOT NULL,"
"nub TEXT NOT NULL,"
"time TEXT NOT NULL);";
rc=sqlite3_exec(db, createTableSQL, 0, 0, &errMsg);
if (rc != SQLITE_OK)
{
printf("无法创建表格:%s %s\n",errMsg,strerror(errno));
log_message(LOG_ERROR,__FILE__,__LINE__, "Can't create table _error:%s",strerror(errno));
sqlite3_free(errMsg);
sqlite3_close(db);
return -2;
}
printf("成功创建表格\n");
printf("_________________________________\n");
log_message(LOG_INFO, __FILE__,__LINE__,"create table successfully");
sprintf(insertSQL, "INSERT INTO MyTable (temp, nub, time) VALUES ('%s', '%s','%s')", tempbuf, Se_nub,timebuf);
rc = sqlite3_exec(db, insertSQL, 0, 0, &errMsg);
if(rc != SQLITE_OK)
{
fprintf(stderr, "插入数据失败: %s %s\n", errMsg,strerror(errno));
log_message(LOG_ERROR,__FILE__,__LINE__, "Inset data failure:%s",strerror(errno));
sqlite3_free(errMsg);
sqlite3_close(db);
return-3;
}
//查询
const char *querySQL = "SELECT * FROM MyTable";
rc = sqlite3_exec(db, querySQL, callback, 0, &errMsg);
if (rc != SQLITE_OK)
{
fprintf(stderr, "查询出错: %s\n", errMsg);
log_message(LOG_ERROR, __FILE__,__LINE__,"Inquire failure:%s",strerror(errno));
sqlite3_free(errMsg);
}
printf("_________________________________\n");
sqlite3_close(db);
log_message(LOG_INFO,__FILE__,__LINE__, "Save data to sqlite table successfully");
return 1;
}
//这是查询数据库相关表中的消息的函数
int Query_and_Send(int fd)
{
sqlite3 *db;
char *errMsg = 0;
int rc;
sqlite3_stmt *stmt;
char data[512];
const char *dropTableSQL = "DROP TABLE IF EXISTS MyTable";
const unsigned char *temp;
const unsigned char *nub;
const unsigned char *time;
int id;
int count=1;
const char *query="SELECT * FROM MyTable";
rc=sqlite3_open("./sql_table/mydata.db",&db);
if(rc)
{
printf("that'ok\n");
log_message(LOG_ERROR,__FILE__,__LINE__,"can't open mydata.db");
return -1;
}
rc = sqlite3_prepare_v2(db, query, -1, &stmt, 0);
if(rc != SQLITE_OK)
{
printf("连接正常,表内无数据\n");
log_message(LOG_ERROR,__FILE__,__LINE__, "Table no data or error:%s",strerror(errno));
return -2;
}
while (sqlite3_step(stmt) == SQLITE_ROW)
{
memset(data, 0,sizeof(data));
id = sqlite3_column_int(stmt, 0);
temp = sqlite3_column_text(stmt, 1);
nub = sqlite3_column_text(stmt, 2);
time = sqlite3_column_text(stmt, 3);
printf("This is data when disconnected:[%d]\n",count);
Send_data((char*)temp,fd,(char*)nub,(char*)time);
count++;
}
rc = sqlite3_exec(db, dropTableSQL, 0, 0, &errMsg);
if(rc != SQLITE_OK)
{
printf("无法删除表格: %s\n", errMsg);
log_message(LOG_ERROR,__FILE__,__LINE__, "error:Delete table failure:%s",strerror(errno));
sqlite3_free(errMsg);
sqlite3_close(db);
}
log_message(LOG_INFO,__FILE__,__LINE__, "query and send data successfully");
sqlite3_finalize(stmt);
sqlite3_close(db);
return 1;
}
//回调函数,查询打印
static int callback(void *data,int argc, char **argv, char **azColName)
{
int i;
for (i = 0; i < argc; i++)
{
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
log_message(LOG_INFO,__FILE__,__LINE__,"callback successfully");
}