i have a problem with rs232 and Eurotherme 2208e this is the code without problem.
public Window8()
{
InitializeComponent();
DispatcherTimer myDispatcherTimer = new DispatcherTimer();
myDispatcherTimer.Interval = new TimeSpan(0, 0, 1); // 100 Milliseconds
myDispatcherTimer.Tick += myDispatcherTimer_Tick;
myDispatcherTimer.Start();
}
void myDispatcherTimer_Tick(object sender, EventArgs e)
{
textBlock1.Text = DateTime.Now.ToString("HH:mm:ss");
}
public void port_DataReceived(object o, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
time_out.Stop();
msg_recu += port.ReadExisting();
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new recevoir_del(recevoir), oven_index);
}catch(UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message,"",MessageBoxButton.OK,MessageBoxImage.Error);
}
}
public delegate void ask_mesure_del(four oven);
public void ask_mesure(four new_etuve)
{
try{
msg_recu = "";
if (new_etuve.regulateur=="EUROTHERM") {
port.StopBits = StopBits.One;
demande_pv_E[1] = demande_pv_E[2] = (byte)new_etuve.gid.ToString().ElementAt(0);
demande_pv_E[3] = demande_pv_E[4] = (byte)new_etuve.uid.ToString().ElementAt(0);
port.Write(demande_pv_E, 0, demande_pv_E.Length);
}
time_out.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "askmesure", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
this is the call instruction :
Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Send, new ask_mesure_del(ask_mesure), Oven_Class.list_Oven.ElementAt(oven_index));
when i add this bloc to function ask_mesure :
public delegate void ask_mesure_del(four oven);
public void ask_mesure(four new_etuve)
{
try{
msg_recu = "";
if (new_etuve.regulateur=="EUROTHERM") {
port.StopBits = StopBits.One;
demande_pv_E[1] = demande_pv_E[2] = (byte)new_etuve.gid.ToString().ElementAt(0);
demande_pv_E[3] = demande_pv_E[4] = (byte)new_etuve.uid.ToString().ElementAt(0);
port.Write(demande_pv_E, 0, demande_pv_E.Length);
}
if(flago == 1){
port.StopBits = StopBits.One;
ecriture_sl_h_E[1] = ecriture_sl_h_E[2] = (byte)new_etuve.gid.ToString().ElementAt(0);
ecriture_sl_h_E[3] = ecriture_sl_h_E[4] = (byte)new_etuve.uid.ToString().ElementAt(0);
for (int i = 0; i < new_etuve.consigne.ToString().Length; i++)
{
ecriture_sl_h_E[10 - i] = (byte)new_etuve.consigne.ToString().ElementAt(new_etuve.consigne.ToString().Length - 1 - i);
}
ecriture_sl_h_E[ecriture_sl_h_E.Length - 1] = bcc(ecriture_sl_h_E);
port.Write(ecriture_sl_h_E, 0, ecriture_sl_h_E.Length);
}
time_out.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "askmesure", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
the port communicate 2 minute and after there is a connection failure 3 minute and connection returns
You may capture your communications to a file using any port monitoring software like Advanced Serial Port Monitor and see the last data packet. It is possible it will help you to diagnose the problem.
Then you may re-send the specific data packet to your program and debug it step-by-step.
Related
I have to use Bulgarian language to send SMS and I use thic project that works fine if you need to send English SMS (https://www.codeproject.com/Articles/38705/Send-and-Read-SMS-through-a-GSM-Modem-using-AT-Com).
So I open Srrial port like
public SerialPort OpenPort(string p_strPortName, int p_uBaudRate, int p_uDataBits, int p_uReadTimeout, int p_uWriteTimeout)
{
receiveNow = new AutoResetEvent(false);
SerialPort port = new SerialPort();
try
{
port.PortName = p_strPortName; //COM1
port.BaudRate = p_uBaudRate; //9600
port.DataBits = p_uDataBits; //8
port.StopBits = StopBits.One; //1
port.Parity = Parity.None; //None
port.ReadTimeout = p_uReadTimeout; //300
port.WriteTimeout = p_uWriteTimeout; //300
port.Encoding = Encoding.GetEncoding("windows-1251");
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.DtrEnable = true;
port.RtsEnable = true;
}
catch (Exception ex)
{
throw ex;
}
return port;
}
I send SMS text that comes from MS SQL Server (nvarchar) like
public bool sendMsg(SerialPort port, string PhoneNo, string Message)
{
bool isSend = false;
try
{
string recievedData = ExecCommand(port,"AT", 300, "No phone connected");
recievedData = ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.");
String command = "AT+CMGS=\"" + PhoneNo + "\"";
recievedData = ExecCommand(port,command, 300, "Failed to accept phoneNo");
command = Message + char.ConvertFromUtf32(26) + "\r";
recievedData = ExecCommand(port,command, 3000, "Failed to send message"); //3 seconds
if (recievedData.EndsWith("\r\nOK\r\n"))
{
isSend = true;
}
else if (recievedData.Contains("ERROR"))
{
isSend = false;
}
return isSend;
}
catch (Exception ex)
{
throw ex;
}
}
//Execute AT Command
public string ExecCommand(SerialPort port,string command, int responseTimeout, string errorMessage)
{
try
{
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
}
catch (Exception ex)
{
throw ex;
}
}
But I cannot see normal text it looks like abrakadabra with ?????? and so on.
Please help me encoding text properly so I get redable SMS.
Thank you!
------- Extra Code to clarify the issue -----------------------------------------
public string ReadResponse(SerialPort port,int timeout)
{
string buffer = string.Empty;
try
{
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
}
catch (Exception ex)
{
throw ex;
}
return buffer;
}
public AutoResetEvent receiveNow;
//Receive data from port
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (e.EventType == SerialData.Chars)
{
receiveNow.Set();
}
}
catch (Exception ex)
{
throw ex;
}
}
I found best answer posible to implement ASAP.
https://github.com/welly87/GSMComm
GsmCommMain comm=new GsmCommMain(/*Set your option here*/);
string txtMessage="your long message...";
string txtDestinationNumbers="your destination number";
//select unicode option by a checkBox or any other control
bool unicode = chkUnicode.Checked;
SmsSubmitPdu[] pdu = SmartMessageFactory.CreateConcatTextMessage(txtMessage, unicode, txtDestinationNumbers);
сomm.SendMessages(pdu);
How to concat long SMS in GSMComm Library?
I am creating a Windows Form application, where it is connecting to a device through bluetooth. I am able to send commands to the device and I am receiving the data continuously. The problem I am facing is that I am not able to show the continuous data in the text box. The text box only shows the first line of characters the application is receiving. Here is my code:
CONNECT BUTTON ACTION:
private void btnConnect_Click(object sender, EventArgs e)
{
if (listBox.SelectedItem != null)
{
lblProgress.Text = "";
btnStart.Enabled = true;
cBoxAvailablePorts.Enabled = cBoxAvailableBaudRates.Enabled = true;
try
{
int pos = listBox.SelectedIndex;
deviceInfo = array.ElementAt(pos);
if (pairDevice())
{
Thread thread = new Thread(() => connectThread());
thread.Start();
}
else
{
MessageBox.Show("Pair failed!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
else
{
MessageBox.Show("Please connect to a device!");
}
}
THREAD ACTION
private void connectThread()
{
//BluetoothClient client = new BluetoothClient();
bc.BeginConnect(deviceInfo.DeviceAddress, serviceClass, this.connectCallBack, bc);
}
CALLBACK ACTION:
private void connectCallBack(IAsyncResult result)
{
//BluetoothClient client = (BluetoothClient)result.AsyncState;
try
{
if (bc.Connected)
{
MessageBox.Show("Connected!");
}
else
{
MessageBox.Show("Connection Failed!");
}
}
catch (Exception)
{
MessageBox.Show("Not able to identify Bluetooth devices! Please try again.!");
}
}
START BUTTON ACTION:
Here I send a command "S".
In button action I call sendMessage("S").
The function that is called is shown below:
public void sendMessage(string msg)
{
try
{
if (bc.Connected)
{
Stream stream = bc.GetStream();
stream.ReadTimeout = 1000;
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.WriteLine(msg);
streamWriter.Flush();
// Read operation
StreamReader streamReader = new StreamReader(stream);
string result = streamReader.ReadLine();
txtResult.Text = result;
}
else
{
MessageBox.Show("Sending failed!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
I wrote the StreamReader part in a loop, and it gave me Socket Exception.
I also tried to get the data from Serial Port and used DataReceived event just in case, but still it didn't help.
Any help would be appreciated.
Thank you!
OKAY! I solved the problem. Without getting in trouble with 32feet library (though it is fun to code with 32feet), I thought to make communication through serial port. I connected the device with my laptop and got to know the outgoing COMPORT in bluetooth setting of my laptop. The two-way communication can only be done through outgoing COMPORT, not the incoming COMPORT.
Suppose the outgoing COMPORT is COM12 and the baud rate that I have set is 9600.
So here is my code:
public delegate void updateDelegate(string text);
private updateDelegate objDelegate;
private SerialPort serialPort;
public View() // constructor
{
InitializeComponent();
this.WindowState = FormWindowState.Normal;
this.StartPosition = FormStartPosition.CenterScreen;
this.objDelegate = new updateDelegate(getText);
serialPort = new SerialPort("COM12", 9600);
serialPort.Handshake = Handshake.None;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
}
START BUTTON ACTION
private void btnStart_Click(object sender, EventArgs e)
{
sendData("S");
}
// SEND COMMAND
public void sendData(string msg)
{
try
{
if (!serialPort.IsOpen)
{
serialPort.Open();
//serialPort.Close();
}
if (serialPort.IsOpen)
{
serialPort.Write(msg);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// READ DATA
public void readData()
{
try
{
serialPort.DataReceived += SerialPort_DataReceived;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string res = serialPort.ReadExisting();
Thread.Sleep(500);
txtResult.Invoke(this.objDelegate, new object[] {res});
}
public void getText(string text)
{
txtResult.Text = text;
}
I hope this will help someone! Thank you!!!
Hi i am using C# to get data from com port. With using Hercules to check data, see this image to compare config:
In Hescules data show with format: FF??ZZ, but in C#, date get only : FF
Here is C# code:
SerialPort _serialPort;
public Form1()
{
InitializeComponent();
//ShowNetworkInterfaces();
getDataFromComPort();
}
private void getDataFromComPort()
{
try
{
_serialPort = new SerialPort("COM3");
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
//_serialPort.StopBits = StopBits.One;
_serialPort.DataBits = 8;
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.NewLine = "\n";
//serialPort1.ReceivedBytesThreshold = 9;
//serialPort1.RtsEnable = true;
//serialPort1.DtrEnable = true;
//_serialPort.ReadTimeout = 500;
//_serialPort.WriteTimeout = 500;
if (_serialPort.IsOpen)
{
_serialPort.Close();
}
_serialPort.Open();
}
catch (Exception e)
{
Console.WriteLine("error : " + e.Message);
}
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (tbText.InvokeRequired)
{
tbText.Invoke(new SerialDataReceivedEventHandler(sp_DataReceived), sender, e);
}
else
{
try
{
string data = _serialPort.ReadLine();
Console.WriteLine("data: " + data);
tbText.Text = data;
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
}
}
It's seem the data is not read by line..
I've got an intra-PC communication server / client set up to send and receive data from one program to another - in this case, a custom server that is listening to text commands and Unity3D.
For the most part, it works, however every once in awhile, it will drop packets, and Unity will not get them without multiple attempts. The packets seem to be sent but lost, as I do see the "Sent message" console log. The following is the code for the server and client:
SERVER:
class TCPGameServer
{
public event EventHandler Error;
public Action<Data> ADelegate;
TcpListener TCPListener;
TcpClient TCPClient;
Client ActiveClient;
NetworkStream networkStream;
StreamWriter returnWriter;
StreamReader streamReader;
Timer SystemTimer = new Timer();
Timer PingTimer = new Timer();
int Port = 8637;
public TCPGameServer()
{
TCPListener = new TcpListener(IPAddress.Loopback, Port);
SystemTimer.Elapsed += StreamTimer_Tick;
SystemTimer.AutoReset = true;
SystemTimer.Interval = 2000;
PingTimer.Elapsed += PingTimer_Tick;
PingTimer.AutoReset = true;
PingTimer.Interval = 30000;
}
public void OpenListener()
{
TCPListener.Start();
TCPListener.BeginAcceptTcpClient(AcceptTCPCallBack, null);
Console.WriteLine("Network Open.");
}
public void GameLogout()
{
SystemTimer.AutoReset = false;
SystemTimer.Stop();
PingTimer.AutoReset = false;
PingTimer.Stop();
ActiveClient = null;
returnWriter.Dispose();
streamReader.Dispose();
Console.WriteLine("The client has logged out successfully.");
}
private void AcceptTCPCallBack(IAsyncResult asyncResult)
{
TCPClient = null;
ActiveClient = null;
returnWriter = null;
streamReader = null;
try
{
TCPClient = TCPListener.EndAcceptTcpClient(asyncResult);
TCPListener.BeginAcceptTcpClient(AcceptTCPCallBack, null);
ActiveClient = new Client(TCPClient);
networkStream = ActiveClient.NetworkStream;
returnWriter = new StreamWriter(TCPClient.GetStream());
streamReader = new StreamReader(TCPClient.GetStream());
Console.WriteLine("Client Connected Successfully.");
Data Packet = new Data();
Packet.cmdCommand = Command.Login;
Packet.strName = "Server";
Packet.strMessage = "LOGGEDIN";
SendMessage(Packet);
SystemTimer.AutoReset = true;
SystemTimer.Enabled = true;
SystemTimer.Start();
Ping();
PingTimer.AutoReset = true;
PingTimer.Enabled = true;
PingTimer.Start();
} catch (Exception ex)
{
OnError(TCPListener, ex);
return;
}
}
private void StreamTimer_Tick(object source, System.Timers.ElapsedEventArgs e)
{
CheckStream();
}
private void PingTimer_Tick(object source, System.Timers.ElapsedEventArgs e)
{
Ping();
}
private void Ping()
{
if (TCPClient.Connected)
{
Data Packet = new Data();
Packet.cmdCommand = Command.Ping;
Packet.strName = "Server";
Packet.strMessage = "PING";
SendMessage(Packet);
}
}
public void CheckStream()
{
try
{
if (TCPClient.Available > 0 || streamReader.Peek() >= 0)
{
string PacketString = streamReader.ReadLine();
Data packet = JsonConvert.DeserializeObject<Data>(PacketString);
switch (packet.cmdCommand)
{
case Command.Logout:
GameLogout();
break;
case Command.Message:
if (ADelegate != null)
{
ADelegate(packet);
}
break;
case Command.Ping:
Console.WriteLine("PONG!");
break;
}
}
} catch (IOException e)
{
Console.WriteLine(e.Message);
} catch (NullReferenceException e)
{
Console.WriteLine(e.Message);
}
}
public void SendMessage(Data packet)
{
if (ActiveClient != null)
{
string packetMessage = JsonConvert.SerializeObject(packet);
returnWriter.WriteLine(packetMessage);
returnWriter.Flush();
}
}
public void OnError(object sender, Exception ex)
{
EventHandler handler = Error;
if (handler != null)
{
ErrorEventArgs e = new ErrorEventArgs(ex);
handler(sender, e);
}
}
public void RegisterActionDelegate(Action<Data> RegisterDelegate)
{
ADelegate += RegisterDelegate;
}
public void UnRegisterActionDelegate(Action<Data> UnregisterDelegate)
{
ADelegate -= UnregisterDelegate;
}
}
CLIENT:
public class TCPNetworkClient
{
public Action<Data> PacketDelegate;
public TcpClient TCPClient;
int Port = 8637;
StreamReader streamReader;
StreamWriter streamWriter;
Timer StreamTimer = new Timer();
public bool LoggedIn = false;
public void Start()
{
if (LoggedIn == false)
{
TCPClient = null;
StreamTimer.AutoReset = true;
StreamTimer.Interval = 2000;
StreamTimer.Elapsed += StreamTimer_Tick;
try
{
TCPClient = new TcpClient("127.0.0.1", Port);
streamReader = new StreamReader(TCPClient.GetStream());
streamWriter = new StreamWriter(TCPClient.GetStream());
StreamTimer.Enabled = true;
StreamTimer.Start();
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
}
private void StreamTimer_Tick(System.Object source, System.Timers.ElapsedEventArgs e)
{
if (TCPClient.Available > 0 || streamReader.Peek() >= 0)
{
string PacketString = streamReader.ReadLine();
Data packet = JsonConvert.DeserializeObject<Data>(PacketString);
PacketDelegate(packet);
}
}
public void Logout()
{
Data Packet = new Data();
Packet.cmdCommand = Command.Logout;
Packet.strMessage = "LOGOUT";
Packet.strName = "Game";
SendMessage(Packet);
if (streamReader != null && streamWriter != null)
{
streamReader.Dispose();
streamWriter.Dispose();
TCPClient.Close();
TCPClient = null;
streamReader = null;
streamWriter = null;
}
StreamTimer.Stop();
}
public void SendMessage(Data packet)
{
string packetMessage = JsonConvert.SerializeObject(packet);
try
{
streamWriter.WriteLine(packetMessage);
streamWriter.Flush();
} catch (Exception e)
{
}
}
public void RegisterActionDelegate(Action<Data> RegisterDelegate)
{
PacketDelegate += RegisterDelegate;
}
public void UnRegisterActionDelegate(Action<Data> UnregisterDelegate)
{
PacketDelegate -= UnregisterDelegate;
}
}
I'm not really sure what's going on, or if there are any more additional checks that I need to add into the system. Note: It's TCP so that "when" this fully works, I can drop the client into other programs that I might write that may not fully rely or use Unity.
new TcpClient("127.0.0.1", Port) is not appropriate for the client. Just use TcpClient(). There is no need to specify IP and port, both of which will end up being wrong.
TCPClient.Available is almost always a bug. You seem to assume that TCP is packet based. You can't test whether a full message is incoming or not. TCP only offers a boundaryless stream of bytes. Therefore, this Available check does not tell you if a whole line is available. Also, there could be multiple lines. The correct way to read is to have a reading loop always running and simply reading lines without checking. Any line that arrives will be processed that way. No need for timers etc.
The server has the same problems.
Issue (2) might have caused the appearance of lost packets somehow. You need to fix this in any case.
I wrote a message last week but would like to add another more simple question again to clarify.
I have a serial port console application. There are 20 virtual ports. My application successfully working but doesnt change received data value until I restart the application. I am not sure why it happens.
This issue appeared after FIFO enabled property was set to true.
How can i refresh serial port?
Thanks
--- here is the codes :
static void serialportinstances()
{
for (int ix =1; ix < 20; ix++)
{
if (sportlar.ContainsValue("COM"+ix.ToString()) ==false)
{
try
{
SerialPort ekle = new SerialPort("COM" + ix.ToString(), 1200, Parity.None, 8, StopBits.One);
//ekle.DtrEnable = true;
//ekle.RtsEnable = true;
try
{
ekle.NewLine = "\r";
ekle.Open();
ekle.DataReceived += new SerialDataReceivedEventHandler(datareceived);
Console.WriteLine(String.Format("Dinamik SP {0} başarıyla açıldı", ekle.PortName));
}
catch (Exception eu)
{
Console.WriteLine(String.Format("Dynamic SP {0} açılamadı!", ekle.PortName));
}
sportlar.Add(ekle, "COM" + ix.ToString());
}
catch (Exception ee)
{
Console.WriteLine("port could not be created");
}
}
}
}
and datareceiving handler ;
static void datareceived(object sender, SerialDataReceivedEventArgs e)
{
lock (mylockobject)
{
SerialPort spn = (SerialPort)sender;
try
{
string s = spn.ReadLine();
GetWeightPWI(spn.PortName, s);
Thread.Sleep(1);
}
catch (Exception ee)
{
Console.WriteLine("error : " + ee.ToString());
}
}
}
and parsing the received data here :
private static void GetWeightPWI(string portadi, string alinan)
{
Console.WriteLine("PORT NAME : "+portadi+" and received data : "+alinan.toString());
}