logo MSJO.kr

MQTT Client 예제 : C#, Rust, Python

2020-09-11
MsJ
       

MQTT가 IoT에서 메시징 프로토콜로 주목을 받고 있다1. 이를 이용하여 Push 서비스를 C#, Rusth, Python 개발언어를 이용하여 간단하게 구현해 보았다. MQTT Broker는 Mosquitto를 사용하였고 간단한 인증을 위하여 username, password를 설정하였다.

C#, Publish
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet.Client.Connecting;

namespace MqttTest
{
    internal class Program
    {
        private static async Task Main()
        {
            await ClientTest();
        }

        private static async Task ClientTest()
        {
            var mqttClient = new MqttFactory().CreateMqttClient();

            var options = new MqttClientOptionsBuilder().WithTcpServer("xxx.xxx.xxx.xxx", 1883).WithCredentials("username", "password").Build();

            var message = new MqttApplicationMessageBuilder().WithTopic("U001/order").WithPayload("테스트 메시지입니다.").WithExactlyOnceQoS().Build();

            var result = await mqttClient.ConnectAsync(options, CancellationToken.None);

            if (result.ResultCode == MqttClientConnectResultCode.Success)
            {
                await mqttClient.PublishAsync(message);
            }
        }
    }
}
Rust, Publish
extern crate paho_mqtt as mqtt;

use std::{
    process,
    time::Duration,
};

fn main() {
    let cli = mqtt::Client::new("tcp://xxx.xxx.xxx.xxx:1883").unwrap_or_else(|err| {
        println!("Error creating the client: {:?}", err);
        process::exit(1);
    });

    let conn_opts = mqtt::ConnectOptionsBuilder::new()
        .keep_alive_interval(Duration::from_secs(10))
        .clean_session(true)
        .user_name("username")
        .password("password")
        .finalize();

    let disconnect_opts = mqtt::DisconnectOptionsBuilder::new()
        .timeout(Duration::from_secs(10))
        .finalize();

    if let Err(e) = cli.connect(conn_opts) {
        println!("Unable to connect:\n\t{:?}", e);
        process::exit(1);
    }

    let msg = mqtt::Message::new("U001/order", "테스트 메시지입니다.", 2);
    let tok = cli.publish(msg);

    if let Err(e) = tok {
        println!("Error sending message: {:?}", e);
    }

    let tok = cli.disconnect(disconnect_opts);
    tok.unwrap();
}
Python, Publish
import paho.mqtt.client as mqtt

mqtt = mqtt.Client("SSS")
mqtt.username_pw_set("username", "password")
mqtt.connect("xxx.xxx.xxx.xxx", 1883)

mqtt.publish("U001/order", "테스트 메시지입니다.")
print("Published!")

mqtt.loop()
print("Exit")
Python, Subscribe
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("U001/#")

def on_message(client, userdata, msg):
    print(msg.topic + " " + msg.payload.decode())

client = mqtt.Client()
client.username_pw_set("username", "password")
client.on_connect = on_connect
client.on_message = on_message
client.connect("xxx.xxx.xxx.xxx", 1883, 60)
client.loop_forever()

C++(QT)에 대한 내용은 Qt MQTT를 참고한다. Qt MQTT is part of the Qt for Automation offering and not Qt. For further details please see Qt for Automation2.

Reference
  1. joinc, MQTT를 이용한 Push 서비스 개발
  2. Qt MQTT / Example

Prεv(Θld)   Nεxt(Nεw)
Content
Search     RSS Feed     BY-NC-ND