当前位置: 首页 > news >正文

mqtt c语言publish topic

客户端地址
这里选择c语言的,版本如下:
https://github.com/LiamBindle/MQTT-C
版本

commit 7a986a68ebea63921d4aab20a9d1b26a8b5f8c9d (HEAD -> master, origin/master, origin/HEAD)
Merge: 2ee39b9 6220c65
Author: Liam Bindle <lrbindle@gmail.com>
Date:   Thu Oct 27 12:43:06 2022 -0700

连接服务器,发布话题,这里使用的broker,是EMQ官方提供测试的服务器:
Broker服务器


/*** @file* A simple program to that publishes the current time whenever ENTER is pressed.*/
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>#include "mqtt.h"
#include "posix_sockets.h"/*** @brief The function that would be called whenever a PUBLISH is received.** @note This function is not used in this example.*/
void publish_callback(void** unused, struct mqtt_response_publish *published);/*** @brief The client's refresher. This function triggers back-end routines to*        handle ingress/egress traffic to the broker.** @note All this function needs to do is call \ref __mqtt_recv and*       \ref __mqtt_send every so often. I've picked 100 ms meaning that*       client ingress/egress traffic will be handled every 100 ms.*/
void* client_refresher(void* client);/*** @brief Safelty closes the \p sockfd and cancels the \p client_daemon before \c exit.*/
void exit_example(int status, int sockfd, pthread_t *client_daemon);/*** A simple program to that publishes the current time whenever ENTER is pressed.*/
int main(int argc, const char *argv[])
{const char* addr;const char* port;const char* topic;/* get address (argv[1] if present) */if (argc > 1) {addr = argv[1];} else {// addr = "test.mosquitto.org"; //broker.emqx.ioaddr = "broker.emqx.io"; //emq官方测试服务器}/* get port number (argv[2] if present) */if (argc > 2) {port = argv[2];} else {port = "1883";}/* get the topic name to publish */if (argc > 3) {topic = argv[3];} else {// topic = "datetime";// topic = "sherlock";topic = "sher";}/* open the non-blocking TCP socket (connecting to the broker) */int sockfd = open_nb_socket(addr, port);if (sockfd == -1) {perror("Failed to open socket: ");exit_example(EXIT_FAILURE, sockfd, NULL);}/* setup a client */struct mqtt_client client;uint8_t sendbuf[2048]; /* sendbuf should be large enough to hold multiple whole mqtt messages */uint8_t recvbuf[1024]; /* recvbuf should be large enough any whole mqtt message expected to be received */mqtt_init(&client, sockfd, sendbuf, sizeof(sendbuf), recvbuf, sizeof(recvbuf), publish_callback);/* Create an anonymous session */const char* client_id = NULL;/* Ensure we have a clean session */uint8_t connect_flags = MQTT_CONNECT_CLEAN_SESSION;/* Send connection request to the broker. */mqtt_connect(&client, client_id, NULL, NULL, 0, NULL, NULL, connect_flags, 400);/* check that we don't have any errors */if (client.error != MQTT_OK) {fprintf(stderr, "error: %s\n", mqtt_error_str(client.error));exit_example(EXIT_FAILURE, sockfd, NULL);}/* start a thread to refresh the client (handle egress and ingree client traffic) */pthread_t client_daemon;if(pthread_create(&client_daemon, NULL, client_refresher, &client)) {fprintf(stderr, "Failed to start client daemon.\n");exit_example(EXIT_FAILURE, sockfd, NULL);}/* start publishing the time */printf("%s is ready to begin publishing the time.\n", argv[0]);printf("Press ENTER to publish the current time.\n");printf("Press CTRL-D (or any other key) to exit.\n\n");// while(fgetc(stdin) == '\n') while(1) {usleep(1000000);/* get the current time */time_t timer;time(&timer);struct tm* tm_info = localtime(&timer);char timebuf[26];strftime(timebuf, 26, "%Y-%m-%d %H:%M:%S", tm_info);/* print a message */char application_message[256];// snprintf(application_message, sizeof(application_message), "%s", timebuf);int random_number = rand() % 100; // 生成 0 到 99 的随机整数snprintf(application_message, sizeof(application_message), "%d", random_number);printf("%s published : \"%s\"", argv[0], application_message);/* publish the time */mqtt_publish(&client, topic, application_message, strlen(application_message) + 1, MQTT_PUBLISH_QOS_0);/* check for errors */if (client.error != MQTT_OK) {fprintf(stderr, "error: %s\n", mqtt_error_str(client.error));exit_example(EXIT_FAILURE, sockfd, &client_daemon);}}/* disconnect */printf("\n%s disconnecting from %s\n", argv[0], addr);sleep(1);/* exit */exit_example(EXIT_SUCCESS, sockfd, &client_daemon);
}void exit_example(int status, int sockfd, pthread_t *client_daemon)
{if (sockfd != -1) close(sockfd);if (client_daemon != NULL) pthread_cancel(*client_daemon);exit(status);
}void publish_callback(void** unused, struct mqtt_response_publish *published)
{/* not used in this example */
}void* client_refresher(void* client)
{while(1){mqtt_sync((struct mqtt_client*) client);usleep(100000U);}return NULL;
}

makefile如下:

#** -LICENSE-START-
#** Copyright (c) 2009 Blackmagic Design
#**  
#** Permission is hereby granted, free of charge, to any person or organization 
#** obtaining a copy of the software and accompanying documentation (the 
#** "Software") to use, reproduce, display, distribute, sub-license, execute, 
#** and transmit the Software, and to prepare derivative works of the Software, 
#** and to permit third-parties to whom the Software is furnished to do so, in 
#** accordance with:
#** 
#** (1) if the Software is obtained from Blackmagic Design, the End User License 
#** Agreement for the Software Development Kit (“EULA”) available at 
#** https://www.blackmagicdesign.com/EULA/DeckLinkSDK; or
#** 
#** (2) if the Software is obtained from any third party, such licensing terms 
#** as notified by that third party,
#** 
#** and all subject to the following:
#** 
#** (3) the copyright notices in the Software and this entire statement, 
#** including the above license grant, this restriction and the following 
#** disclaimer, must be included in all copies of the Software, in whole or in 
#** part, and all derivative works of the Software, unless such copies or 
#** derivative works are solely in the form of machine-executable object code 
#** generated by a source language processor.
#** 
#** (4) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
#** OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
#** FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT 
#** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE 
#** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, 
#** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
#** DEALINGS IN THE SOFTWARE.
#** 
#** A copy of the Software is available free of charge at 
#** https://www.blackmagicdesign.com/desktopvideo_sdk under the EULA.
#** 
#** -LICENSE-END-CC=gcc# SDK_PATH=../../include
CFLAGS=-Wno-multichar -I $(SDK_PATH) -fno-rtti
LDFLAGS=-lm -ldl -lpthreadHEADERS= \mqtt.h\mqtt_pal.hSRCS= mqtt.c\mqtt_pal.c\simple_publisher.cMqtt: $(SRCS) $(HEADERS) $(CC) -o Mqtt $(SRCS)  $(CFLAGS) $(LDFLAGS)clean:rm -f Mqtt

附录:

完整项目见
https://download.csdn.net/download/weixin_43466192/90927383

mqtt服务器本地搭建

Grafana部署

http://www.xdnf.cn/news/702919.html

相关文章:

  • 6 质量控制中的常用缩略语和符号(OEE)以及解释
  • 嵌入式学习之系统编程(七)线程的控制(互斥与同步)和死锁
  • CPG开源项目对比
  • 18度的井水
  • C++补充基础小知识:为什么要继承、什么时候继承、什么时候直接用
  • 高并发计数器LongAdder 实现原理与使用场景详解
  • Jmeter性能测试(应用场景、性能测试流程、搭建测试环境)
  • 实例与选项对象
  • SpringBoot+Vue+Echarts实现可视化图表的渲染
  • 自动生成程序的heap文件
  • #!/usr/bin/env python
  • JS中的属性描述符
  • Day 20
  • 生成式引擎在不同行业的应用案例
  • 第十章 Java基础-Static静态变量
  • 基于物理约束的稀疏IMU运动捕捉系统
  • spring和Mybatis的各种查询
  • Rust 学习笔记:使用迭代器改进 minigrep
  • 力扣刷题Day 61:子集(78)
  • 【案例94】笛卡尔积导致报“临时表空间不足”
  • bat 批处理通过拖拽,来获取拖入文件的信息
  • 【25-cv-00656】Whitewood律所代理Olga Drozdova 蝴蝶版权图维权案
  • 【Web应用】若依框架:基础篇07功能详解-定时任务
  • 不同坐标系下的 面积微元
  • Android-Room + WorkManager学习总结
  • 2G Nand Jlink烧录报错Failed to allocated 0x1B000000 bytes of memory!
  • 5G 核心网中 NRF 网元的功能、接口及参数详解
  • 8.7 使用 EAP-AKA 进行订阅转移
  • 星图云交通综合应用解决方案:破解交通基建抢建拖建、工程量大等难题,赋能智慧交通
  • 2025年5月AI科技领域周报(5.19-5.25):大模型多模态突破 具身智能开启机器人新纪元