49 lines
1.8 KiB
C
49 lines
1.8 KiB
C
#include "includes/mosquitto.h" // mqtt
|
||
#include "includes/sqlite3.h" // sqlite3
|
||
#include <stdbool.h> // bool
|
||
#include <stdio.h>
|
||
#include <stdlib.h>
|
||
#include <string.h>
|
||
|
||
int isConnected = 0;
|
||
|
||
void connect_callback(struct mosquitto *mosq, void *obj, int rc)
|
||
{
|
||
if (rc == 0)
|
||
{
|
||
printf("---连接服务器成功---\n");
|
||
isConnected = 1;
|
||
}
|
||
}
|
||
int main(int argc, char const *argv[])
|
||
{
|
||
if (argc < 3)
|
||
{
|
||
printf("format: %s msgid topic msg", argv[0]);
|
||
return -1;
|
||
}
|
||
mosquitto_lib_init(); // 初始化(固定格式)
|
||
struct mosquitto *client = mosquitto_new(NULL, true, NULL); // 创建客户端
|
||
mosquitto_connect_callback_set(client, connect_callback); // 设置连接回调函数
|
||
// mosquitto_connect(client, "localhost", 1883, 60); // 连接服务器(地址,端口,超时时间)
|
||
mosquitto_connect(client, "flykhan.com", 1883, 60); // 连接服务器(地址,端口,超时时间)
|
||
mosquitto_loop_start(client); // 开启客户端线程
|
||
while (isConnected == 0)
|
||
; // 等待连接成功(当连接成功后,isConnected会被置为1,然后跳出循环)
|
||
|
||
int msg_id = atoi(argv[1]); // 消息ID
|
||
char *topic = (char *)argv[2]; // 主题
|
||
char *msg = (char *)argv[3]; // 消息
|
||
int flag = mosquitto_publish(client, &msg_id, topic, strlen(msg), msg, 1, true); // 发布消息
|
||
|
||
// 发布成功
|
||
if (flag == MOSQ_ERR_SUCCESS)
|
||
{
|
||
printf("---消息发布成功: %s(%d):%s---\n", topic, msg_id, msg);
|
||
mosquitto_destroy(client);
|
||
mosquitto_lib_cleanup();
|
||
}
|
||
|
||
return 0;
|
||
}
|