Serial Port not reading - C# - c#

I have a machine where I have to read the data coming through comport. But the comport output is this one link on the picture below:
I have created a program where I was able to intercept the data coming through but it was the "normal" Com Port.
Cable is working normally, when I connect to a printer, it prints normally. What I need to do is get, on my program, the same data that is printed. I sucessfully have done that but not with this different output(image 1). The class I am using the SerialPort class to do this work for me.
SerialPort port = new SerialPort();
My code is working. I am just wondering if for the output(image 1) I have to use a different class. I couldn't find anything related to that, once I search anything related to COM Port or Serial Port, I ended up on the same results, that's why I am here.
Hope I could myself clear.
Thanks
My class:
using System;
using System.IO.Ports;
namespace SerialReader
{
class PortReader
{
static void Main(string[] args)
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in ports)
{
Console.WriteLine(port);
}
Console.WriteLine("Enter the COM Port: ");
string comport = Console.ReadLine();
var reader = new ArduinoSerialReader(comport);
Console.ReadLine();
}
}
public class ArduinoSerialReader : IDisposable
{
private SerialPort _serialPort;
public ArduinoSerialReader(string portName)
{
_serialPort = new SerialPort(portName);
_serialPort.Open();
_serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
Console.WriteLine(_serialPort.ReadLine());
}
public void Dispose()
{
if (_serialPort != null)
{
_serialPort.Dispose();
}
}
}
}

Related

Communication between STM32 and C# via ESP8266

I'm now trying to connect STM32F429 to C# desktop application with ESP8266(in STA mode). I want ESP8266 to be a client and C# to be a Server. However ESP8266 remains failing to find my PC in the same LAN.
Now I have succeeded to use AT command to connect ESP8266 to my Router AP. And I used XAMPP to open a gate on my PC whose address is 192.168.1.11:80, then use the following command (AT+CIPSTART=\"TCP\",\"192.168.1.11\",80") to successfully connect ESP8266 to it(It returned OK to my STM32F429).
Then I wanna replace XAMPP with my C# code to open a TCP server. But I couldn't make it!
As for the C# Code, I have successfully build a connection between two C# programs (The IP Address is 192.168.1.11:80 which is the same as the one mentioned above).But when I tried to use ESP8266 to connect to the same IP and Port, it failed.
I suspected that there might be some wrong conceptions I have got about opening a TCP Listener on certain port in my LAN... I don't know...
The following is my C# code. (The code of STM32 is just a basic Usart code which I won't present here.)
// Code for Server
namespace Tcp_Server
{
public partial class Form1 : Form
{
private TcpListener myListener;
private TcpClient newClient;
public BinaryReader br;
public BinaryWriter bw;
public Form1()
{
InitializeComponent();
Thread myThread = new Thread(ServerA);
myThread.Start();
}
private void ServerA()
{
IPAddress SvrIP = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); // Get the virtual IP of my PC.
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, ip.ToString() });
myListener = new TcpListener(ip, 80); //construct a Tcp Listener.
myListener.Start(); //Tcp Listener start
newClient = myListener.AcceptTcpClient();// Searching for a client...
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, "Connect Successfully" });
while (true)
{
try
{
NetworkStream clientStream = newClient.GetStream();
br = new BinaryReader(clientStream);
string receive = null;
receive = br.ReadString();//读取
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, receive });
}
catch
{
MessageBox.Show("Receving failed...");
}
}
}
// Code for client
namespace Client
{
public partial class Form1 : Form
{
private TcpClient client;
public BinaryReader br;
public BinaryWriter bw;
public Form1()
{
InitializeComponent();
Thread myThread = new Thread(ClientA);
myThread.Start();
}
private void ClientA()
{
IPAddress ip = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); // Get the virtual IP of my PC.
client = new TcpClient(ip.ToString(), 80);
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, "Connect to Server Successfully!" });
while (true)
{
try
{
NetworkStream clientStream = client.GetStream();
br = new BinaryReader(clientStream);
string receive = null;
receive = br.ReadString();
}
catch
{
MessageBox.Show("Receving failed...");
}
}
}
private void AddToTextbox(TextBox txt, String s)
{
txt.Text += s;
}
private delegate void AddToTextbox_dg(TextBox txt, String s);
private void btn_send_Click(object sender, EventArgs e)
{
NetworkStream clientStream = client.GetStream();
bw = new BinaryWriter(clientStream);
bw.Write(message.Text);
}
}
}
Could somebody please help me with this problem ?
I wonder why I cannot connect ESP8266 to the TcpListener I built on my PC with C#.
What did my PC do when receiving the command:
myListener = new TcpListener(ip, 80);
This project I'm doing is about to transmit the image data I got with Stm32F429 and OV7725 to my PC through ESP8266. I know Usart will be too slow to do that, but now I'm just trying to build the connection. Is there any suggestion you guys could give me about this?
First, make sure no other application on your pc is listening to port 80. if so, you have to change it.
Second, try setting the ip of the TCPListener to local host "127.0.0.1". you will be able to reach this server by connecting to the ip of your PC.
I have checked the used IP in command window as below:
Command Window for checking IP usage
And I remain the IP address which ESP8266 will try to access to be 192.168.1.11:1900 which is the virtual IP of my PC in the LAN as below:
Address ESP8266 try to access
And change the IP C# will try to create a TCPListener on:
C# code
Is this what you mean? Thank you.

