【发布时间】:2019-11-15 00:44:40
【问题描述】:
我尝试生成一个新设备并通过 MQTT 向它发布一些随机数据。 我遵循这个官方示例: https://cumulocity.com/guides/device-sdk/mqtt-examples/#hello-mqtt-cs
所有操作都执行,没有任何错误。甚至建立连接。但是当我尝试向设备发布消息时,出现以下错误
“与MQTT服务器连接失败(ConnectionRefusedNotAuthorized)”
这是我连接到服务器的信息
const string serverUrl = "mytenant.eu-latest.cumulocity.com";
const string clientId = "d:testdevice4";
const string device_name = "testdevice4";
const string user = "<mytenant>.eu-latest/<myusername>";
const string password = "XXXXXXXX";
以下是在不引发任何异常或 ConnectionFailed 事件的情况下执行的操作:
建立连接
await client.EstablishConnectionAsync();
创建设备
string topic = "s/us";
string payload = $"100,{device_name}, c8y_MQTTDevice";
var message = new MqttMessageRequestBuilder()
.WithTopicName(topic)
.WithQoS(QoS.EXACTLY_ONCE)
.WithMessageContent(payload)
.Build();
Cumulocity 示例的其他操作
// set device's hardware information
var deviceMessage = new MqttMessageRequestBuilder()
.WithTopicName("s/us")
.WithQoS(QoS.EXACTLY_ONCE)
.WithMessageContent($"110, {device_name}, MQTT test model, Rev0.1")
.Build();
await client.PublishAsync(deviceMessage);
// add restart operation
await client.SubscribeAsync(new MqttMessageRequest() { TopicName = "s/ds" });
await client.SubscribeAsync(new MqttMessageRequest() { TopicName = "s/e" });
await client.PublishAsync(new MqttMessageRequestBuilder()
.WithTopicName("s/us")
.WithQoS(QoS.EXACTLY_ONCE)
.WithMessageContent("114,c8y_Restart")
.Build());
但是当我尝试按如下方式向设备发布消息时,会调用 ConnectionFailed 事件并出现错误:
“与MQTT服务器连接失败(ConnectionRefusedNotAuthorized)”
Random rnd = new Random();
while (!cToken.IsCancellationRequested)
{
int temp = rnd.Next(10, 20);
Console.WriteLine("Sending temperature measurement (" + temp + "º) ...");
var xx = client.ConnectionDetails;
await client.PublishAsync(new MqttMessageRequestBuilder()
.WithTopicName("s/us")
.WithQoS(QoS.EXACTLY_ONCE)
.WithMessageContent("211," + temp)
.Build());
Thread.Sleep(1000);
}
【问题讨论】:
-
他们的例子有
string user = "<<tenant>>/<<username>>";。你的有"<mytenant>.eu-latest/<myusername>";。你确定你的正确吗? -
我尝试过使用和不使用 .eu-latest。我也尝试将用户名作为电子邮件和别名。所有变化都会导致相同的错误。我不确定clientId。 “d:
”是否正确? -
如果您还没有解决,我们遇到了同样的问题。我们通过将代理设置为与我们的驾驶舱 URL 相同的主机来解决它。您的租户将是
没有区域。 -
@GambitSupport 感谢您的信息。我们奇怪地通过创建一个全新的用户来解决它,授予它必要的权限并使用它的凭据。
标签: c# mqtt cumulocity