做这项工作之前,我已经做了一些准备工作了,我之前写的 “基于mosquitto库搭建mqtt客户端发布实现与阿里云的通信”以及“基于树莓派3B SHT20温湿度采样”都是为此项目做好准备的,大家如果想要完成树莓派与阿里云的通信,请务必先了解一下,我之前的博客,链接:基于树莓派3B SHT20温湿度采样
基于mosquitto库搭建mqtt客户端发布实现与阿里云的通信
再有了这些准备工作之后,我们就可以完成此项任务了,首先我们要了解基本的流程:如下图
我把sht20封装成一个函数写在了回调函数里面,然后采样温湿度,打包成josn格式,发送给阿里云。
在这里我们先来看一下我代码中怎么把温度和湿度,打包成josn格式的,首先看josn文件。
关于此篇博客,跟我之前那个“基于mosquitto库搭建mqtt客户端发布实现与阿里云的通信”的博客很像,只不过,我只是在原来的代码的基础上加了sht20的温湿度采样的函数,所以在这里,我只附上主函数的源码吧,关于更多源码,我会在下面给出gitee的链接地址。
主函数源码:
/*********************************************************************************
* Copyright: (C) 2020 makun<1394987689@qq.com>
* All rights reserved.
*
* Filename: mosquitto_pub.c
* Description: This file
*
* Version: 1.0.0(2020年07月08日)
* Author: makun <1394987689@qq.com>
* ChangeLog: 1, Release initial version on "2020年07月08日 22时30分04秒"
*
********************************************************************************/
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <libgen.h>
#include <getopt.h>
#include <string.h>
#include <mosquitto.h>
#include <stdlib.h>
#include "conf.h"
#include "cJSON.h"
#include "sht20.h"
#define PROG_VERSION "1.0.0"
#define PATH_INT "./mqtt_aly_conf.ini"
int get_temp_humidity(int fd, float *temp, float *humidity);
void pub_conn_callback(struct mosquitto *mosq, void *obj, int rc);
static void print_usage( char *progname)
{
printf("Usage %s [option]...\n", progname);
printf("%s is makun studi MQTT daemon program running on RaspberryPi\n", progname);
printf("-p (--port): the port of the server you want to connect\n");
printf("-h (--host): the hostname of the server you want to connect\n");
printf("-u (--user): the username of the client\n");
printf("-P (--passwd): the passwd of the client you\n");
printf("-i (--clientid): the clientid of the user\n");
printf("-t (--topic): the topic of the client you want to pub\n");
printf("-H (--help): Display this help information\n");
printf("-v (--version): Display the program version\n");
printf("%s Version %s\n", progname, PROG_VERSION);
return ;
}
int main (int argc, char **argv)
{
char *host = NULL;
int port ;
char