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

相关文章

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

SpringBoot+RustFS 实现文件切片极速上传的实例代码

《SpringBoot+RustFS实现文件切片极速上传的实例代码》本文介绍利用SpringBoot和RustFS构建高性能文件切片上传系统,实现大文件秒传、断点续传和分片上传等功能,具有一定的参考... 目录一、为什么选择 RustFS + SpringBoot?二、环境准备与部署2.1 安装 RustF

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

修复已被利用的高危漏洞! macOS Sequoia 15.6.1发布

《修复已被利用的高危漏洞!macOSSequoia15.6.1发布》苹果公司于今日发布了macOSSequoia15.6.1更新,这是去年9月推出的macOSSequoia操作... MACOS Sequoia 15.6.1 正式发布!此次更新修复了一个已被黑客利用的严重安全漏洞,并解决了部分中文用户反馈的

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

使用Spring Cache本地缓存示例代码

《使用SpringCache本地缓存示例代码》缓存是提高应用程序性能的重要手段,通过将频繁访问的数据存储在内存中,可以减少数据库访问次数,从而加速数据读取,:本文主要介绍使用SpringCac... 目录一、Spring Cache简介核心特点:二、基础配置1. 添加依赖2. 启用缓存3. 缓存配置方案方案

MySQL的配置文件详解及实例代码

《MySQL的配置文件详解及实例代码》MySQL的配置文件是服务器运行的重要组成部分,用于设置服务器操作的各种参数,下面:本文主要介绍MySQL配置文件的相关资料,文中通过代码介绍的非常详细,需要... 目录前言一、配置文件结构1.[mysqld]2.[client]3.[mysql]4.[mysqldum

Python多线程实现大文件快速下载的代码实现

《Python多线程实现大文件快速下载的代码实现》在互联网时代,文件下载是日常操作之一,尤其是大文件,然而,网络条件不稳定或带宽有限时,下载速度会变得很慢,本文将介绍如何使用Python实现多线程下载... 目录引言一、多线程下载原理二、python实现多线程下载代码说明:三、实战案例四、注意事项五、总结引