programming GSM modem in C# - c#

I have a usb gsm modem of type lightWave. I found this code in c# that can receive, send, delete and read sms message from this modem but when a new message arrives to modem, the event that should be raised when new message is received does not get raised. I don't know what the problem is; however, I can read this message from sim after received, but I want the event of received message raised when message arrive this part of code:
private void Form1_Load(object sender, EventArgs e)
{
int port = GsmCommMain.DefaultPortNumber;
int baudRate = 9600; // We Set 9600 as our Default Baud Rate
int timeout = GsmCommMain.DefaultTimeout;
dlg = new frmConnection();
dlg.StartPosition = FormStartPosition.CenterScreen;
dlg.SetData(port, baudRate, timeout);
if (dlg.ShowDialog(this) == DialogResult.OK)
{
dlg.GetData(out port, out baudRate, out timeout);
CommSetting.Comm_Port = port;
CommSetting.Comm_BaudRate = baudRate;
CommSetting.Comm_TimeOut = timeout;
}
else
{
Close();
return;
}
Cursor.Current = Cursors.WaitCursor;
CommSetting.comm = new GsmCommMain(port, baudRate, timeout);
Cursor.Current = Cursors.Default;
CommSetting.comm.PhoneConnected += new EventHandler(comm_PhoneConnected);
CommSetting.comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
//....
}
This event does not get raised when message
CommSetting.comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
This code in C# I founded at codeproject.com can any help me please?

+CMTI
A GSM/GPRS modem or mobile phone uses +CMTI to notify the computer / PC that a new SMS message has been received and the memory location where it is stored.
keep on run the thread at event handle DataReceivedHandler,
if(indata.Contains("+CMTI"))//Alert for message recived read message from the loacation
Get the loaction and read the message from that specfic sim location.
ref http://www.developershome.com/sms/resultCodes3.asp
ref http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx

first of all you have to make sure that your port, baudRate and time out is valid. And then check comm is properly initialized.
to add handler write the following code only......
comm.MessageReceived += comm_MessageReceived;
and initialize comm by following code.......
comm = new GsmCommMain(port, baudRate, timeout);

Related

How to receive more messages from Serial Port c#

I am using System.IO.Ports.
I send messages to device and want to wait for all messages from it.
I am trying do it like this:
message = Console.ReadLine();
_serialPort.Write(message);
Console.WriteLine(_serialPort.ReadExisting());
But it returns only the first line.
I have tried using port.BytesToRead, but I get the same results.
When I use ReadLine() it doesn't return anything.
Edit:
To see all line use Event handler.
Solution for my problem is use \r (enter) on the end line.
ReadExisting return the available bytes available at the exacte time, put a delay befor you read the buffer, a work around would be
message = Console.ReadLine();
_serialPort.Write(message);
Thread.Sleep(200);
Console.WriteLine(_serialPort.ReadExisting());
Edit 2 :
here is how i do it on my projects
private SerialPort port;
string DataReceived = string.Empty;
public string OpenPort(string PortName, int BaudRate)
{
// if the port is already used by other window then return the same instance
if (port != null)
if(port.IsOpen)
return "True";
port = new SerialPort(PortName, BaudRate, Parity.None, 8, StopBits.One);
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
try
{
port.Open();
}
catch(Exception ex)
{
return ex.Message;
}
return "True";
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.sleep(200);
DataReceived = port.ReadExisting();
}
in your main
message = Console.ReadLine();
_serialPort.Write(message);
//use Stopwatch to calculate time befor you can exit from the loop
while(true)
{
if(!string.IsNullOrWhiteSpace(DataReceived))
break;
// Todo : Check stopwatch for timeout
}
Maybe you have a new line issue expected from your serial device try:
message = Console.ReadLine();
_serialPort.WriteLine(message);
Console.WriteLine(_serialPort.ReadExisting()); # try debug here replace with string test = _serialPort.ReadLine();

C# - SerialPort.ReadLine() freezes my program

I'm trying to read messages sent form my Arduino over a Serial port using baud rate 9600.
My Arduino code is programmed to send a "1" whenever I press a button and a "0" when I release my finger off the button.
So it's not constantly sending data.
My C# Program is to read that message and add it to a ListBox. But whenever I start it, the program hangs.
private void button1_Click(object sender, EventArgs e)
{
SerialPort port = new SerialPort();
port.BaudRate = 9600;
port.PortName = "COM4";
port.ReadTimeout = 1000;
port.Open();
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
try
{
ee = port.ReadLine();
listBox1.Items.Add(ee);
}
catch (Exception)
{
timer1.Stop();
}
}
I guess, maybe the reason is that my program should check if there's data available to be received before receiving?
Try something like this instead. It will at least not hang, and then you can sort out what sort of data your are getting via DataReceived
From there you can determine how to better write your app
private void button1_Click(object sender, EventArgs e)
{
SerialPort port = new SerialPort();
port.BaudRate = 9600;
port.PortName = "COM4";
port.ReadTimeout = 1000;
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer in the output window
Debug.WriteLine("data : " + port.ReadExisting());
}
SerialPort.DataReceived Event
Indicates that data has been received through a port represented by
the SerialPort object.
SerialPort.ReadExisting Method ()
Reads all immediately available bytes, based on the encoding, in both
the stream and the input buffer of the SerialPort object.
To avoid this problem, you need to add "\n" to your data in your arduino because
port.ReadLine(); search for ending line ("\n")
For example, let's say that the data which arduino sends is "1", to read this data with port.ReadLine(); it should be "1\n"
Also, do not worry, port.ReadLine(); doesn't read "\n". Just stops there when it sees "\n".
I hope it helps.

unable to communicate with obd-II

