MQTT in Python, C# and JavaScript
MQTT is on my horizon for a lot of communication projects, I am going to experiment.
So I am gathering basic samples how to use it in different languages.
- Python, usefull for Linux and Raspberry PI
- C#, because I am a PC
- JavaScrip + Node, usefull if used with Azure Function or Amazon Lambda
- JavaScript in a Browser
Python
Roughly, what to install on Windows.
- Download Python 2.7
- Pip package manager. Download and run pip https://bootstrap.pypa.io/get-pip.py
- C:\Python27\python.exe get-pip.py # to install pip
- Use pip to download the package paho-mqtt
- C:\Python27\Scripts\pip install paho-mqtt
For more setup info, see page hivemq.com.
Subscribe
import paho.mqtt.client as paho
def on_subscribe(client, userdata, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
def on_message(client, userdata, msg):
print("topic:"+msg.topic+" qos:"+str(msg.qos)+" payload:"+str(msg.payload))
client = paho.Client()
client.on_subscribe = on_subscribe
client.on_message = on_message
client.connect("broker.mqttdashboard.com", 1883)
client.subscribe("encyclopedia/temperature", qos=1)
client.loop_forever()
Publish
import paho.mqtt.client as paho
import time
def on_publish(client, userdata, mid):
print("mid: "+str(mid))
client = paho.Client()
client.on_publish = on_publish
client.connect("broker.mqttdashboard.com", 1883)
client.loop_start()
temperature = 90
while True:
print("temperature:%d " % temperature)
(rc, mid) = client.publish("encyclopedia/temperature", str(temperature), qos=1)
time.sleep(2)
temperature = temperature + 1
C#
For C# I am using the library M2Mqtt, that can be downloaded from NuGet.
Complere Source Code MQTT CSharp.cs
Complere Source Code MQTT CSharp.cs
Subscribe
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
}
const string mqttServer = "broker.mqttdashboard.com";
const string pusblishedVar = "encyclopedia/temperature";
private static void SubscribeAndListen(string CLIENT_ID_SUB)
{
MqttClient client;
Console.WriteLine("Setting up subscribe mode:{0}, clientID:{1}", mqttServer, CLIENT_ID_SUB);
client = new MqttClient(mqttServer);
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
client.MqttMsgSubscribed += Client_MqttMsgSubscribed;
client.Connect(CLIENT_ID_SUB);
client.Subscribe(new string[] { pusblishedVar }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE });
var displayMenu = new Action(delegate()
{
Console.Clear();
Console.WriteLine("Q)uit C)lear - Waiting...");
});
var quit = false;
displayMenu();
while (!quit)
{
if (Console.KeyAvailable)
{
switch (Console.ReadKey().Key)
{
case ConsoleKey.Q: quit = true; break;
case ConsoleKey.C: ; displayMenu(); break;
}
}
Thread.Sleep(250);
}
client.Disconnect();
}
Publish
const string mqttServer = "broker.mqttdashboard.com";
const string pusblishedVar = "encyclopedia/temperature";
private static void Publish(string CLIENT_ID_PUB)
{
Console.WriteLine("Setting up publish mode ClientID:{0}", CLIENT_ID_PUB);
var client = new MqttClient(mqttServer);
client.Connect(CLIENT_ID_PUB);
var varValue = 70;
client.MqttMsgPublished += Client_MqttMsgPublished;
Console.WriteLine("Publishing {0}:{1}", pusblishedVar, varValue);
client.Publish(pusblishedVar, Encoding.UTF8.GetBytes(varValue.ToString()), MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, false);
client.Disconnect();
}
JavaScript + Node.js
To install MQTT package
nmp install mqtt
Publish
// contoller.js and garage.js
var mqtt = require('mqtt')
var client = mqtt.connect("mqtt://broker.mqttdashboard.com");//, 1883)
client.on('connect', function() {
console.log("Connected, Publishing.");
// Inform controllers that garage is connected
client.publish('encyclopedia/temperature', '66')
})
/**
* Want to notify controller that garage is disconnected before shutting down
*/
function handleAppExit (options, err) {
console.log("Exiting...")
if (err) {
console.log(err.stack)
}
if (options.cleanup) {
}
if (options.exit) {
process.exit()
}
}
/**
* Handle the different ways an application can shutdown
*/
process.on('exit', handleAppExit.bind(null, {
cleanup: true
}))
process.on('SIGINT', handleAppExit.bind(null, {
exit: true
}))
process.on('uncaughtException', handleAppExit.bind(null, {
exit: true
}))
No comments:
Post a Comment