I am using MQTT.fx and
"test.mosquitto.org"
locally as a broker. Now i want to send a message from the broker to Visual Studio (where I am connected with the client/broker). How does that work? What I have since now is:
Edit: Obviously
//await client.PublishAsync(new MqttApplicationMessage(topic,
Encoding.UTF8.GetBytes($"{message}")),
MqttQualityOfService.ExactlyOnce); //QOS 2
is not working at the moment...
private async void OnButton2Clicked(object sender, EventArgs e)
{
try
{
testLabel2.Text = "test";
await client.SubscribeAsync(topic, MqttQualityOfService.ExactlyOnce); //QOS 2
//await client.PublishAsync(new MqttApplicationMessage(topic, Encoding.UTF8.GetBytes($"{message}")), MqttQualityOfService.ExactlyOnce); //QOS 2
OnMessageReceived();
}
catch (Exception ex)
{
testLabel2.Text = "Ausnahme gefunden: " + ex.Message;
}
}
///////////////////////////////////////////////
private void OnMessageReceived()
{
MessagingCenter.Subscribe<IMqttClient>(topic, "Hallooo", (sender) =>
{
testLabel2.Text = "Du hast eine Nachricht bekommen";
});
}
private async void SubscriptionTemp() **// Here I make a method, to subscribe a temperature.**
{
if (MainPage.client2.IsConnected) **//Check if IMqttClient is connected**
{
await MainPage.client2.SubscribeAsync(topicTemp, MqttQualityOfService.AtMostOnce); // QOS 0
MainPage.client2
.MessageStream
.Where(msg => msg.Topic == topicTemp)
.Subscribe(msg => onTempRelayReceived(msg));
}
}
private void onTempRelayReceived(MqttApplicationMessage msg)
{
string msgEncoded = (Encoding.UTF8.GetString(msg.Payload)); // **Here I assign the payload received from mqtt as a string.**
tempRelay = double.Parse(msgEncoded);
}
Related
I'm trying to connect to Mosquitto using MQTTnet. I am able to receive messages but IsConnected property is false. Anyone know why?
Only property iStart is set to true.
The problem seems to be with the Mosquitto host.
mosquitto.conf is mostly defaults. I only have these parameters set:
allow_anonymous true
password_file C:\mosquitto\passwd
tls_version tlsv1.2
log_dest file C:\mosquitto\log\mosquitto.log
Log file is empty.
class Program
{
static async Task Main()
{
var mqttClientId = "MyClientId"; // Unique ClientId or pass a GUID as string for something random
var mqttBrokerAddress = "localhost"; // hostname or IP address of your MQTT broker
var mqttBrokerUsername = "guest"; // Broker Auth username if using auth
var mqttBrokerPassword = "guest"; // Broker Auth password if using auth
var topic = "topic"; // topic to subscribe to
var mqttClient = new MqttFactory().CreateManagedMqttClient();
var mqttClientOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithTcpServer(mqttBrokerAddress, 1883)
.WithCredentials(mqttBrokerUsername, mqttBrokerPassword) // Remove this line if no auth
.WithCleanSession().WithKeepAlivePeriod(new TimeSpan(1))//.WithTls(tlsOptions)
.Build()
)
.Build();
mqttClient.ApplicationMessageReceivedAsync += async e => MqttOnNewMessage(e);
mqttClient.ConnectedAsync += async e => MqttOnConnected(e);
mqttClient.DisconnectedAsync += async e => MqttOnDisconnected(e);
mqttClient.SynchronizingSubscriptionsFailedAsync += async e => test(e);
mqttClient.ConnectingFailedAsync += async e => test2(e);
var aaa = new List<MqttTopicFilter>();
var bbb = new MqttTopicFilterBuilder().WithTopic(topic).Build();
aaa.Add(bbb);
try
{
await mqttClient.SubscribeAsync(aaa);
await mqttClient.StartAsync(mqttClientOptions);
System.Console.WriteLine(mqttClient.IsConnected);
}
catch (Exception ex)
{
throw;
}
Console.ReadLine();
}
private static void test2(ConnectingFailedEventArgs e)
{
Console.WriteLine();
}
private static void test(ManagedProcessFailedEventArgs e)
{
Console.WriteLine();
}
private static void MqttOnNewMessage(MqttApplicationMessageReceivedEventArgs e)
{
// Do something with each incoming message from the topic
Console.WriteLine($"MQTT Client: OnNewMessage Topic: {e.ApplicationMessage.Topic} / Message: {e.ApplicationMessage.Payload}");
}
private static void MqttOnConnected(MqttClientConnectedEventArgs e) => Console.WriteLine($"MQTT Client: Connected with result: {e.ConnectResult.ResultCode}");
private static void MqttOnDisconnected(MqttClientDisconnectedEventArgs e) => Console.WriteLine($"MQTT Client: Broker connection lost with reason: {e.Reason}.");
}
I'm using Two await function in my program, and first one is working flawlessly but on encountering second await, my program comes out of function without executing that awaitable function and any line after that.
Not giving error and not even crashing.
Tried "wait()", "Running on main thread", "Task Run", "Threading Sleep"..
here a snippet of the code along
private async void Btn_Clicked(object sender, EventArgs e)
{
//this statement works perfectly fine
var status = await CrossPermissions.Current.RequestPermissionAsync<LocationPermission>();
//on debugging i found out it return out of function at this point without executing
var check = await CrossPermissions.Current.RequestPermissionAsync<CameraPermission>();
//None of the code is executed
Console.WriteLine("Granted");
Console.WriteLine("Granted");
}
You try to use the below method :
private async void Btn_Clicked(object sender, EventArgs e)
{
await GetPermissions();
}
public static async Task<bool> GetPermissions()
{
bool permissionsGranted = true;
var permissionsStartList = new List<Permission>()
{
Permission.Location,
Permission.Camera,
};
var permissionsNeededList = new List<Permission>();
try
{
foreach (var permission in permissionsStartList)
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(permission);
if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
permissionsNeededList.Add(permission);
}
}
}
catch (Exception ex)
{
}
var results = await CrossPermissions.Current.RequestPermissionsAsync(permissionsNeededList.ToArray());
try
{
foreach (var permission in permissionsNeededList)
{
var status = Plugin.Permissions.Abstractions.PermissionStatus.Unknown;
//Best practice to always check that the key exists
if (results.ContainsKey(permission))
status = results[permission];
if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted || status == Plugin.Permissions.Abstractions.PermissionStatus.Unknown)
{
permissionsGranted = true;
}
else
{
permissionsGranted = false;
break;
}
}
}
catch (Exception ex)
{
}
return permissionsGranted;
}
Iam developing a WPF application to interact with ELM327. The communication medium between myApp and ELM327 is USB protocol. ELM327 is connected to vehicle through OBD port. My app able to establish USB communication successfully. Whatever command Iam sending from my App, Iam getting ? as reply. I set baud rate as 9600. For example, I sent ATZ, iam getting ? as reply. I sent 010D, I got ?. I tried with the app comes along with ELM327, that app can successfully able to extract data.
MyApp USB communication connect code:
public SerialPort sport;
private void Button_Click(object sender, RoutedEventArgs e)
{
int baudValue=0;
if (cbBaud.Text == null)
MessageBox.Show("select a baud rate");
else
{
if (cbBaud.Text != null)
{
baudValue = int.Parse(cbBaud.Text);
}
serialConnect(baudValue);
}
}
public void serialConnect(int baudRate)
{
try
{
if (tbCOM.Text != null)
{
sport = new System.IO.Ports.SerialPort(tbCOM.Text,
baudRate);
if (!sport.IsOpen)
{
sport.Open();
sport.DataReceived += new SerialDataReceivedEventHandler(serialDataReceived);
elIndicator.Fill = Brushes.Green;
}
else
{
MessageBox.Show("Connection already Opened");
}
}
}
catch(Exception EX)
{
MessageBox.Show("Connection Error");
}
}
MyApp data sent code:
private void BtSent_Click(object sender, RoutedEventArgs e)
{
try
{
sport.WriteLine(tbSend.Text);
}
catch(Exception EX)
{
MessageBox.Show("Write Error");
}
}
MyApp data receive code:
private void serialDataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.Dispatcher.Invoke((Action)(() =>
{
recData.Text = "\n";
recData.Text = System.Environment.NewLine + sport.ReadExisting();
}));
}
Is there any initialization code amI have to sent ?
can anyone please help me with to parse data from xml file(bot a local file in my pc ) . I really don't know what to do ..I think i should use httpclient since it's not a local file...i know i should've put some code snippets but it's really so messed up .. as i changed in i a lot .. thanks in advance
First this the code i tried to use but it didn't work
private async void Start_Click(object sender, RoutedEventArgs e)
{
Uri resourceAddress;
// The value of 'AddressField' is set by the user and is therefore untrusted input. If we can't create a
// valid, absolute URI, we'll notify the user about the incorrect input.
if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress))
{
rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
return;
}
Helpers.ScenarioStarted(StartButton, CancelButton, OutputField);
rootPage.NotifyUser("In progress", NotifyType.StatusMessage);
try
{
HttpResponseMessage response = await httpClient.GetAsync(resourceAddress).AsTask(cts.Token);
await Helpers.DisplayTextResultAsync(response, OutputField, cts.Token);
response.EnsureSuccessStatusCode();
XElement element = XElement.Parse(await response.Content.ReadAsStringAsync().AsTask(cts.Token));
OutputList.ItemsSource = (
from c in element.Elements("item")
select c.Attribute("name").Value);
rootPage.NotifyUser("Completed", NotifyType.StatusMessage);
}
catch (TaskCanceledException)
{
rootPage.NotifyUser("Request canceled.", NotifyType.ErrorMessage);
}
catch (Exception ex)
{
rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
}
finally
{
Helpers.ScenarioCompleted(StartButton, CancelButton);
}
}
private void Cancel_Click(object sender, RoutedEventArgs e)
{
cts.Cancel();
cts.Dispose();
// Re-create the CancellationTokenSource.
cts = new CancellationTokenSource();
}
public void Dispose()
{
if (httpClient != null)
{
httpClient.Dispose();
httpClient = null;
}
if (cts != null)
{
cts.Dispose();
cts = null;
}
}
I am building an application , in which I need to have a c# server and nodejs client. I have built the components , but I am always getting ECONNREFUSED error. any leads when I can except this error?
FYI,
I am able to connect to c# server from c# client. similarly. I am able to connect to nodejs tcp server from nodejs tcp client. however the I am facing error with this mixture.
hey sorry for not adding code earlier.
the following is the c# server code:
using System;
using System.Text;
using AsyncClientServerLib.Server;
using System.Net;
using AsyncClientServerLib.Message;
using SocketServerLib.SocketHandler;
using SocketServerLib.Server;
namespace TestApp
{
delegate void SetTextCallback(string text);
public partial class FormServer : Form
{
private BasicSocketServer server = null;
private Guid serverGuid = Guid.Empty;
public FormServer()
{
InitializeComponent();
}
protected override void OnClosed(EventArgs e)
{
if (this.server != null)
{
this.server.Dispose();
}
base.OnClosed(e);
}
private void buttonStart_Click(object sender, EventArgs e)
{
this.serverGuid = Guid.NewGuid();
this.server = new BasicSocketServer();
this.server.ReceiveMessageEvent += new SocketServerLib.SocketHandler.ReceiveMessageDelegate(server_ReceiveMessageEvent);
this.server.ConnectionEvent += new SocketConnectionDelegate(server_ConnectionEvent);
this.server.CloseConnectionEvent += new SocketConnectionDelegate(server_CloseConnectionEvent);
this.server.Init(new IPEndPoint(IPAddress.Loopback, 2147));
this.server.StartUp();
this.buttonStart.Enabled = false;
this.buttonStop.Enabled = true;
this.buttonSend.Enabled = true;
MessageBox.Show("Server Started");
}
void server_CloseConnectionEvent(AbstractTcpSocketClientHandler handler)
{
MessageBox.Show(string.Format("A client is disconnected from the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void server_ConnectionEvent(AbstractTcpSocketClientHandler handler)
{
MessageBox.Show(string.Format("A client is connected to the server"), "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
void server_ReceiveMessageEvent(SocketServerLib.SocketHandler.AbstractTcpSocketClientHandler handler, SocketServerLib.Message.AbstractMessage message)
{
BasicMessage receivedMessage = (BasicMessage)message;
byte[] buffer = receivedMessage.GetBuffer();
if (buffer.Length > 1000)
{
MessageBox.Show(string.Format("Received a long message of {0} bytes", receivedMessage.MessageLength), "Socket Server",
MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
string s = System.Text.ASCIIEncoding.Unicode.GetString(buffer);
this.SetReceivedText(s);
}
private void buttonStop_Click(object sender, EventArgs e)
{
this.server.Shutdown();
this.server.Dispose();
this.server = null;
this.buttonStart.Enabled = true;
this.buttonStop.Enabled = false;
this.buttonStop.Enabled = false;
MessageBox.Show("Server Stopped");
}
private void SetReceivedText(string text)
{
if (this.textBoxReceived.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetReceivedText);
this.Invoke(d, new object[] { text });
}
else
{
this.textBoxReceived.Text = text;
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
ClientInfo[] clientList = this.server.GetClientList();
if (clientList.Length == 0)
{
MessageBox.Show("The client is not connected", "Socket Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
AbstractTcpSocketClientHandler clientHandler = clientList[0].TcpSocketClientHandler;
string s = this.textBoxSend.Text;
byte[] buffer = System.Text.ASCIIEncoding.Unicode.GetBytes(s);
BasicMessage message = new BasicMessage(this.serverGuid, buffer);
clientHandler.SendAsync(message);
}
}
}
The following is the nodejs client code.
var sys = require("sys"),
net = require("net");
var client = net.createConnection(2147);
client.setEncoding("UTF8");
client.addListener("connect", function() {
sys.puts("Client connected.");
// close connection after 2sec
setTimeout(function() {
sys.puts("Sent to server: close");
client.write("close", "UTF8");
}, 2000);
});
client.addListener("data", function(data) {
sys.puts("Response from server: " + data);
if (data == "close") client.end();
});
client.addListener("close", function(data) {
sys.puts("Disconnected from server");
});
I am able to solve the issue. This is just a overlook issue. In server code , I am using lan address assigned to my machine , but in client side , I am using 127.0.0.1 . when I changed the both to same value , I amnot getting econnrefused error.
Now I am able to send and receive data. However I am getting ECONNRESET error very frequently. any leads?