I used to use a Java library for receiving SMS to my phone, which I then wrote to a text file to be picked up periodically by other programs. Obviously this is pretty terrible in practice due to file locks and other filesystem overheads. I was going to rewrite it to use a database but never got round to it until I needed to dig out the functionality again.
The project has moved on since then and I was determined to integrate SMS properly into my C# solution. First I tried using the built in serial port libraries of System.IO.Ports added in C# 2.0 and AT commands to talk to my Nokia 6310.
We decided on the 6310 as it is a reliable cheap phone with a GSM modem, required if you want to use AT commands to talk to it. The Java app I wrote originally used AT commands to read a list of messages at periodic intervals. Developers Home provided a great source of info on the required AT commands to read off all unread SMS messages which I then parsed elsewhere.
When I rewrote the Java app for C# I tried to use all the same AT commands but every time I tried I just got garbled text returned, even when I did everything completely in serial and added pauses for the com port to catch up (serialin is my com port instance):
serialIn.Write(“AT” + System.Environment.NewLine);
serialIn.WriteLine(“AT+CNMI=2,1,0,0,0″ + System.Environment.NewLine);
serialIn.WriteLine(“AT+CMGF=1″ + System.Environment.NewLine);
serialIn.WriteLine(“AT+CMGL=”all”” + System.Environment.NewLine);
For reference my serial port was set up to work with my 6310 using a DLR-3P cable I picked up off ebay for £5. The initialization of the port was as follows:
serialIn = new SerialPort();
serialIn.PortName = “COM1″;
serialIn.BaudRate = 2400;
serialIn.DataBits = 8;
serialIn.Parity = Parity.None;
serialIn.StopBits = StopBits.One;
serialIn.Handshake = Handshake.RequestToSend;
serialIn.DtrEnable = true;
serialIn.RtsEnable = true;
serialIn.NewLine = System.Environment.NewLine;
I was confused as to why I was getting back garbled text from the serial port as I had tried these exact same commands in HyperTerminal without any problems. I played around with timings and pauses but whatever I did it still didnt give me the correct SMS message readouts I expected.
Next I tried to find a working tutorial but nothing I did could get the port to send back the correct info as they all used a similar method of sending AT commands. I eventually gave up and found an open source library called SMSlib. This library is written for Java currently but they used to have a C# version, which I had to dig up at a Google Group dedicated to the project and you can download from here.
Although the C# version is depreciated, it works great and with a little bit of threading I integrated SMS receiving into my existing solution. I added the SMSlib project, made a reference to the project in my main project, added the “SMSLib.Service” object and followed the “ReadMessages” example included.