MQTT如何确认返回的值,就是客户端下发时主题对应的字段?
1.客户端发送一组不同字段的主题给MQTT,期望MQTT下发相关指令给相关设备,返回这些字段的实时值。
2.由于客户端发送的是一组主题,且定时器会定时发送,这个列表在不断变化。因此,需要一个消息id,用于确认返回值与主题字段相相对应。
目前方案出现的问题:客户端每发一个主题做下延时。在接收到返回时,字段名称与值还能对应。但超过延时间隔时,字段名称就发生了变化,返回的值就对应到了不同的字段
mqtt v5 支持发送meta数据
而在 mqttnet这个库就利用这个特性,加了个 ResponseTopic(意为回复topic)
当然也有mqtt rpc库你可以直接用(因为你要得东西其实就是RPC)
当然其实我们自己做也是OK的,不过我们不叫“延时”,因为你要叫延时意味着着 很容易走到什么定时器,线程whie(ture)这种山路上
我们就直接叫异步IO,异步Rpc就行了
基础形状为:
taskcomplect<task> tc
await 发布消息
await 订阅返回消息.where(msg=>判定).处理(pc=>tc.trysetvalue(), 超时cancel)
手机回复,不好敲代码,你看得明白就行
您指的是类似于这种方式吗?
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
CopyFileAsync(@"c:\log.txt", @"c:\1.txt", ReadCount);
Console.ReadKey();
void ReadCount(int c)
{
Console.WriteLine("读写个数:"+c);
}
static async Task<int> CopyFileAsync(string sourceFilePath, string desFilePath, Action<int> progressCallback)
{
var bytesRead = 0;
using (var source = File.OpenRead(sourceFilePath))
using (var des = File.OpenWrite(desFilePath))
{
byte[] buffer = new byte[4096];
int totalBytesRead = 0;
int bytesReadThisTime;
while ((bytesReadThisTime = await source.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await des.WriteAsync(buffer, 0, bytesReadThisTime);
bytesRead += bytesReadThisTime;
totalBytesRead += bytesReadThisTime;
if (progressCallback != null)
{
progressCallback(totalBytesRead);
}
}
}
return bytesRead;
}