温度采集上报
提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用
提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
通过树莓派上的温度传感器,每隔30S上报给服务器,在收到来自客户端的数据后,把数据保存在数据库中。
提示:以下是本篇文章正文内容,下面案例可供参考
一、客户端代码
1.树莓派上运行socket客户端程序代码,每隔30s以字符串“ID/时间/温度”形式上报采集温度。
2.通过命令行参数指定服务器IP地址和采样间隔时间。
3.程序放到后台运行,并通过syslog记录程序出错原因,调试日志。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <dirent.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <getopt.h>
#include <syslog.h>
int g_stop = 0;
int socket_fd = -1;
char *server_ip;
int port = 0;
char MSG[50];
char timechar[256]={
0};
void sig_handle(int signum)
{
if(SIGUSR1 == signum)
{
g_stop = 1;
}
}
void print_usage(char *progname)
{
printf("%s usage: \n",progname);
printf("-i(--ipaddr):specify IP address.\n");
printf("-p(--port):specify server port.\n");
printf("-t(--time):specify sleep time.\n");
printf("-d(--daemon):\n");
printf("-h(--help): print this help information\n");
}
int ds18b20_get_temperature(float *temp);
int conn_server(void);
char *get_date_time(char *datetime);
int main(int argc,char **argv)
{
float temp;
char *datetime;
int sle_time = 0;
time_t timep;
time (&timep);
char *id = "JMQ";
int daemon_run = 0;
int opt;
struct option opts[] = {
{
"ipaddr",required_argument,NULL,'i'},
{
"port",required_argument,NULL,'p'},
{
"time",required_argument,NULL,'t'},
{
"daemon",no_argument,NULL,'d'},
{
"help",no_argument,NULL,'h'},
{
NULL,0,NULL,0}
};
while((opt = getopt_long(argc,argv,"i:p:t:dh",opts,NULL)) != -1)
{
switch(opt)
{
case 'i':
server_ip = optarg;
break;
case 'p':
port = atoi(optarg);
break;
case 't':
sle_time = atoi(optarg);
break;
case 'd':
daemon_run = 1;
break;
case 'h':
print_usage(argv[0]);
return 0;
}
}
if (!port || !server_ip)
{
print_usage(argv[0]);
return 0;
}
if(daemon_run)
{
daemon(0,0);
}
signal(SIGUSR1,sig_handle);
while(!g_stop)
{
if( ds18b20_get_temperature(&temp) < 0 )
{
syslog(LOG_INFO,"ERROR:ds18b20 get temperrature failure\n");
return -1;
}
printf("get temp: %f摄氏度\n",temp);
datetime = get_date_time(datetime);
printf("DATE:%s\n",datetime);
memset(MSG,0,sizeof(MSG));
int ret = snprintf(MSG,50,"%s/%s/%f",id,datetime,temp);
printf("ret:%d,%d\n",ret,sizeof(MSG));
if (ret < 0)
{
printf("snprintf() failure:%s\n",strerror