Hello all,
first, sorry for my bad english (but better writing my own bad english than use google translate..)
I just know a little of VB, not C sharp, so it's very hard for me translate all functions of this great library from C#. Anyway, with days of unresponsive tests, i've run a MQTT broker that's correctly started (tested with various clients). Now on server machine i need to start also a client (did it, a managed client..) that manage incoming "external" messages, but really dont know how handle incoming events in VB referred at incoming messages...
Could someone help??
I paste the code i wrote on my VB editor (visual studio 2017) but please dont judge me as i really am a newby.
Thanks alot, any answer appreciate.
PS: I dont know what kind of tag i've to use to paste next code into this message to make it better readable..... :(
Imports System
Imports System.Text
Imports System.Net.Sockets
Imports System.Threading.Tasks
Imports System.IO
Imports System.Collections.Generic
Imports MQTTnet.Client
Imports MQTTnet.ManagedClient
Imports MQTTnet.Protocol
Imports MQTTnet.Server
Imports MQTTnet.Exceptions
Public Class MainForm
Dim MqttServer As New MQTTnet.MqttFactory
' Dim ManagedMqttClient As New MQTTnet.MqttFactory
Dim WithEvents ManagedClient As New MQTTnet.MqttFactory
Dim OptionsBuilderServer As New MQTTnet.Server.MqttServerOptionsBuilder
Dim OptionServer As New MQTTnet.Server.MqttServerOptions
Dim ClientOptions As New MQTTnet.Client.MqttClientOptionsBuilder
Dim Options As New MQTTnet.ManagedClient.ManagedMqttClientOptionsBuilder
Dim TopicBuildClient As New MQTTnet.TopicFilterBuilder
Dim TopicBuild2Client As New MQTTnet.TopicFilterBuilder
Dim MessageoutBuilder As New MQTTnet.MqttApplicationMessageBuilder
Private Async Sub Avvio_MQTT()
'Avvia e connette Broker MQTT
OptionsBuilderServer.WithDefaultEndpointPort(30174)
'optionsBuilderServer.
'optionServer.ConnectionValidator
'optionsBuilderServer.WithConnectionValidator()
Await MqttServer.CreateMqttServer.StartAsync(OptionsBuilderServer.Build)
'Avvia e connette Managed Client MQTT
ClientOptions.WithClientId("LocalClientVsBroker")
ClientOptions.WithTcpServer("127.0.0.1", 30174)
ClientOptions.WithTls()
ClientOptions.WithCleanSession(True)
Options.WithClientOptions(ClientOptions.Build)
Options.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
Await ManagedClient.CreateManagedMqttClient.StartAsync(Options.Build)
'Sottoscrive topic Managed Client
TopicBuildClient.WithTopic("VersusBroker")
Await ManagedClient.CreateManagedMqttClient.SubscribeAsync("VersusBroker", MqttQualityOfServiceLevel.ExactlyOnce)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles start.Click
Avvio_MQTT()
End Sub
Private Sub fine_Click(sender As Object, e As EventArgs) Handles fine.Click
Stop_MQTT()
End Sub
Private Async Sub Stop_MQTT()
Await mqttServer.CreateMqttServer.StopAsync
End Sub
Private Sub ManagedClient_ApplicationMessageReceived()
Dim a
a = 1
End Sub
Private Async Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
messageoutBuilder.WithTopic("VersusBroker")
messageoutBuilder.WithPayload("Messaggio " & Now)
messageoutBuilder.WithExactlyOnceQoS()
messageoutBuilder.WithRetainFlag()
messageoutBuilder.Build()
Await managedClient.CreateManagedMqttClient.PublishAsync(messageoutBuilder)
End Sub
End Class
need to explain......
1) "Private Sub ManagedClient_ApplicationMessageReceived()" was just a try, i don know how to manage events thats part of declared object...
2) "Private Async Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click" was a try to write a message vs broker, no response...
Many of mine tryes born just in my mind, i didn't found noone example to refer....
Hi there,
Sorry, I'm new to MQTT so I can't help with your question, but I also prefer VB and would like to see VB equivalents of the examples.
Normally, C# & VB syntax is quite similar and isn't too difficult to convert yourself, but this has beaten me.
I've tried various, online code converters but none of them can convert the code - probably because they are not aware of the special references.
PLEASE can we have VB examples?
Thanks
Sorry but I am no VB developer. So I cannot provide example. If there is anyone feel free to extend the Wiki.
Hi,
I've since got the tcp client working in VB but I don't have access to the code for a week or so.
I'll post back when I can, but the client example given here is actually fairly straightforward to convert.
Hi,
I've since got the tcp client working in VB but I don't have access to the code for a week or so.
I'll post back when I can, but the client example given here is actually fairly straightforward to convert.
Hey dazzalogan...
It's been awhile since you posted this, but I (and others!?!) would be very interested in your successful VB client implementation of MQTTnet that you mentioned. I'm rather fluent in VB.NET, but my C#, errrr shaky.
Thanks!
My PoC/test VB.NET console code, anyone is welcome to reuse and hopefully even add to wiki (the thread handling is probably not great but it works):
Imports System.Text
Imports System.Threading
Imports System.IO
Imports MQTTnet
Imports MQTTnet.Client
Imports MQTTnet.Client.Options
Imports MQTTnet.Client.Connecting '' Not actually used, for now
Imports MQTTnet.Client.Disconnecting
Module Module1
Dim OutputFile As StreamWriter
Dim mqttClient As MqttClient
Dim Factory As MqttFactory = New MqttFactory()
Sub Main()
OutputFile = New StreamWriter(My.Application.Info.DirectoryPath & "\MQTT" & DateTime.Now.ToString("yyyyMMddhhmmss") & ".txt")
OutputFile.AutoFlush = True
Start.GetAwaiter.GetResult()
End Sub
Async Function Start() As Task
mqttClient = Factory.CreateMqttClient()
mqttClient.UseApplicationMessageReceivedHandler(AddressOf MessageRecieved)
mqttClient.UseDisconnectedHandler(AddressOf ConnectionClosed)
Dim Options As New MqttClientOptionsBuilder
With Options
.WithTcpServer("127.0.0.1")
.WithClientId("MQTTnet Test")
.WithCredentials("test", "test")
End With
Await mqttClient.ConnectAsync(Options.Build)
Await mqttClient.SubscribeAsync("/wibble")
Await Task.Delay(Timeout.Infinite)
End Function
Private Sub MessageRecieved(e As MqttApplicationMessageReceivedEventArgs)
SpamText(e.ApplicationMessage.Topic & " - " & Encoding.UTF8.GetString(e.ApplicationMessage.Payload))
End Sub
Private Sub ConnectionClosed(e As MqttClientDisconnectedEventArgs)
SpamText("Closed")
End '' Should really be much neater and even to reconnect, but this is just a test right...
End Sub
Private Sub SpamText(Message As String)
Debug.Print(Message)
Console.Write(Message & vbNewLine)
OutputFile.WriteLine(Message)
End Sub
End Module
Hi to everybody.
First of all, thanks to chkr1011 for Mqttnet library, it´s a fantastic job.
Well, like pompierecattivo I´m newbye with IoT and Mqtt, and I feel more comfortable with VB than with C#.
I'm very interested in building a Mqtt communication between 2 computers. The adamwSE code helps me a lot on the client´s part.
I dare to ask if anyone has a similar code for the server´s part. I prefer VB but C# could help me to.
Thanks and best regards!
I do not exactly see the problem with VB and C#? The code is exchangeable 1:1 and conversion can be done online?? If you want, I can extend the wiki on that...
Hi SeppPenner, thanks to answer so quickly!
I´m fully agree with you, VB and C# are very similar, but I´m more confortable with VB... old person nonsenses :)
what I would like to see really is broker code fully implemented. It would be very helpfull for me.
thanks again and have a nice weekend!
Download http://www.icsharpcode.net/OpenSource/SD/Download/Default.aspx#SharpDevelop4x and follow the instructions from Stackoverflow: https://stackoverflow.com/questions/4559950/how-to-convert-full-c-sharp-project-to-vb-net.~~ (This does not work...)
If you want to check some classes or functions only, I would recommend: http://converter.telerik.com/.
If you want to have the whole project as VB, try to compile it from source using Visual Studio (Or download the release dlls) and inspect them with https://github.com/0xd4d/dnSpy (It allows to show C# and VB code).
This are the easiest options to do this.
Hello, where can you download the dll files? Greetings Mike
Imports MQTTnet
Imports MQTTnet.Client
Imports MQTTnet.Client.Options
Imports MQTTnet.Client.Connecting '' Not actually used, for now
Imports MQTTnet.Client.Disconnecting
They're part of the MQTTnet nuget package. In VS right click References in your solution tree and choose "Manage nuget Packages" and from there search for MQTTnet and download.
As @adamwSE already said: Either from the nuget package and checking the nuget folder or from building the source.
Hi again!
@adamwSE, then your code, can be used like a Publisher or a Suscriber with a borker than Mosquitto, can´t it?
I´m trying, but I don´t make it to work
Hi again!
@adamwSE, then your code, can be used like a Publisher or a Suscriber with a borker than Mosquitto, can´t it?
I´m trying, but I don´t make it to work
You can use the client like this (Check the other available options in the wiki and adjust them as needed):
var factory = new MqttFactory();
var mqttClient = factory.CreateMqttClient();
var options = new MqttClientOptionsBuilder().WithClientId("ClientId")
.WithTcpServer("ServerName", 8883)
.WithCredentials("UserName", "Password").WithTls().WithCleanSession().Build();
mqttClient.ConnectAsync(options);
or in VB.Net:
Private Sub SurroundingSub()
Dim factory = New MqttFactory()
Dim mqttClient = factory.CreateMqttClient()
Dim options = New MqttClientOptionsBuilder().WithClientId("ClientId").WithTcpServer("ServerName", 8883).WithCredentials("UserName", "Password").WithTls().WithCleanSession().Build()
mqttClient.ConnectAsync(options)
End Sub
You can easily convert the client code from the wiki (https://github.com/chkr1011/MQTTnet/wiki/Client) to VB.Net using http://converter.telerik.com/.
@pepelolo30 If you have further questions, create a new issue and provide detailed information on what you did (and what you're trying to do so that @chkr1011 and the others here can help you), please.
I do use mosquitto as the broker so the code above will work with it. Didn't try publishing anything though, wasn't interested at the time to see.
Hello,
Given the lack of explanations and references on how to use Vb.net & mqtt
I have written an example code with all the basic features for MQTT Client
https://github.com/bassouma21001/MQTTBasic
I hope to be useful
Thank you for that work. You can also add them in the wiki in this project
if you like.
Bousselmi Bessem notifications@github.com schrieb am Di., 5. Mai 2020,
08:44:
Hello,
Given the lack of explanations and references on how to use Vb.net & mqtt
I have written an example code with all the basic features for MQTT Client
https://github.com/bassouma21001/MQTTBasic
I hope to be useful—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/chkr1011/MQTTnet/issues/333#issuecomment-623882601,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/ABU6JIUQ3IBWARCHHJLV3VTRP6YTZANCNFSM4FGXWS3Q
.
Hello, thank you to adamwSE for almost working VB.NET code. I´ve finished some corrections.
Issues of codes around here and there that freezes the thread:
DO NOT USE Task1.GetAwaiter. GetResult
NOT WAIT continue with Task2, use Task1 .GetAwaiter
Using Async Sub instead of Function As Task you can use Task1 .Start
WAIT for Task1 to end, use Task1 .Wait, but you must any Await call treat with
Await mqClient.ConnectAsync(Options.Build).ConfigureAwait(False)
VB.NET code for MQTTnet. Here you are, nice async functions:
Dim mqClient As MqttClient
Dim mqFactory As New MqttFactory
Sub mmqt_start()
Connect("client", "host", "user", "pass").Wait()
Publish("topic/volume", "20").Wait()
Subscribe("topic/volume").Wait()
End Sub
Async Function Connect(Client As String, Server As String, User As String, Password As String) As Task
mqClient = CType(mqFactory.CreateMqttClient(), MqttClient)
mqClient.UseApplicationMessageReceivedHandler(AddressOf MessageRecieved)
mqClient.UseDisconnectedHandler(AddressOf ConnectionClosed)
mqClient.UseConnectedHandler(AddressOf ConnectionOpened)
Dim Options As New Options.MqttClientOptionsBuilder
Options.WithClientId(Client).WithTcpServer(Server, 1883).WithCredentials(User, Password)
Await mqClient.ConnectAsync(Options.Build).ConfigureAwait(False)
End Function
Async Function Publish(Topic As String, Payload As String) As Task
Await mqClient.PublishAsync(Topic, Payload).ConfigureAwait(False)
End Function
Async Function Subscribe(Topic As String) As Task
Await mqClient.SubscribeAsync(Topic).ConfigureAwait(False)
End Function
Private Sub MessageRecieved(e As MqttApplicationMessageReceivedEventArgs)
MessageBox.Show("Topic: " & e.ApplicationMessage.Topic & Chr(10) & Chr(13) &
"Payload: " & Text.Encoding.UTF8.GetString(e.ApplicationMessage.Payload))
End Sub
Private Sub ConnectionClosed(e As Disconnecting.MqttClientDisconnectedEventArgs)
MessageBox.Show("Connection closed.")
End Sub
Private Sub ConnectionOpened(e As Connecting.MqttClientConnectedEventArgs)
MessageBox.Show("Connection opened.")
End Sub
Awesome! I did say my threading wasn't great, glad to see someone updated it and explained the reasoning.
@pyramidak Thank you for your effort here :)
I have added your code to the wiki under https://github.com/chkr1011/MQTTnet/wiki/Examples and https://github.com/chkr1011/MQTTnet/wiki/Using-the-MQTT-client-in-VB.net just in case someone searches for that :)
Most helpful comment
I do use mosquitto as the broker so the code above will work with it. Didn't try publishing anything though, wasn't interested at the time to see.