using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Zhaoxi.Upper
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
private double _value;
// 需要C#代码进行值更新,并且通知到页面
public double Value
{
get { return _value; }
set
{
_value = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Value"));
}
}
CancellationTokenSource cts = new CancellationTokenSource();
Task Task = null;
IManagedMqttClient client = null;
bool state = false;
public MainWindow()
{
InitializeComponent();
// 设置数据源
this.DataContext = this;
// 开始执行PLC点位获取动作
// 连接到PLC
S7.Net.Plc plc = new S7.Net.Plc(S7.Net.CpuType.S7200Smart, "192.168.2.1", 102, 0, 1);
plc.Open();
// 持续获取点位数据
//Thread thread = new Thread(() => { });
//thread.IsBackground = true;
Task = Task.Run(async () =>
{
while (!cts.IsCancellationRequested)
{
await Task.Delay(500);
// 200SmartPLC里面 VW0 -》 666
Value = double.Parse(plc.Read("DB1.DBW0").ToString());
// 如果MQTT客户端连接成功,那么开始分发数据
if (state)
{
// 当拿到最新的点位数据后,由MQTT客户端对象提交上去
// 主题
// 负载 打包一起发 Json
DataEntity dataEntity = new DataEntity();
dataEntity.DeviceId = 123;
dataEntity.Points.Add(new PointEntity { PropId = 3, Value = Value });
client.PublishAsync("A/A/A", System.Text.Json.JsonSerializer.Serialize(dataEntity));
}
}
}, cts.Token);
MqttClient();
}
protected override void OnClosed(EventArgs e)
{
cts.Cancel();
Task.WaitAll(new Task[] { Task });
}
public event PropertyChangedEventHandler? PropertyChanged;
private void MqttClient()
{
// 服务器相关配置
// 192.168.151.137 1883 admin 123456
// Client ID
// 实例化一个客户端对象
client = new MqttFactory().CreateManagedMqttClient();
client.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e =>
{
state = true;
});
IMqttClientOptions clientOptions = new MqttClientOptionsBuilder()
.WithClientId(Guid.NewGuid().ToString())
.WithTcpServer("192.168.151.137", 1883)
.WithCredentials("admin", "123456")
.Build();
IManagedMqttClientOptions options = new ManagedMqttClientOptionsBuilder()
.WithClientOptions(clientOptions)
.Build();
client.StartAsync(options);// 连接到某个服务器
}
}
class DataEntity
{
public int DeviceId { get; set; }
public List<PointEntity> Points { get; set; } = new List<PointEntity>();
}
class PointEntity
{
public int PropId { get; set; }
public double Value { get; set; }
}
}
CancellationTokenSource 配合task 用法
最新推荐文章于 2024-05-04 19:39:13 发布