iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 27
1
IoT

來與IoT譜寫一首戀愛樂章吧系列 第 27

op.27 《全領域》-全域開發實戰 - 居家植物盆栽 Mvt II (C# Broker & Mysql)

op.27 紀錄時空間的情話

讓我們彼此之間的記憶與美好時光
永恆紀載

今天來將 Broker 進行改寫吧,把對應的內容記載至資料庫裡。

先看看原本的程式碼:

using System;
using System.Data;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Adapter;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Receiving;
using MQTTnet.Diagnostics;
using MQTTnet.Protocol;
using MQTTnet.Server;

namespace mqtt_3._0._5
{
    class Program
    {
        private static MqttServer MqttServer = null;
        void Main(string[] args)
        {
            MqttAsync();
            while (true) ;

        }
        private static async Task MqttAsync()
        {
            var optionsBuilder = new MqttServerOptionsBuilder().WithConnectionBacklog(100).WithDefaultEndpointPort(1883).WithConnectionValidator(e =>
            {
                
            });
            var mqttServer = new MqttFactory().CreateMqttServer();
            await mqttServer.StartAsync(optionsBuilder.Build());
            mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine($"Client:{e.ClientId} Topic:{e.ApplicationMessage.Topic} Message:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}");
            });
            mqttServer.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(e =>
            {
                Console.WriteLine($"Client:{e.ClientId} 已連接!");
            });
            mqttServer.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(e =>
            {
                Console.WriteLine($"Client:{e.ClientId}已離線!");
            });
        }
    }
}

我們需要將 Mysql 的套件 Nuget 進來,忘記的夥伴可以參考這一篇文章
op.18 《應用層》-C# 與 MySQL的愛情
然後在 private static MqttServer MqttServer = null;下新增 Mysql 的變數

private static MySqlConnection conn = new MySqlConnection();
private static String ConnectionString = "server=127.0.0.1;port=3306;user id=root;password=password;";

為了在運行 MQTT 服務之前測試資料庫是否可以使用,我們先寫一個測試連線的 Function

static void test_Database_Link()
{
    conn.ConnectionString = ConnectionString;
    try
    {
        conn.Open();
        if (conn.State == ConnectionState.Open)
        {
            Console.WriteLine("資料庫已連線");
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

然後將其放在 main 裡,順序先確認資料庫是否可以連線,再啟動 MQTT 服務。

static void Main(string[] args)
{
    test_Database_Link();
    MqttAsync();
    while (true) ;
}

接下來需要在需要紀錄的地方加入寫資料庫的部分,在那之前需要先新增資料庫以及建好資料表。
這裡就建立紀錄濕度的資料庫及資料表吧

CREATE TABLE `data`.`pot_humidity` ( `Date` DATETIME NOT NULL , `Humidity` INT NOT NULL ) ENGINE = MyISAM;

新增資料的部分一樣在op.18 《應用層》-C# 與 MySQL的愛情有寫到,可以回去複習個。
這時候就要考慮韌體發送的 主題 !兩邊主題要一樣才可以進行監聽,並且記錄下來,昨天用的主題為 Data ,那今天我們就針對 Data 來做監聽。

先找到 Broker 監聽訊息的地方,加入主題判斷,符合的主題進入資料庫,並將時間一起紀錄下來。

 mqttServer.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine($"Client:{e.ClientId} Topic:{e.ApplicationMessage.Topic} Message:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}");

            });

我們要針對 Topic 做過濾,所以加入判斷。

if(e.ApplicationMessage.Topic == "Data"){

}

在 if 裡塞入新增資料庫的程式碼。

Console.WriteLine($"Client:{e.ClientId} Topic:{e.ApplicationMessage.Topic} Message:{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}");
conn.ConnectionString = ConnectionString;
try
{
    conn.Open();
    if (conn.State == ConnectionState.Open)
    {
        DateTime date = DateTime.Now;
        var commandStr = "INSERT INTO `data`.`pot_humidity` (`Date`,`Humidity`) VALUES ('" +
        date.ToString("yyyy-MM-dd HH:mm:ss") + "', '" +
        Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0]) + "');";

        var sqlCommand = new MySql.Data.MySqlClient.MySqlCommand(commandStr, conn);
        var dr = sqlCommand.ExecuteNonQuery();
        conn.Close();
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}  

接下來拿出昨天的實作看看是否會寫入資料庫呢?
https://ithelp.ithome.com.tw/upload/images/20201012/20129084sTaNNddFzD.png
https://ithelp.ithome.com.tw/upload/images/20201012/20129084KA9jtGtN5X.png
是的,資料成功寫進去了!恭喜發財!

好啦今天就到這裡啦~感謝各位收看!

今日的曲子:<<小鎮>>盧亮輝

Yes

這首是在國小時候練的,對其旋律非常難忘,簡單卻不會讓人膩的旋律,中間的行板柔美卻又富有韻味,推薦給大家。


上一篇
op.26 《全領域》-全域開發實戰 - 居家植物盆栽 Mvt I (NodeMCU & MQTT)
下一篇
op.28 《全領域》-全域開發實戰 - 居家植物盆栽 Mvt III (Mini-Server:Raspberry Pi)
系列文
來與IoT譜寫一首戀愛樂章吧30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言