C# TCP connecting to a computer

After some research I've almost managed to get a program to connect to another PC using TCP.
I've made 2 programs :
one to connect and
one to receive which goes on the other computer if that makes sense.
I'm not sure if I use my public IP address to connect but it doesn't work.
I'm not sure if its the program or the wrong IP.
So here is the code for the program that connects.
public static bool IsConnected;
public static NetworkStream Writer;
static void Main(string[] args)
{
Console.Title = "Offline";
TcpClient Connector = new TcpClient();
GetConnection:
Console.WriteLine("Enter server IP :");
string IP = Console.ReadLine();
try
{
Connector.Connect(IP, 2001);
IsConnected = true;
Console.Title = "Online";
Writer = Connector.GetStream();
}
catch
{
Console.WriteLine("Error connecting to target server! Press any key to try again.");
Console.ReadKey();
Console.Clear();
goto GetConnection;
}
Its a console application where I just type in the ip address and it tells me if its connected or not,
It uses port 2001 just like the receiver which the code for that is below.
public static NetworkStream Receiver;
[DllImport("kernel32.dll")]
static void Main(string[] args)
{
FreeConsole();
TcpListener l = new TcpListener (2001);
l.Start();
TcpClient Connection = l.AcceptTcpClient();
Receiver = Connection.GetStream();
}
If anyone has any ideas as to why it doesn't connect its appriciated
I was using the public ip address instead of the ipv4 address

Can't receive Broadcasts in WinRT

I'm trying to receive a broadcast via DatagramSockets in WinRT/C#, but I just don't receive a packet.
To be more specific, this is my code:
public sealed partial class MainPage : Page
{
public MainPage(){
this.InitializeComponent();
}
private DatagramSocket listener;
async private void Loaded(object sender, RoutedEventArgs e) {
listener = new DatagramSocket();
listener.MessageReceived += MessageReceived;
await listener.BindServiceNameAsync("50011");
}
private void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) {
txtText.Text = "Win :D:D:D:D:D:D:D"; //Breakpoint here
}
}
The program never reaches the breakpoint.
I've set all the correct rights/permissions in the appxmanifest.
The program which sends the broadcast is the following one:
static void Main(string[] args) {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 50011);
string hostname = Dns.GetHostName();
byte[] data = new byte[1];
data[0] = 129;
while (true) {
sock.SendTo(data, iep);
Console.WriteLine("Daten gesendet: {0}", data[0]);
Thread.Sleep(1000);
}
}
I know this program works, because I tested it with another little C# programm on the same PC (but not with WinRT functionality, just normal C#). Also it can't be a Firewall- or Routing Problem, because it, as I just mentioned, already worked with a normal C# program (but I already tried turning the firewall off).
I'm currently trying it on a Wifi-Network using Windows 8.1 and have x64 Processor.
Am I missing something? Is it even possible?
I hope somebody of you can help me
(PS: I know it's pretty similar to this post: Can't Receive UDP Windows RT but there hasen't been progress for more than a year so ...)
I solved it.
You just have to send the broadcasts from a different device.
However it doesn't like broadcasts sent from the same device ....

Cannot figure out how to get Socket to receive data C#

So what I am specifically trying to do is get a serial proxy going to pipe an arduino into Unity3d to run on linux. System.IO.Ports just doesn't work on linux with unity.
So I have gotten a python based serial proxy script, I have that up and running just fine. I can netcat into that localhost and actually get output from the arduino.
nc localhost 8082
g'day from bitty 1.0 -- type 'logout' to disconnect
Connecting to /dev/tty.usbmodem5d11... connected.
HELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLOHELLO
I have the arduino only printing out HELLO on repeat.
But the serial proxy is up and running, and has data going over it.
Now I am trying to write the code in Unity to receive this data, and I just can't get it to work.
This is my code for that:
public Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
public byte[] buffer = new byte[256];
int pinRead = 0;
void Start ()
{
socket.Connect(IPAddress.Parse("127.0.0.1"),8082);
}
void Update ()
{
if (socket.IsBound)
{
try
{
int bytesRead;
bytesRead = socket.Receive(buffer);
string incommingdata = System.Text.Encoding.ASCII.GetString(buffer);
Debug.Log(bytesRead+" || "+incommingdata);
}
catch (System.Exception e)
{
}
}
bytesRead is ALWAYS 0 and incomingData just doesn't have anything. It connects, and isBound returns true. I just can't get the code right to receive the data and put it in a format that is usable.
Please help. I need to get this working and its far out of my area of expertise. How do I make this work?
So I got this to work using tcpclient objects and some snippets of code that were posted on a random unity blog....
Here it is if anyone wants to see. I would still be really curious to know how to get the Socket implementation functioning though.
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;
using System.IO;
using System.Threading;
public class ArduinoTest : MonoBehaviour
{
private bool socketReady = false;
private TcpClient mySocket;
private NetworkStream theStream;
private StreamWriter theWriter;
private StreamReader theReader;
private string Host = "localhost";
private Int32 Port = 9900;
private int pinRead = 0;
void Start ()
{
setupSocket();
}
void Update ()
{
string read = readSocket();
if (read != "")
{
int value = int.Parse(read);
if ( value > 53)
{
Debug.Log((value-54)+" DOWN");
}
else
{
Debug.Log(value+" UP");
}
}
}
void OnApplicationQuit()
{
writeSocket("logout");
closeSocket();
}
public void setupSocket()
{
try
{
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e)
{
Debug.Log("Socket error:" + e);
}
}
public void writeSocket(string theLine)
{
if (!socketReady)
return;
String tmpString = theLine + "\r\n";
theWriter.Write(tmpString);
theWriter.Flush();
}
public string readSocket()
{
if (!socketReady)
return "";
if (theStream.DataAvailable)
return theReader.Read().ToString();
return "";
}
public void closeSocket()
{
if (!socketReady)
return;
theWriter.Close();
theReader.Close();
mySocket.Close();
socketReady = false;
}
public void maintainConnection()
{
if(!theStream.CanRead)
{
setupSocket();
}
}
}
(Sorry I can't post comments yet or would do so there)
BytesRead = 0 typically means the remote side disconnected.
For what it's worth, your code works fine when I run a test TCP server listening for connections on port 8082 and sending out some text messages. So I doubt the problem is on the C# client-side.
Beyond this simple example, "getting this to work" is not necessarily a simple question. Here are a couple things you should keep in mind:
You are making a blocking Receive call, which means you will need to call Update in a loop.
TCP is a streaming protocol, so you might get partial messages or many messages bundled together in the same Read call. Look up "TCP Framing" to get more details on this.
You can try using telnet on this socket, just to see if you can connect to it.
telnet 127.0.0.1 8082

>1 client can't connect to server in c#

I am creating a chat client in C# to be demonstrated on localhost.
Here's the relevant code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
static List<TcpListener> garabage_collection_preventor = new List<TcpListener>();
static Dictionary<IPEndPoint, bool> address_dictionary = new Dictionary<IPEndPoint, bool>();
static int port_increment = 9999;
static int client_id = 0;
void start_listening()
{
while (true)
{
TcpListener listen = new TcpListener(IPAddress.Any, port_increment);
garabage_collection_preventor.Add(listen);
listen.Start();
TcpClient client = listen.AcceptTcpClient();
IPEndPoint temp_end = ((IPEndPoint)listen.LocalEndpoint);
address_dictionary.Add(temp_end, false);
port_increment++;
new Thread(new ParameterizedThreadStart(connection_stuff)).Start(client);
}
}
void writer(object ob,int end_point)
{
StreamWriter write = ob as StreamWriter;
while (true)
{
foreach (KeyValuePair<IPEndPoint, bool> value in address_dictionary)
{
IPEndPoint index = value.Key;
int temp = value.Key.Port;
if (temp == end_point)
{
while (address_dictionary[index] == true)
{
write.WriteLine(msg_box.Text);
}
}
}
}
}
void reader(StreamReader read)
{
while (true)
{
MessageBox.Show(read.ReadLine());
}
}
void connection_stuff(object ob)
{
TcpClient client = ob as TcpClient;
int writer_identification_endpoint = ((IPEndPoint)client.Client.LocalEndPoint).Port;
NetworkStream stream = client.GetStream();
StreamReader read = new StreamReader(stream);
StreamWriter write = new StreamWriter(stream);
ThreadStart port_passing = delegate { writer(write, writer_identification_endpoint); };
Thread thread = new Thread(port_passing);
reader(read);
thread.Start();
}
public Form1()
{
InitializeComponent();
}
private void send_Click(object sender, EventArgs e)
{
int end_point = int.Parse(port.Text);
foreach (KeyValuePair<IPEndPoint, bool> value in address_dictionary)
{
IPEndPoint index = value.Key;
int temp = value.Key.Port;
if (temp == end_point)
{
address_dictionary[index] = true;
}
}
}
private void listener_Click(object sender, EventArgs e)
{
new Thread(start_listening).Start();
listener.Enabled = false;
}
}
}
Now the problem is that the first client can easily connect with the program and send messages which this program can easily read. However every subsequent client cannot connect.
I know that I shouldn't be making creating than one TCPListener but the problem is that I have to demonstrate the program on localhost and port number is the only true way to differentiate between client.
So please tell me what's wrong with the code I have been banging my head against the wall on it for hours.
EDIT
this is what happens when english is not a first language :) This code(not complete presently) will be a chat client. Each instance of this code will be able to connect with other instance of this same code to communicate. Any number of instances should be able to connect with any number of instances(like if double click 5 times the program there would now be 5 instances ready to communicate with each other).
Now the problem is that every instance will have the same IP Address(Because they are all running on the same machine). The question arises how say instance 1 suppose to connect to instance 4, ip can't be used here because instance 2,3 and 5 will also have the same IP address. So what i am trying to do is to connect instance 1 with instance 4 with IP Address and PORT instead of just using just the IP Address as is the case with a single TCPListener.
Try moving these three lines of code outside the while(true) loop in your start_listening routine.
TcpListener listen = new TcpListener(IPAddress.Any, port_increment);
garabage_collection_preventor.Add(listen);
listen.Start();
You only need one listener, from which you accept many different connections.
Try it like this:
void start_listening()
{
TcpListener listen = new TcpListener(IPAddress.Any, port_increment);
garabage_collection_preventor.Add(listen);
listen.Start();
while (true)
{
TcpClient client = listen.AcceptTcpClient();
// etc
}
}
That is, once you have created your listener, it runs in the loop accepting incoming connections from the client.
Edit: The problem you are having is because your simulation is flawed. In the real world, each chat server runs in a single O/S instance, on one, known, port number. Because you only have one O/S instance yourself, you can't run multiple chat servers on that instance all listening on the same port. But something like this might work, i.e., you need two loops, the first one to create your listeners, and the second inner loop for each listener to accept multiple clients. Note: these loops need exit conditions!
void start_listening()
{
while (true)
{
TcpListener listen = new TcpListener(IPAddress.Any, port_increment);
garabage_collection_preventor.Add(listen);
listen.Start();
while (true)
{
TcpClient client = listen.AcceptTcpClient();
IPEndPoint temp_end = ((IPEndPoint)listen.LocalEndpoint);
address_dictionary.Add(temp_end, false);
new Thread(new ParameterizedThreadStart(connection_stuff)).Start(client);
}
port_increment++;
}
}

Categories

Resources