gpt4 book ai didi

c - 我必须连接到 MQTT 代理吗?

转载 作者:行者123 更新时间:2023-11-30 21:10:19 24 4
gpt4 key购买 nike

我正在尝试使用 MQTT 将数据发送到我的数据库 (MySQL)。但我无法获取任何信息,或者只是不明白我是否需要先使用 C 代码连接到我的 MQTT 代理?或者如果我可以输入我的数据库地址和端口号?连接代码如下。

我使用 HiveMQ 作为代理。

    while(1){

MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
int rc = 0;
char buf[200];
MQTTString topicString = MQTTString_initializer;

char* payload = "Hello World!";
int payloadlen = strlen(payload);
int buflen = sizeof(buf);

data.clientID.cstring = "me";
data.keepAliveInterval = 20;
data.cleansession = 1;

int len = MQTTSerialize_connect(buf, buflen, &data); /* 1 */

topicString.cstring = "cc3200-ben";

len += MQTTSerialize_publish(buf + len, buflen - len, 0, 0, 0, 0, topicString, payload, payloadlen); /* 2 */

len += MQTTSerialize_disconnect(buf + len, buflen - len); /* 3 */

// creating a TCP socket
int mysock = sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0);
if( mysock < 0 )
{
ERR_PRINT(mysock);
LOOP_FOREVER();
}

SlSockAddrIn_t addr;

//filling the TCP server socket address
addr.sin_family = SL_AF_INET;
addr.sin_port = sl_Htons(1883);
//addr.sin_port = sl_Htons(3306);
addr.sin_addr.s_addr = sl_Htonl(0xC6291EF1);

// connecting to TCP server
rc = sl_Connect(mysock, (SlSockAddr_t *) &addr, sizeof(addr));
if(rc<0){
ERR_PRINT(rc);
LOOP_FOREVER();
}
// sending packet
rc = sl_Send(mysock, buf, len, NULL);
if(rc<0){
ERR_PRINT(rc);
LOOP_FOREVER();
}

//closing the socket
rc = sl_Close(mysock);
if(rc<0){
ERR_PRINT(rc);
LOOP_FOREVER();
}

// rc = Socket_new("0.0.0.0", 1883, &mysock);
// rc = write(mysock, buf, len);
// rc = close(mysock);

osi_Sleep(200);
}

最佳答案

DB和MQTT代理完全是serape,请按照以下步骤获得你想要的:

  1. 在应用程序启动期间连接到您的 mqtt 代理。
  2. 订阅您正在等待其数据的主题。
  3. 连接到您的数据库。
  4. 在回调函数(来自第 2 步)中,使用数据库连接并通过负载更新数据库。

要将数据发送到您的服务器,请执行以下操作:

  1. 连接到您的 mqtt 代理。
  2. 向您的主题发布消息(来自上一步 2)。

关于c - 我必须连接到 MQTT 代理吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086019/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com