How to get acknowledgement after sending sms successfully? - vb.net

In my VB.Net Application, I have done with SMS sending using modem (dongle) as well as mobile phone connected to it.
I have done this using AT commands..
I need to show acknowledgement / response on the screen after sending the sms.
How can i do this ?
Some Code Snippet :
If IsOpen = True Then
SMSPort.Write("AT" & vbCr)
SMSPort.Write("AT+CSCS=""GSM""" & vbCr)
SMSPort.Write("AT+CMGF=1" & vbCr)
SMSPort.Write("AT+CMGS=""+91" & CellNumber & """" & vbCr)
_ContSMS = False
SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
_Continue = False
RaiseEvent Sending(False)
End If

-you need to make a recieve data event;
Imports System
Imports System.IO.Ports
Class PortDataReceived
Public Shared Sub Main()
Dim mySerialPort As New SerialPort("COM1")
mySerialPort.BaudRate = 9600
mySerialPort.Parity = Parity.None
mySerialPort.StopBits = StopBits.One
mySerialPort.DataBits = 8
mySerialPort.Handshake = Handshake.None
AddHandler mySerialPort.DataReceived, AddressOf DataReceivedHandler
mySerialPort.Open()
Console.WriteLine("Press any key to continue...")
Console.WriteLine()
Console.ReadKey()
mySerialPort.Close()
End Sub
Private Shared Sub DataReceivedHandler(
sender As Object,
e As SerialDataReceivedEventArgs)
Dim sp As SerialPort = CType(sender, SerialPort)
Dim indata As String = sp.ReadExisting()
Console.WriteLine("Data Received:")
Console.Write(indata)
End Sub
End Class
And then you need to figure out how to get a acknowledgement with your provider and hardware.

Related

My Program Freezes when sending a message using gsm shield VB.net

My program is hangs when sending a messsage my code show no error and when i am testing my gsm shield in hyperterminal i can send message and recieve it through my phone using AT commands. But in my program it just freezes.
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM4")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 9600
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CSCA="" +639170000130""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS= + TextBox1.text + " & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("+ TextBox1.text +" & vbCrLf & Chr(26)) 'SMS sending
MessageBox.Show(":send")
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not SMSPort.IsOpen Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen Then
SMSPort.Close()
End If
End Sub
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
If Not BackgroundWorker1.IsBusy Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CSCA="" +639170000130""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS= + TextBox1.text + " & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("+ TextBox1.text +" & vbCrLf & Chr(26)) 'SMS sending
MessageBox.Show(":send")
SMSPort.Close()
End If
End Sub

I cannot access listbox from another thread and invoke is not required in vb.net

I hope somebody can help me. I am trying to access a listbox from another thread and the rare thing is that invokerequired is giving me "false", it suppose to be able to access it directly but nothing happens, the item is not added to the listbox.
Here is my code and thanks in advance:
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Public Class FrmTCPServer
Dim fn, temp_file, str_rute, str_filename, str_content, file_name, clNo, NewText As String
Dim file_len, recfilelen, counter As Integer
Dim serverSocket As New TcpListener(IPAddress.Any, 9088)
Dim clientSocket As TcpClient
Public thread As Thread = Nothing
Private Sub FrmServer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Lbconn.Items.Clear()
Dim IPHost As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName)
lblStatus.Text = "My IP address is " + IPHost.AddressList(1).ToString()
End Sub
Private Sub Btnstart_Click(sender As Object, e As EventArgs) Handles Btnstart.Click
serverSocket.Start()
ThreadProcSafe("Server Started")
thread = New Thread(New ThreadStart(AddressOf listenerThread))
thread.Start()
End Sub
Private Sub listenerThread()
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
ThreadProcSafe("Client No: " & Convert.ToString(counter) & " IP: " & (IPAddress.Parse(CType(clientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString() & " Started!")
Dim client1 As New FrmTCPServer
client1.startClient(clientSocket, Convert.ToString(counter))
End While
End Sub
Public Sub startClient(ByVal clientSocket As TcpClient, ByVal counter As Integer)
thread = New Thread(New ThreadStart(AddressOf handlerThread))
thread.Start()
End Sub
Private Sub handlerThread()
ThreadProcSafe("Receiving File... ")
End Sub
Sub ThreadProcSafe(item As Object)
If Lbconn.InvokeRequired Then
Lbconn.Invoke(Sub() Lbconn.Items.Add(item & " (Invoke)"))
Else
Lbconn.Items.Add(item & " (No Invoke)") '**Here pass whith no exception but does not add the item to the listbox**
End If
End Sub
End Class
In listenerThread method:
Private Sub listenerThread()
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
ThreadProcSafe("Client No: " & Convert.ToString(counter) & " IP: " & (IPAddress.Parse(CType(clientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString() & " Started!")
Dim client1 As New FrmTCPServer ' *** THIS PLACE ***
client1.startClient(clientSocket, Convert.ToString(counter))
End While
End Sub
You create new FrmTCPServer form and then call startClient on new object. So you data add in new list no this form which is running!
You should change listenerThread method to this:
Private Sub listenerThread()
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
ThreadProcSafe("Client No: " & Convert.ToString(counter) & " IP: " & (IPAddress.Parse(CType(clientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString() & " Started!")
Me.startClient(clientSocket, Convert.ToString(counter))
End While
End Sub
Change ThreadProcSafe method to below codes and try again:
Sub ThreadProcSafe(item As Object)
If Lbconn.InvokeRequired Then
Lbconn.Invoke(Sub() Lbconn.Items.Add(item))
Else
Lbconn.Items.Add(item)
End If
End Sub

Sending And Receiving SMS From GSM modem

I am trying to send message from GSM modem. I can submit AT commands the response is OK without any ERRORS. But the problem is I can't send message or read message.
I have implemented 3 functions:
Connect to port
Read SMS
Send SMS
Handles
1. Connect To Port:
Private Sub BtnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnConnect.Click
If SerialPort1.IsOpen Then
SerialPort1.Close()
BtnConnect.Text = "Connect"
Else
Try
With SerialPort1
.PortName = Trim(Mid(ComboBox1.Text, 1, 5))
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = Ports.StopBits.One
.Handshake = Ports.Handshake.None
.RtsEnable = True
.DtrEnable = True
.Open()
.WriteLine("AT+CNMI=1,2,0,0,0" & vbCrLf) 'send whatever data that it receives to serial port
End With
BtnConnect.Text = "Disconnect"
Catch ex As Exception
BtnConnect.Text = "Connect"
MsgBox(ex.Message)
End Try
End If
End Sub
2. Read SMS
Private Sub btn_read_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_read.Click
Try
SerialPort1.WriteLine("AT" & vbCrLf) 'is modem okay?
Thread.Sleep(1000)
SerialPort1.WriteLine("AT+CMGF=1" & vbCrLf) 'To format SMS as a TEXT message
Thread.Sleep(1000)
SerialPort1.WriteLine("AT+CPMS=""SM""" & vbCrLf) ' Select SIM storage
Threading.Thread.Sleep(1000)
SerialPort1.WriteLine("AT+CMGL=""REC UNREAD""" & vbCrLf) 'read unread messages
Threading.Thread.Sleep(1000)
SerialPort1.WriteLine("AT+CMGL=""ALL""" & vbCrLf) 'print all message
Threading.Thread.Sleep(1000)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
3. Send SMS
Private Sub btn_send_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_send.Click
Try
With SerialPort1
.WriteLine("AT" & vbCrLf)
Threading.Thread.Sleep(1000)
.WriteLine("AT+CMGF=1" & vbCrLf) 'Instruct the GSM / GPRS modem to operate in SMS text mode
Threading.Thread.Sleep(1000)
.WriteLine("AT+CMGS=""9802100355""" & vbCr) 'sender ko no. rakhne ho tyo txtnumber ma
Threading.Thread.Sleep(1000) 'thapeko
.WriteLine("This is test message" & vbCrLf & Chr(26)) 'txtmessage automatic huna parchha haina?
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
4. Handles for Data received in Serial Port
Private Sub serialport1_datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'Pause while all data is read
System.Threading.Thread.Sleep(300)
rcvdata = SerialPort1.ReadExisting()
MsgBox(rcvdata, , "Response From AT")
rcvdata = ""
End Sub
Where did I miss anything? While sending SMS I get CMS 500 error. With the software from the modem I am able to read and send sms. But I need to implement my own in my software.
There may several cause of this error. First check your network. Second set Message service center number using AT commands and save this setting. Hope this will help you
In your second function, you can try declaring a string variable to receive the data, like this:
With serialport1
rcvdata=""
.Write(All AT commands)
Threading.Thread.Sleep(1000)
Msgbox(rcvdata.Tostring)
End With
You can add a handler to datareceived to read all the bytes:
Dim entrada As String = " "
Dim numeros As Integer = SerialPort1.BytesToRead
For i As Integer = 1 To numeros
entrada&= Chr(SerialPort1.ReadChar)
Next
chama(entrada)
Private Sub chama(ByVal dados As String)
rcvdata &= dados
End Sub
AT+CMGS=""9802100355"
Your Phone number is wrong thats why you getting error 500, you need to enter full phone number including 0 at the front.

