mqttnet客户端,并形成折线图。

这里topic是设置好的test2

namespace _11._14._16._15
{
public partial class Form1 : Form
{
private Queue dataQueue = new Queue(100);
private MqttClient mqttClient = null;
public string a;
public string date;
string topic = “test2”;

    public Form1()
    {
        InitializeComponent();
        Task.Run(async () => { await ConnectMqttServerAsync(); });
    }

    private Task ConnectMqttServerAsync()
    {
        throw new NotImplementedException();


    }
    private void Form1_Load(object sender, EventArgs e)
    {
        mqttClient = new MqttClientFactory().CreateMqttClient() as MqttClient;
        mqttClient.ApplicationMessageReceived += MqttClient_ApplicationMessageReceived;
        mqttClient.Connected += MqttClient_Connected;
        mqttClient.Disconnected += MqttClient_Disconnected;

        var options = new MqttClientTcpOptions
        {
            Port = 1883,
            Server = "8.131.79.105",
            ClientId = Guid.NewGuid().ToString().Substring(0, 5),
            UserName = "asdjg",
            Password = "asd123456",
            CleanSession = true
        };

        mqttClient.ConnectAsync(options);
        Console.ReadLine();
        Console.WriteLine("Hello World!");
    }

    private void MqttClient_Disconnected(object sender, EventArgs e)
    {
        Console.WriteLine("已断开MQTT连接!" + Environment.NewLine);
    }

    private void MqttClient_Connected(object sender, EventArgs e)
    {
        Console.WriteLine("已连接到MQTT服务器!" + Environment.NewLine);
        mqttClient.SubscribeAsync(new List<TopicFilter> {
            new TopicFilter(topic, MqttQualityOfServiceLevel.AtMostOnce)
        });
        Console.WriteLine($"已订阅[{topic}]主题" + Environment.NewLine);
        //开始发布消息
        string inputString = "";
        var appMsg = new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes(inputString), MqttQualityOfServiceLevel.AtMostOnce, false);
        mqttClient.PublishAsync(appMsg);
    }
    private void MqttClient_ApplicationMessageReceived(object sender, MqttApplicationMessageReceivedEventArgs e)
    {
        //接受数据
        Console.WriteLine($">> {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}{Environment.NewLine}");
        CheckForIllegalCrossThreadCalls = false;
       a = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
        richTextBox2.AppendText(a);

        this.richTextBox2.AppendText("\r\n");

保存文本

private void btnsavetext_Click(object sender, EventArgs e)
{
string savetext = this.richTextBox2.Text;

        SaveFileDialog saveFileDialog = new SaveFileDialog();

        saveFileDialog.Filter = "文本文件(*.txt)|*.txt";

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(saveFileDialog.FileName, true);
            sw.Write(savetext);
            sw.Close();

形成图表

  private void bntdrawline_Click(object sender, EventArgs e)
        {
            string date =a;//如果这里是a换成this.richTextBox2.Text,则只会显示第一个数据值。
            date = date.Replace("{", "").Trim(); 
            string[] d1 = date.Split(',');
            string pm = d1[0].Split(':')[1].Replace("\"", "");/
            double pm_25 = Convert.ToInt32(pm);
            string[] d2 = d1[4].Split(':');
            string time = d2[1] + d2[2] + d2[3].TrimEnd('}');
            string x = time;
            double y = pm_25;

            Series series = chartdate1.Series[0];
            series.ChartType = SeriesChartType.Spline;

          
            chartdate1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            chartdate1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
            chartdate1.Series[0].Points.AddXY(x, y);

        }
我们这里需要把数据分离


我的数据格式是
{" ":" ","  ":"  ","  ":"  ","     ":"  ","  ":"2020-11-13 19:48:58"}


运行效果如下
![在这里插入图片描述](https://img-blog.csdnimg.cn/20201128151441101.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5fQ2hlbmV5,size_16,color_FFFFFF,t_70)


# 总结
这里仅形成了一个数据图形
此程序现存一个问题是第一个数据他不显示到图形中,
因为只是简单搞一下,感觉还能·拿来用·,就没有深究,
有哪位大神看到,明白了,告诉俺一声也。互帮互助,

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值