zhuangpei-mesbackend/DOAN.Service/MES/mqtt/ProductExecuteService.cs
gcw_MV9p2JJN cfdcd5d6bf 1
2025-12-08 11:43:04 +08:00

92 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using DOAN.Model.MES.product;
using DOAN.Service.MES.product.IService;
using Infrastructure.Attribute;
using MQTTnet;
using MQTTnet.Formatter;
using MQTTnet.Protocol;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DOAN.Service.MES.mqtt
{
[AppService(ServiceType = typeof(ProductExecuteService), ServiceLifetime = LifeTime.Transient)]
public class ProductExecuteService
{
// MQTT Broker 配置(替换为你的实际 Broker 地址)
private static string MqttBrokerUrl = "broker.hivemq.com"; // 公共测试 MQTT 服务器
private static int MqttBrokerPort = 1883; // 默认 MQTT 端口,不加密
private static string MqttUsername = null; // 如果你的 broker 需要用户名
private static string MqttPassword = null; // 如果你的 broker 需要密码
// 要发送的 MQTT 主题和消息内容
private static string Topic = "product/topic"; // 你要发送的目标 MQTT 主题
/// <summary>
/// 开始工单后,转发指定配方给设备
/// </summary>
public async Task SendRecipeToDeviceAfterStartWorkOrder(string MessageContent)
{
//把工单信息和配方信息组装成消息内容
Console.WriteLine($"准备向 MQTT 主题 '{Topic}' 发送消息...");
// 1. 创建 MQTT 客户端工厂
var factory = new MqttClientFactory();
var mqttClient = factory.CreateMqttClient();
// 2. 配置 MQTT 客户端连接选项
var options = new MqttClientOptionsBuilder()
.WithTcpServer(MqttBrokerUrl, MqttBrokerPort) // MQTT 服务器地址和端口
.WithCredentials(MqttUsername, MqttPassword) // 如果有身份验证
.WithCleanSession()
.Build();
try
{
// 3. 连接到 MQTT Broker
Console.WriteLine($"正在连接到 MQTT Broker: {MqttBrokerUrl}:{MqttBrokerPort}...");
await mqttClient.ConnectAsync(options);
Console.WriteLine("✅ MQTT 连接成功!");
// 4. 构建要发送的消息
var message = new MqttApplicationMessageBuilder()
.WithTopic(Topic) // 目标主题
.WithPayload(MessageContent) // 消息内容(字符串)
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce) // QoS 级别:至少一次 (1)
.WithRetainFlag(false) // 是否保留消息(一般 false
.Build();
// 5. 发布消息
Console.WriteLine($"正在向主题 '{Topic}' 发送消息: {MessageContent}");
await mqttClient.PublishAsync(message);
Console.WriteLine("✅ 消息发送成功!");
}
catch (Exception ex)
{
Console.WriteLine($"❌ 发生错误: {ex.Message}");
}
finally
{
// 6. (可选)断开连接
if (mqttClient.IsConnected)
{
await mqttClient.DisconnectAsync();
Console.WriteLine("🔌 MQTT 已断开连接");
}
}
Console.WriteLine("按 Enter 键退出...");
Console.ReadLine();
}
}
}