I am trying to communicate with ECUsim 2000 which is OBD-ll ECU simulator (link). Yet, responses I always receive from device are something like "??" or "?" (when I run programs like TouchScan or OBD Auto Doctor, they successfully reads data so device is working properly). I am sending comand in C# via
serialPort1.Write("010D\r")
and I am receiving signal in SerialPort's DataReceived event as
message = "Data Received: " + serialPort1.ReadExisting();
this.Invoke(new EventHandler(displayText));
I do not now what I am missing. Here is the full source code
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 115200;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.DataBits = 8;
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.Open();
}
private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("010D\r");
}
}
private void displayText(object sender, EventArgs e)
{
textBox1.AppendText(message + "\n");
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
message = "Data Received: " + serialPort1.ReadExisting();
this.Invoke(new EventHandler(displayText));
}
Default communication settings of ECUsim 2000 are
Baud Rate: 115200
Data bits: 8
Parity: none
Stop bits:1
protocol is ISO 15765-4 and there are two switches on the device which are protocol attribute CAN ID 29/11 bit and CAN Baud Rate 500 kbps/250kbps. Maybe, the problem are related with these such that there is no proper communication set.
Another question -> Is there a way to set protocol (like ISO 15765-4) in serial communication?
There are two problems related with the code given.
1) There are two connector on the ECUsim 2000. One of them is type B USB port, other one is Diagnostic Link Connector (DLC). If one wants to get connected to device via type B USB port, baud rate is: 115200. If DLC is used, Baud Rate is most probably either 9600 or 38400. Here, connection is made through scan tool, therefore (for my case) baud rate 38400 worked for me.
2) As mentioned in the comment, In order to get data, Read() method of SerialPort must be used. It can be used as the following code:
int buffSize = 1024;
bool cont = true;
int count = 0;
byte[] bff = new byte[buffSize];
string returnVal = string.Empty;
count = serialPort1.Read(bff, 0, buffSize);
returnVal += System.Text.Encoding.Default.GetString(bff, 0, count);

SerialPort First Command OK. Second Command Error

I'm writing a serialport app to talk to a Bluetooth module over serial port. The first At command I send to the device runs fine and I get a response of the module version. All subsequent commands fail with a response of ERROR.
Part of the code is here:
namespace PhoneApp
{
public partial class Form1 : Form
{
//SerialPort myport = OPenPort.OpenIt();
SerialPort myport = new SerialPort();
public Form1()
{
InitializeComponent();
myport.PortName = "COM3";
myport.BaudRate = 115200;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.NewLine = System.Environment.NewLine;
myport.ReadTimeout = 500;
myport.WriteTimeout = 500;
myport.DtrEnable = false;
myport.RtsEnable = false;
myport.WriteBufferSize = 4096;
myport.ReadBufferSize = 4096;
myport.Handshake = Handshake.None;
myport.Encoding = System.Text.Encoding.ASCII;
if (!myport.IsOpen)
{
myport.Open();
}
calling.Visible = false;
myport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
mycommand.Text = #"AT+BGVER";
the button which sends the command. The device requires a newline after each comand.
private void button2_Click(object sender, EventArgs e)
{
try
{
myport.WriteLine(mycommand.Text.Trim());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Not sure what I'm missing here.
Thanks for the replies. i found the problem. In fact I had to use myport.Write instead of myport.WriteLine. I deleted the line myport.NewLine and I appended "\r" to every command. Now the device responds as expected. As for DTR and RTS they are not required by the device according to the vendor
Not sure if this solves your problem, but I noticed that you don't have flow control enabled (e.g. myport.RtsEnable = false; myport.DtrEnable = false;).
Have you checked the documentation to make sure that the Bluetooth module doesn't require it? Typically devices with 115kbps and higher need flow control.
Another thing to check is the NewLine constant. You set it to the sys default which is likely Cr+Lf. Make sure that the module expects that.

Using SerialPort class to read response from connected device

I'm using C#'s SerialPort class to try and send a AT command to a device and get a response back. I've verified it works correctly in HyperTerminal, if I send a command of AT it responds back with OK. However, in my console app, if I send AT, it replies back with an echo AT. The code is below, any insight into what I'm doing wrong in my receiving code would be greatly appreciated:
ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived);
public void Open()
{
Console.WriteLine();
//close port if already open.
if (ComPort.IsOpen)
{
ComPort.Close();
}
//setup port.
ComPort.PortName = ConfigurationManager.AppSettings["PortName"].ToString();
ComPort.BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]);
ComPort.Parity = Parity.None;
ComPort.StopBits = StopBits.One;
ComPort.DataBits = 8;
ComPort.DtrEnable = true;
ComPort.RtsEnable = true;
if (Convert.ToBoolean(ConfigurationManager.AppSettings["HWFlowControlEnabled"]))
{
ComPort.Handshake = Handshake.RequestToSend;
}
//open port.
Console.WriteLine("Opening port " + ComPort.PortName + "...");
ComPort.Open();
Console.WriteLine("Opened port " + ComPort.PortName);
}
void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string message = ComPort.ReadExisting();
Console.WriteLine("RECEIVED: " + message);
if (message.IndexOf("OK") > -1)
{
ReceivedOK = true;
}
}
I think the default is to echo your commands back to you, then the OK. Send an ATE0 first to turn off echo:
http://tigger.cc.uic.edu/depts/accc/network/dialin/modem_codes.html
By default, the device (a modem I guess) is configured to echo all communication back. There are AT commands to turn echo on and off. Also, several hardware signalling approaches exist to control the flow of data. Have a look here for a basic overview.
It's quite a while (> 10 years actually) since I was doing modem communications, so I'm sorry in case my answer isn't 100% precise.

Categories