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 ?
Related
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);
}
I have programmed a server and a client application under Xamarin C# (for PC and Android phone).
Now I have a problem with the umlauts (äöüÄÖÜ) at Text.Encoding.Default.GetBytes () / Encoding.Default.GetString ().
If the server and client running on the PC, umlauts are converted correctly. When operated smartphone and PC only question marks will be issued on conversion of umlauts. All other data is converted properly.
Where is the problem?
private void cButtonSend_Click(object sender, EventArgs e)
{
try
{
if (cAktiveClient == "") Toast.MakeText(this, "Wählen Sie einen Client aus!", ToastLength.Long).Show();
else
{
string txt = cSendeText.Text;
byte[] telegramm = new byte[txt.Length];
telegramm = System.Text.Encoding.Default.GetBytes(txt);
foreach (TcpClient c in cServer.ClientList)
{
if (c.Client.RemoteEndPoint.ToString() == cAktiveClient) cServer.Send(c, telegramm);
}
cSendeText.Text = "";
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
}
}
private void cServer_Recieve(object sender, EventArgs e)
{
// bei Aufrufen aus anderenThreads
this.RunOnUiThread(() =>
{
try
{
TCPIP_MultiServer t = sender as TCPIP_MultiServer;
cEmpfangsClient.Text = t.NowClient.Client.RemoteEndPoint.ToString();
cEmpfangsText.Text = Encoding.Default.GetString(cServer.Buffer, 0, cServer.RecievedBytes);
}
catch (Exception ex)
{
Toast.MakeText(this, ex.Message, ToastLength.Long).Show();
}
});
}
To reduce the size of the application, Xamarin doesn't include any specific encodings.
Read this:
https://developer.xamarin.com/guides/ios/advanced_topics/localization_and_internationalization/encodings/ (on Android it's the same)
And this:
https://developer.xamarin.com/guides/cross-platform/xamarin-forms/localization/
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?
I am currently working on C# application which requires to read serial port. In UI, there is a ON/OFF button which enables user click on it to start and stop reading data from serial port. If I continuously click on the button on and off. It threw an exception - Access to COM3 is denied or even said "The device is not connected". Can anyone suggest a better way to implement the serial port function which is able to resolve the situation as described above? Here is the code I use:
**// Start reading data from serial port**
public override void StartReading(string portname)
{
try
{
int k = int.Parse(portname.Replace("COM", ""));
if (startThread != null)
{
startThread.Abort();
startThread = null;
}
startThread = new Thread(new ThreadStart(delegate
{
isActive = true;
try
{
using (SerialPort sp = new SerialPort(portname))
{
if (!isActive)
{
DisposeBT(sp);
return;
}
sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
if (!isActive)
{
DisposeBT(sp);
return;
}
if (!isActive)
{
DisposeBT(sp);
return;
}
else
{
Thread.Sleep(6500);
try
{
if (sp != null && !sp.IsOpen)
{
sp.Open();
}
}
catch (Exception ex)
{
Logger.Warn("Failed to open the serial port for HRM once. Try it again.");
Logger.Error(ex);
////////////////////// new added below
if(sp !=null && sp.IsOpen)
{
sp.Dispose();
}
Thread.Sleep(6500);
if (IsPortAvailable(k))
{
try
{
if (sp != null && !sp.IsOpen)
{
sp.Open();
}
}
catch (Exception ex1)
{
////////////////////// new added below
if (sp != null && sp.IsOpen)
{
sp.Dispose();
}
Logger.Warn("Failed to open the serial for HRM twice.");
Logger.Error(ex1);
// return;
}
}
}
}
while (true)
{
if (!isActive)
{
DisposeBT(sp);
break;
}
}
if (!isActive)
{
DisposeBT(sp);
return;
}
DisposeBT(sp);
}
}
catch (Exception ex)
{
Logger.Warn("Exception thrown for HRM.");
Logger.Error(ex);
}
}));
startThread.IsBackground = true;
startThread.Priority = ThreadPriority.Highest;
startThread.Start();
}
catch (Exception ex)
{
Logger.Warn("Failed to start reading for HRM02I3A1 bluetooth device.");
Logger.Error(ex);
}
}
// Stop reading data from serial port
public override void StopReading()
{
try
{
isActive = false;
}
catch { }
}
// event handler for the serial port to read data from sp.
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (isActive)// && startThread.IsAlive
{
SerialPort sp1 = (SerialPort)sender;
try
{
sp1.Read(data, 0, 8);
decoder.Decode(data);
}
catch(Exception ex)
{
Logger.Warn("------data received from Serial Port error for HRM-------");
Logger.Error(ex);
};
}
}
first make background worker thread that accept the cancel event.
in the DoWork method you can write something like that
void DoWork{
// init com port
while(no body cancelled the background worker){
// if there any waiting data receive and process it. do not use event handlers
}
// close the serial port so you can open it again later.
}
Also if you want to cancel the background work it would be a piece of cake
// send cancel command.
// wait till it is canceled.
Try adding startThread.Join() directly after the call to startThread.Abort().
Take a look at the msdn documentation on Thread.Abort and perhaps you also should check what join does.
I'm trying to scan multiple ports at once using asynchronymous scanning. The problem is that I can only display the first working port and then waiting like 20 seconds my app is closing with out telling me that the port is closed.
What could be wrong with this code?
private void btnStart_Click(object sender, EventArgs e)
{
for (int port = 80; port < 100; port++)
{
ScanPort(port);
}
}
private void ScanPort(int port)
{
var client = new TcpClient();
try
{
client.BeginConnect(IPAddress.Parse("74.125.226.84"), port, new AsyncCallback(CallBack), client);
}
catch (SocketException)
{
client.Close();
}
}
private void CallBack(IAsyncResult result)
{
var client = (TcpClient)result.AsyncState;
client.EndConnect(result);
if (client.Connected)
{
this.Invoke((MethodInvoker)delegate
{
txtDisplay.Text += "open2" + Environment.NewLine;
});
}
else
{
this.Invoke((MethodInvoker)delegate
{
txtDisplay.Text += "closed2" + Environment.NewLine;
});
}
}
In your callback method, I would make sure close the connection and dispose of the TcpClient. Also TcpClient.EndConnect(IAsyncResult) can also throw exceptions. I also do not see where capturing the port number for display to the user. I would write the callback something like this.
Edit: I didn't actually compile or execute my code (sorry). I also found this other article that shows how to create a port scanner in C#, http://www.dijksterhuis.org/building-a-simple-portscanner-in-c/ There is a comment in this post stating,
There is a gotcha here : The .NET implementation of TCPClient.Close() function does not actually close the connection properly. So we need to do the additional steps of obtaining the stream representing the connection and closing this as well before calling TCPClient.Close.
private void CallBack(IAsyncResult result)
{
var client = (TcpClient)result.AsyncState;
bool connected = false;
try
{
client.EndConnect(result);
connected = client.Connected;
}
catch (SocketException)
{
}
catch (ObjectDisposedException)
{
}
finally
{
if (client.Connected)
{
client.Close();
}
client.Dispose();
}
if (connected)
{
this.Invoke((MethodInvoker)delegate
{
txtDisplay.Text += "open2" + Environment.NewLine;
});
}
else
{
this.Invoke((MethodInvoker)delegate
{
txtDisplay.Text += "closed2" + Environment.NewLine;
});
}
}