SMS Sending Application in VB.net

I'm trying to develop an application with vb.net 2008 to send sms to phone numbers from my pc. I've connected my nokia phone to my pc using USB cable (connected with COM3 port). Given bellow code which I have written should work but message is not being sent and I'm getting my app as deadlock condition:
Imports System
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
Dim ports As String() = SerialPort.GetPortNames
Dim port As String
For Each port In ports
ComboBox1.Items.Add(port)
Next port
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cmdConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdConnect.Click
Try
With SerialPort1
.PortName = ComboBox1.Text
.BaudRate = 9600
.Parity = Parity.None
.StopBits = StopBits.One
.DataBits = 8
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
.Open()
MsgBox("Connected !", MsgBoxStyle.Information)
End With
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cmdSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSend.Click
Try
If SerialPort1.IsOpen Then
With SerialPort1
.Write("AT" & vbCrLf)
.Write("AT+CMGF=1" & vbCrLf)
.Write("AT+CMGS=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
.Write(RichTextBox1.Text & Chr(26))
.Close()
MsgBox("Message Sent!", MsgBoxStyle.Information)
End With
Else
MsgBox("Error on port")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
Public Function sendMsg(ByVal port As SerialPort, ByVal PhoneNo As String, ByVal Message As String) As Boolean
Dim isSend As Boolean = False
Try
Dim recievedData As String = ExecCommand(port,"AT", 300, "No phone connected")
recievedData = ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.")
Dim command As String = "AT+CMGS=""" & PhoneNo & """"
recievedData = ExecCommand(port,command, 300, "Failed to accept phoneNo")
command = Message & Char.ConvertFromUtf32(26) & vbCr
recievedData = ExecCommand(port,command, 3000, "Failed to send message") '3 seconds
If recievedData.EndsWith(vbCrLf & "OK" & vbCrLf) Then
isSend = True
ElseIf recievedData.Contains("ERROR") Then
isSend = False
End If
Return isSend
Catch ex As Exception
Throw ex
End Try
End Function
ExecCommand
Public Function ExecCommand(ByVal port As SerialPort, ByVal command As String, ByVal responseTimeout As Integer, ByVal errorMessage As String) As String
Try
port.DiscardOutBuffer()
port.DiscardInBuffer()
receiveNow.Reset()
port.Write(command & vbCr)
Dim input As String = ReadResponse(port, responseTimeout)
If (input.Length = 0) OrElse (((Not input.EndsWith(vbCrLf & "> "))) AndAlso ((Not input.EndsWith(vbCrLf & "OK" & vbCrLf)))) Then
Throw New ApplicationException("No success message was received.")
End If
Return input
Catch ex As Exception
Throw ex
End Try
End Function
You can also try this coding..
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM17")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 19200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
Application.DoEvents()
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
Thread.Sleep(500)
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
Thread.Sleep(500)
' SMSPort.WriteLine("AT+CSCA=""+919822078000""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS=" & """" & Form1.TextBox1.Text & """" & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
Thread.Sleep(500)
SMSPort.WriteLine(Form1.TextBox2.Text & Chr(26)) 'SMS sending(specify the labl and the text box)
MessageBox.Show(":send")
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not (SMSPort.IsOpen = True) Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
you have to connect your phone with PC Suite or Bluetooth or using USB cable.
After that you have to check the port number and change in coding part according to your port number.
Dim SMSEngine As New SMSCOMMS("COM17")
It is working for me..

vb.net server - multiple clients continually processing different information

I am looking for help with writing a server application to serve an updating text stream to clients. My requirements are as follows:
I need to be able to have a client request information on server port 7878 and receive back an initial set of values, the changed values would then be reported every 5 seconds. The hanging point for me has been connecting another client. I need to be able to connect a 2nd (or 3rd or 4th) client while the first is still running. The second client would receive the initial values and then begin updating as well. I need the two streams to be completely independent of each other. Is this possible with VB.Net and TCP sockets?
Edit to add: I have pasted some of my code below of what I can share. WriteLog is a separate sub that isn't really relevant to my problem. This code will allow for a client to connect and then allow for another client to connect, but all transmissions to the 1st client stop on a new connection.
Public Class ServerApp
Dim serverSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Private Sub ServerApp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
WriteLog(String.Format("Start of form load.."))
Dim listener As New Thread(New ThreadStart(AddressOf ListenForRequests))
listener.IsBackground = True
listener.Start()
End Sub
Private Sub ListenForRequests()
Dim CONNECT_QUEUE_LENGTH As Integer = 4
serverSocket.Bind(New IPEndPoint(IPAddress.Any, 7878))
serverSocket.Listen(CONNECT_QUEUE_LENGTH)
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
End Sub
Private Sub OnAccept(ByVal ar As IAsyncResult)
clientSocket = serverSocket.EndAccept(ar)
serverSocket.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
WriteLog("just accepted new client")
Try
clientSocket.Send(Encoding.UTF8.GetBytes("first response on connect"), SocketFlags.None)
While True
clientSocket.Send(Encoding.UTF8.GetBytes("string of updates"), SocketFlags.None)
Thread.Sleep(5000)
End While
Catch ex As Exception
WriteLog(ex.Message)
WriteLog("Remote host has disconnected")
End Try
End Sub
End Class
I recommend trying out the UdpClient class, i find it easier to use and understand.
Now for some code...
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Imports System.Net
Public Class Form1
Private port As Integer = 7878
Private Const broadcastAddress As String = "255.255.255.255"
Private receivingClient As UdpClient
Private sendingClient As UdpClient
Private myTextStream As String = "Blah blah blah"
Private busy As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
InitializeSender()
InitializeReceiver()
End Sub
Private Sub InitializeSender()
Try
sendingClient = New UdpClient(broadcastAddress, port)
sendingClient.EnableBroadcast = True
Catch ex As Exception
MsgBox("Error, unable to setup sender client on port " & port & "." & vbNewLine & vbNewLine & ex.ToString)
End Try
End Sub
Private Sub InitializeReceiver()
Try
receivingClient = New UdpClient(port)
ThreadPool.QueueUserWorkItem(AddressOf Receiver)
Catch ex As Exception
MsgBox("Error, unable to setup receiver on port " & port & "." & vbNewLine & vbNewLine & ex.ToString)
End
End Try
End Sub
Private Sub sendStream()
busy = True
Dim i% = 0
Do While i < 4
If myTextStream <> "" Then
Dim data() As Byte = Encoding.ASCII.GetBytes(myTextStream)
Try
sendingClient.Send(data, data.Length)
Catch ex As Exception
MsgBox("Error, unable to send stream." & vbNewLine & vbNewLine & ex.ToString)
End
End Try
End If
Thread.Sleep(5000)
i += 1
Loop
busy = False
End Sub
Private Sub Receiver()
Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port)
While True
Dim data() As Byte
data = receivingClient.Receive(endPoint)
Dim incomingMessage As String = Encoding.ASCII.GetString(data)
If incomingMessage = "what ever the client is requesting, for example," & "GET_VALUES" Then
If busy = False Then Call sendStream()
End If
End While
End Sub
End Class
A few links that may help: Here,
here,
here and
here.