mosquitto发布端和订阅端代码范例

2024-01-08 10:04

本文主要是介绍mosquitto发布端和订阅端代码范例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我也是复制的,没有测试。应该能正常工作中。

发布端

/**********************************************************************************      Copyright:  (C) 2022 Ye Xingwei<2929273315@qq.com>*                  All rights reserved.**       Filename:  subscribe.c*    Description:  This file MQTT_pub*                 *        Version:  1.0.0(2022年01月04日)*         Author:  Ye Xingwei <2929273315@qq.com>*      ChangeLog:  1, Release initial version on "2022年01月04日 15时08分27秒"*                 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <mosquitto.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <signal.h>
#include <ctype.h>#include "cJSON.h"#define HOST           "localhost"
#define PORT            1883
#define KEEP_ALIVE      60
#define MSG_MAX_SIZE    512static int  g_stop = 0;void mqtt_connect_callback(struct mosquitto *mosq, void *obj, int rc);
void mqtt_disconnect_callback(struct mosquitto *mosq, void *obj, int rc);
int get_time(char *datetime, int bytes);
int get_temperature(float *temp);
int get_ipaddr(char *interface,char *ipaddr,int ipaddr_size);
void sig_handle(int signum);int main (int argc, char **argv)
{int                 rv;struct mosquitto    *mosq = NULL;/*安装信号*/signal(SIGUSR1,sig_handle);/* MQTT 初始化 */rv = mosquitto_lib_init();if(rv != MOSQ_ERR_SUCCESS){printf("mosquitto lib int failure:%s\n", strerror(errno));goto cleanup;}/* 创建新的客户端 */mosq = mosquitto_new(NULL,true,NULL);if(!mosq){printf("create client failure:%s\n",strerror(errno));goto cleanup;}/* 回调函数 */mosquitto_connect_callback_set(mosq, mqtt_connect_callback);while(!g_stop){/*  连接MQTT服务器,ip,端口,时间 */ if(mosquitto_connect(mosq,HOST,PORT,KEEP_ALIVE) != MOSQ_ERR_SUCCESS){printf("mosquitto_connect() failed: %s\n",strerror(errno));goto cleanup;}printf("connect successfully\n");/* 无阻塞 断线连接 */mosquitto_loop_forever(mosq,-1,1);sleep(10);}cleanup: mosquitto_destroy(mosq);mosquitto_lib_cleanup();return 0;
} /*确认连接回函数*/
void mqtt_connect_callback(struct mosquitto *mosq, void *obj, int rc)
{char                    ipaddr[16];char                    *interface="eth0";char                    datetime[64];cJSON                   *root;cJSON                   *item;char                    *msg;struct mqtt_user_data   *mqtt;printf("Connection successful cJSON call packaging\n");float temper = 0.000000;if(get_temperature(&temper) < 0){printf("get_temperature failed.\n");return;}if(get_time(datetime,sizeof(datetime))<0){printf("get_time failure\n");return ;}memset(ipaddr,0,sizeof(ipaddr));if(get_ipaddr(interface,ipaddr,sizeof(ipaddr))<0){printf("ERROR:get ip address failure\n");return ;}root = cJSON_CreateObject();item = cJSON_CreateObject();/* cJSON打包 */cJSON_AddItemToObject(root,"id",cJSON_CreateString(ipaddr));cJSON_AddItemToObject(root,"time",cJSON_CreateString(datetime));cJSON_AddItemToObject(root,"Temperature",cJSON_CreateNumber(temper));msg = cJSON_Print(root);//printf("%s\n",msg);if(!rc){if(mosquitto_publish(mosq,NULL,"temp",strlen(msg),msg,0,NULL) != MOSQ_ERR_SUCCESS){printf("mosquitto_publish failed: %s\n",strerror(errno));return;}}mosquitto_disconnect(mosq);
}/* 获取时间 */
int get_time(char *datetime, int bytes)
{time_t              now;struct tm          *t;time(&now);t = localtime(&now);snprintf(datetime, bytes, "%04d-%02d-%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, (t->tm_hour)+8, t->tm_min, t->tm_sec);return 0;
}
/* 安装信号 */
void sig_handle(int signum)
{if(SIGUSR1 == signum){g_stop = 1;}
}/* 获取温度 */
int get_temperature(float *temp)
{int     fd = -1;char    buf[128];char    *ptr=NULL;DIR     *dirp = NULL;struct dirent *direntp = NULL;char    w1_path[64]="/sys/bus/w1/devices/";char    chip_sn[32];int     found = 0;dirp=opendir(w1_path);if(!dirp){printf("open foldir %s failure:%s\n",w1_path,strerror(errno));return -1;}while(NULL!=(direntp=readdir(dirp))){if(strstr(direntp->d_name,"28-")){strncpy(chip_sn, direntp->d_name,sizeof(chip_sn));found = -1;}}closedir(dirp);if(!found){printf("can not find ds18b20 chipset\n");return  -2;}strncat(w1_path,chip_sn,sizeof(w1_path)-strlen(w1_path));strncat(w1_path,"/w1_slave",sizeof(w1_path)-strlen(w1_path));if((fd = open(w1_path,O_RDONLY))<0){printf("File opened successfully:%s\n",strerror(errno));return -3;}memset(buf, 0, sizeof(buf));if(read(fd, buf, sizeof(buf))<0){printf("read data from fd=%d failure:%s\n",fd,strerror(errno));return -4;}ptr = strstr(buf,"t=");if(!ptr){printf("t=string\n");return -5;}ptr+= 2;*temp = atof(ptr)/1000;close(fd);return 0;}/* 获取IP地址 */
int get_ipaddr(char *interface,char *ipaddr,int ipaddr_size)
{char            buf[1024];char            *ptr;char            *ip_start;char            *ip_end;FILE            *fp;int             len;int             rv;if(!interface || !ipaddr || ipaddr_size <16){printf("Invalid input argument\n");return -2;}memset(buf, 0 , sizeof(buf));snprintf(buf,sizeof(buf),"ifconfig %s",interface);fp = popen(buf,"r");if(NULL==fp){printf("popen() to extern command\"%s\"failure:%s\n",buf,strerror(errno));return -2;}rv = -3;while(fgets(buf,sizeof(buf),fp)){if(strstr(buf,"netmask")){ptr = strstr(buf,"inet");if(!ptr){break;}ptr +=strlen("inet");while(isblank(*ptr))ptr++;ip_start = ptr;while(!isblank(*ptr))ptr++;ip_end = ptr;memset(ipaddr,0,sizeof(ipaddr));len = ip_end-ip_start;len = len>ipaddr_size ? ipaddr_size:len;memcpy(ipaddr,ip_start,len);rv = 0;break;}}pclose(fp);return rv;
}

订阅端

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mosquitto.h>#include "cJSON.h"#define HOST "localhost"
#define PORT  1883
#define KEEP_ALIVE 60
#define MSG_MAX_SIZE  512static int running = 1;/* 确认连接回调函数 */
void mqtt_connect_callback(struct mosquitto *mosq, void *obj, int rc)
{printf("Confirm the connection to the client\n");if(rc){printf("on_connect error!\n");exit(1);}else{if(mosquitto_subscribe(mosq, NULL, "temp", 2)){printf("Set the topic error!\n");exit(1);}}
}/*获取到订阅的内容*/
void mqtt_message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
{printf("Obtaining content successfully\n");printf("\n");printf("Succeeded in obtaining the time and temperature:%s\n", (char *)msg->payload);
}int main (int argc, char **argv)
{int                 ret;struct mosquitto    *mosq;/* MQTT 初始化 */ret = mosquitto_lib_init();if(ret){printf("Init lib error!\n");goto cleanup;return -1;}/* 创建新的客户端 */mosq = mosquitto_new(NULL,true, NULL);if(mosq == NULL){printf("Create a new client failure\n");goto cleanup;return -1;}/* 回调函数 */mosquitto_connect_callback_set(mosq, mqtt_connect_callback);mosquitto_message_callback_set(mosq, mqtt_message_callback);/* 连接代理 */ret = mosquitto_connect(mosq, HOST, PORT, KEEP_ALIVE);if(ret){printf("Connect server error!\n");goto cleanup;return -1;}printf("connection client is OK\n");while(running){mosquitto_loop(mosq, -1, 1);}/* 释放 清空 */
cleanup:mosquitto_destroy(mosq);mosquitto_lib_cleanup();return 0;
} 

这篇关于mosquitto发布端和订阅端代码范例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/583105

相关文章

Python中顺序结构和循环结构示例代码

《Python中顺序结构和循环结构示例代码》:本文主要介绍Python中的条件语句和循环语句,条件语句用于根据条件执行不同的代码块,循环语句用于重复执行一段代码,文章还详细说明了range函数的使... 目录一、条件语句(1)条件语句的定义(2)条件语句的语法(a)单分支 if(b)双分支 if-else(

MySQL数据库函数之JSON_EXTRACT示例代码

《MySQL数据库函数之JSON_EXTRACT示例代码》:本文主要介绍MySQL数据库函数之JSON_EXTRACT的相关资料,JSON_EXTRACT()函数用于从JSON文档中提取值,支持对... 目录前言基本语法路径表达式示例示例 1: 提取简单值示例 2: 提取嵌套值示例 3: 提取数组中的值注意

CSS3中使用flex和grid实现等高元素布局的示例代码

《CSS3中使用flex和grid实现等高元素布局的示例代码》:本文主要介绍了使用CSS3中的Flexbox和Grid布局实现等高元素布局的方法,通过简单的两列实现、每行放置3列以及全部代码的展示,展示了这两种布局方式的实现细节和效果,详细内容请阅读本文,希望能对你有所帮助... 过往的实现方法是使用浮动加

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

nginx-rtmp-module模块实现视频点播的示例代码

《nginx-rtmp-module模块实现视频点播的示例代码》本文主要介绍了nginx-rtmp-module模块实现视频点播,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习... 目录预置条件Nginx点播基本配置点播远程文件指定多个播放位置参考预置条件配置点播服务器 192.

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

Java实现Elasticsearch查询当前索引全部数据的完整代码

《Java实现Elasticsearch查询当前索引全部数据的完整代码》:本文主要介绍如何在Java中实现查询Elasticsearch索引中指定条件下的全部数据,通过设置滚动查询参数(scrol... 目录需求背景通常情况Java 实现查询 Elasticsearch 全部数据写在最后需求背景通常情况下

Git提交代码详细流程及问题总结

《Git提交代码详细流程及问题总结》:本文主要介绍Git的三大分区,分别是工作区、暂存区和版本库,并详细描述了提交、推送、拉取代码和合并分支的流程,文中通过代码介绍的非常详解,需要的朋友可以参考下... 目录1.git 三大分区2.Git提交、推送、拉取代码、合并分支详细流程3.问题总结4.git push