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

相关文章

Java中调用数据库存储过程的示例代码

《Java中调用数据库存储过程的示例代码》本文介绍Java通过JDBC调用数据库存储过程的方法,涵盖参数类型、执行步骤及数据库差异,需注意异常处理与资源管理,以优化性能并实现复杂业务逻辑,感兴趣的朋友... 目录一、存储过程概述二、Java调用存储过程的基本javascript步骤三、Java调用存储过程示

Visual Studio 2022 编译C++20代码的图文步骤

《VisualStudio2022编译C++20代码的图文步骤》在VisualStudio中启用C++20import功能,需设置语言标准为ISOC++20,开启扫描源查找模块依赖及实验性标... 默认创建Visual Studio桌面控制台项目代码包含C++20的import方法。右键项目的属性:

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Java实现自定义table宽高的示例代码

《Java实现自定义table宽高的示例代码》在桌面应用、管理系统乃至报表工具中,表格(JTable)作为最常用的数据展示组件,不仅承载对数据的增删改查,还需要配合布局与视觉需求,而JavaSwing... 目录一、项目背景详细介绍二、项目需求详细介绍三、相关技术详细介绍四、实现思路详细介绍五、完整实现代码

Go语言代码格式化的技巧分享

《Go语言代码格式化的技巧分享》在Go语言的开发过程中,代码格式化是一个看似细微却至关重要的环节,良好的代码格式化不仅能提升代码的可读性,还能促进团队协作,减少因代码风格差异引发的问题,Go在代码格式... 目录一、Go 语言代码格式化的重要性二、Go 语言代码格式化工具:gofmt 与 go fmt(一)

HTML5实现的移动端购物车自动结算功能示例代码

《HTML5实现的移动端购物车自动结算功能示例代码》本文介绍HTML5实现移动端购物车自动结算,通过WebStorage、事件监听、DOM操作等技术,确保实时更新与数据同步,优化性能及无障碍性,提升用... 目录1. 移动端购物车自动结算概述2. 数据存储与状态保存机制2.1 浏览器端的数据存储方式2.1.

基于 HTML5 Canvas 实现图片旋转与下载功能(完整代码展示)

《基于HTML5Canvas实现图片旋转与下载功能(完整代码展示)》本文将深入剖析一段基于HTML5Canvas的代码,该代码实现了图片的旋转(90度和180度)以及旋转后图片的下载... 目录一、引言二、html 结构分析三、css 样式分析四、JavaScript 功能实现一、引言在 Web 开发中,

Python如何去除图片干扰代码示例

《Python如何去除图片干扰代码示例》图片降噪是一个广泛应用于图像处理的技术,可以提高图像质量和相关应用的效果,:本文主要介绍Python如何去除图片干扰的相关资料,文中通过代码介绍的非常详细,... 目录一、噪声去除1. 高斯噪声(像素值正态分布扰动)2. 椒盐噪声(随机黑白像素点)3. 复杂噪声(如伪

Java Spring ApplicationEvent 代码示例解析

《JavaSpringApplicationEvent代码示例解析》本文解析了Spring事件机制,涵盖核心概念(发布-订阅/观察者模式)、代码实现(事件定义、发布、监听)及高级应用(异步处理、... 目录一、Spring 事件机制核心概念1. 事件驱动架构模型2. 核心组件二、代码示例解析1. 事件定义

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部