Imports System.Collections.Generic Imports System.ComponentModel Imports System.Drawing Imports System.Linq Imports System.Text Imports System.Windows.Forms Imports System.IO.Ports Imports System.IO Imports System.Reflection Imports System.Threading Imports MessagingToolkit.Core Imports MessagingToolkit.Core.Mobile Imports MessagingToolkit.Core.Log Imports MessagingToolkit.Core.Mobile.Message Imports MessagingToolkit.Core.Mobile.Event Imports MessagingToolkit.Core.Helper Imports MessagingToolkit.Pdu Imports MessagingToolkit.Pdu.Ie Imports MessagingToolkit.Pdu.WapPush Public Class frmGSM Inherits Form 'Private mobileGateway As IMobileGateway = MobileGatewayFactory.[Default] 'Private Shared CustomDateTimeFormat As String = "dd MMM yyyy, hh:mm:ss tt" 'Private Parity As New Dictionary(Of String, PortParity)() From { _ ' {"None", PortParity.None}, _ ' {"Odd", PortParity.Odd}, _ ' {"Even", PortParity.Even}, _ ' {"Mark", PortParity.Mark}, _ ' {"Space", PortParity.Space} _ '} 'Private StopBits As New Dictionary(Of String, PortStopBits)() From { _ ' {"1", PortStopBits.One}, _ ' {"1.5", PortStopBits.OnePointFive}, _ ' {"2", PortStopBits.Two}, _ '{"None", PortStopBits.None} _ '} 'Private Handshake As New Dictionary(Of String, PortHandshake)() From { _ ' {"None", PortHandshake.None}, _ '' {"RequestToSendXOnXOff", PortHandshake.RequestToSendXOnXOff}, _ ' {"XOnXOff", PortHandshake.XOnXOff}, _ ' {"RequestToSend", PortHandshake.RequestToSend} _ '} 'Private MessageType As New Dictionary(Of String, MessageStatusType)() From { _ ' {"Received Unread Message", MessageStatusType.ReceivedUnreadMessages}, _ ' {"Received Read Message", MessageStatusType.ReceivedReadMessages}, _ ' {"Stored Unsent Message", MessageStatusType.StoredUnsentMessages}, _ ' {"Stored Sent Message", MessageStatusType.StoredSentMessages}, _ ' {"All Message", MessageStatusType.AllMessages} _ '} 'Private MessageEncoding As New Dictionary(Of String, MessageDataCodingScheme)() From { _ ' {"Auto Detect", MessageDataCodingScheme.Undefined}, _ ' {"Default Alphabet - 7 Bits", MessageDataCodingScheme.DefaultAlphabet}, _ ' {"ANSI - 8 Bits", MessageDataCodingScheme.EightBits}, _ ' {"Unicode - 16 Bits", MessageDataCodingScheme.Ucs2} _ '} 'Private MessageSplit As New Dictionary(Of String, MessageSplitOption)() From { _ ' {"Truncate", MessageSplitOption.Truncate}, _ ' {"Simple Split", MessageSplitOption.SimpleSplit}, _ ' {"Concatenate", MessageSplitOption.Concatenate} _ '} 'Private QueuePriority As New Dictionary(Of String, MessageQueuePriority)() From { _ ' {"Low", MessageQueuePriority.Low}, _ ' {"Normal", MessageQueuePriority.Normal}, _ ' {"High", MessageQueuePriority.High} _ '} 'Private ValidityPeriod As New Dictionary(Of String, MessageValidPeriod)() From { _ ' {"1 Hour", MessageValidPeriod.OneHour}, _ '{"3 Hours", MessageValidPeriod.ThreeHours}, _ '{"6 Hours", MessageValidPeriod.SixHours}, _ '{"12 Hours", MessageValidPeriod.TwelveHours}, _ '{"1 Day", MessageValidPeriod.OneDay}, _ '{"1 Week", MessageValidPeriod.OneWeek}, _ '{"Maximum", MessageValidPeriod.Maximum} _ '} ' Log level 'Private LoggingLevel As New Dictionary(Of String, LogLevel)() From { _ ' {"Error", LogLevel.[Error]}, _ ' {"Warn", LogLevel.Warn}, _ ' {"Info", LogLevel.Info}, _ ' {"Verbose", LogLevel.Verbose} _ '} ' Message class 'Private MessageClass As New Dictionary(Of String, Integer)() From { _ ' {"None", 0}, _ ' {"ME", PduUtils.DcsMessageClassMe}, _ ' {"SIM", PduUtils.DcsMessageClassSim}, _ ' {"TE", PduUtils.DcsMessageClassTe} _ '} ' DCS Message class enum lookup 'Private DcsMessageClass As New Dictionary(Of String, MessageClasses)() From { _ ' {"None", MessageClasses.None}, _ ' {"ME", MessageClasses.[Me]}, _ ' {"SIM", MessageClasses.Sim}, _ ' {"TE", MessageClasses.Te} _ '} 'Private AllStorages As New List(Of MessageStorage)() From { _ ' MessageStorage.Sim, _ ' MessageStorage.Phone, _ ' MessageStorage.MobileTerminating _ '} 'Private Models As New List(Of String)() From { _ ' "Wavecom", _ ' "Huawei", _ ' "Sony Ericsson", _ ' "Siemens" _ '} Public Delegate Sub DisplayCallLog(e As IncomingCallEventArgs) Public Delegate Sub DisplayCallEventLog(e As OutgoingCallEventArgs) 'Private Delegate Sub DisplayMessageLog(e As MessageReceivedEventArgs) 'Private Delegate Sub DisplayCallLog(e As IncomingCallEventArgs) 'Private Delegate Sub DisplayCallEventLog(e As OutgoingCallEventArgs) 'Private Delegate Sub DisplayUssdResponse(e As UssdReceivedEventArgs) 'Private _displayMessageLog As DisplayMessageLog 'Private _displayUssdResponse As DisplayUssdResponse 'Private _displayCallLog As DisplayCallLog 'Private _displayCallEventLog As DisplayCallEventLog Public _displayCallLog As DisplayCallLog Public _displayCallEventLog As DisplayCallEventLog 'Private Const ProviderFileExtension As String = ".mm1" 'Private Const MMSProviderPath As String = "MMSProviders" #End Region Private Sub frmSMS_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Add the port Dim portNames As String() = SerialPort.GetPortNames() If portNames.Length > 0 Then ' There is a bug that for high COM port there is a "c" at the back, e.g. "COM11c" Dim sortedList = portNames Dim id As PlatformID = Environment.OSVersion.Platform If id = PlatformID.Win32Windows OrElse id = PlatformID.Win32NT Then ' This is a Windows based OS, serial port should start with COM portNames.OrderBy(Function(port) Convert.ToInt32(port.Replace("COM", String.Empty).Replace("c", String.Empty))) End If 'var sortedList = portNames.OrderBy(port => port.Replace("COM", string.Empty)); For Each port As String In sortedList If Not cboPort.Items.Contains(port) Then cboPort.Items.Add(port) End If Next cboPort.SelectedIndex = 0 End If ' Message indication option cboMessageIndicationOption.Items.AddRange(New String() {"Trigger", "Polling"}) cboMessageIndicationOption.SelectedIndex = 0 _displayMessageLog = New DisplayMessageLog(AddressOf Me.ShowMessageLog) _displayCallLog = New DisplayCallLog(AddressOf Me.ShowCallLog) _displayCallEventLog = New DisplayCallEventLog(AddressOf Me.ShowCallEventLog) End Sub Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click Dim config As MobileGatewayConfiguration = MobileGatewayConfiguration.NewInstance() 'string portName = cboPort.Text; 'if (portName.EndsWith("c")) portName = portName.Substring(0, portName.Length - 1); config.PortName = cboPort.Text config.BaudRate = PortBaudRate.BitsPerSecond115200 config.DataBits = PortDataBits.Eight config.Parity = PortParity.None config.StopBits = PortStopBits.One config.Handshake = PortHandshake.None config.DisablePinCheck = True ' If set to true, then a dialog box will be popped up for any API errors config.DebugMode = chkDebugMode.Checked ' Default to verbose by default config.LogLevel = LogLevel.Verbose ' Set the connected event AddHandler config.GatewayConnected, AddressOf OnGatewayConnect config.DtrEnable = True config.RtsEnable = True config.LicenseKey = "" ' If we want persistence queue. Default to false 'config.PersistenceQueue = true; ' Set a different log file prefix and path 'config.LogFile = "mylog"; 'config.LogLocation = @"c:\temp"; ' Set the log file name without the date config.LogNameFormat = LogNameFormat.Name ' Set watch dog interval to 5 seconds. Default to 60 seconds 'config.WatchDogInterval = 5000; ' You can also specify the total number of milliseconds for AT command time out ' Multiply these 2 parameters you can the number of milliseconds for command time out. ' E.g. below is the default of 30 seconds config.CommandWaitInterval = 50 config.CommandWaitRetryCount = 100 ' Do this if there is a problem you faced when device is unplug and plug in again to the server ' Most of the time you don't need to set these 2 parameter at all. They should be defaulted to FALSE. config.SafeConnect = False config.SafeDisconnect = False ' Create the gateway for mobile Dim _messageGateway As MessageGateway(Of IMobileGateway, MobileGatewayConfiguration) = MessageGateway(Of IMobileGateway, MobileGatewayConfiguration).NewInstance() Try btnConnect.Enabled = False mobileGateway = _messageGateway.Find(config) If mobileGateway Is Nothing Then MessageBox.Show("Error connecting to gateway. Check the log file", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error]) Return End If 'mobileGateway.LogLevel = LogLevel.Verbose; 'txtSmsc.Text = mobileGateway.ServiceCentreAddress.Number updSendRetries.Value = mobileGateway.Configuration.SendRetries updPollingInterval.Value = mobileGateway.Configuration.MessagePollingInterval updSendWaitInterval.Value = mobileGateway.Configuration.SendWaitInterval chkDeleteReceivedMessage.Checked = mobileGateway.Configuration.DeleteReceivedMessage txtLogFile.Text = mobileGateway.LogFile AddHandler mobileGateway.MessageReceived, AddressOf OnMessageReceived AddHandler mobileGateway.MessageSendingFailed, AddressOf OnMessageFailed AddHandler mobileGateway.MessageSent, AddressOf OnMessageSent AddHandler mobileGateway.CallReceived, AddressOf OnCallReceived AddHandler mobileGateway.GatewayDisconnected, AddressOf OnGatewayDisconnect AddHandler mobileGateway.WatchDogFailed, AddressOf OnWatchDogFailed ' Set the serial port read time out. Default to 3 seconds 'mobileGateway.ReadTimeout = 6000; mobileGateway.EnableCallNotifications() 'AddHandler mobileGateway.CallDialled, New OutgoingCallEventHandler(AddressOf OnCallDialled) 'mobileGateway.EnableCLIR() 'mobileGateway.EnableCOLP() ' Set the serial port write time out. Default to 3 seconds 'mobileGateway.WriteTimeout = 6000; lSttsGSMDevice.Text = "GSM Connected" mobileGateway.SendCommand("AT+CLCC=1") Catch ex As Exception MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error]) Finally btnConnect.Enabled = True End Try End Sub Private Sub btnDisconnect_Click(sender As Object, e As EventArgs) Handles btnDisconnect.Click Try If mobileGateway IsNot Nothing Then btnDisconnect.Enabled = False If mobileGateway.Disconnect() Then mobileGateway.Dispose() mobileGateway = Nothing mobileGateway = MobileGatewayFactory.[Default] lSttsGSMDevice.Text = "GSM Disconnected" Else MessageBox.Show(mobileGateway.LastError.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error]) End If End If Finally btnDisconnect.Enabled = True End Try End Sub Private Sub btnApplyConfiguration_Click(sender As Object, e As EventArgs) Handles btnApplyConfiguration.Click Dim sendRetries As Integer = Convert.ToInt32(updSendRetries.Value) Dim pollingInterval As Integer = Convert.ToInt32(updPollingInterval.Value) Dim sendWaitInterval As Integer = Convert.ToInt32(updSendWaitInterval.Value) Dim deleteReceivedMessage As Boolean = chkDeleteReceivedMessage.Checked Dim debugMode As Boolean = chkDebugMode.Checked If sendRetries > 0 Then mobileGateway.Configuration.SendRetries = sendRetries End If If pollingInterval > 0 Then mobileGateway.Configuration.MessagePollingInterval = pollingInterval End If If sendWaitInterval > 0 Then mobileGateway.Configuration.SendWaitInterval = sendWaitInterval End If mobileGateway.Configuration.DebugMode = debugMode mobileGateway.Configuration.DeleteReceivedMessage = deleteReceivedMessage End Sub Private Sub chkEnableMessageIndication_CheckedChanged(sender As Object, e As EventArgs) Handles chkEnableMessageIndication.CheckedChanged cboMessageIndicationOption.Enabled = chkEnableMessageIndication.Checked End Sub Private Sub btnApplyMessageSettings_Click(sender As Object, e As EventArgs) Handles btnApplyMessageSettings.Click Try btnApplyMessageSettings.Enabled = False Dim result As Boolean = False If chkEnableMessageIndication.Checked Then If cboMessageIndicationOption.Text.Equals("Trigger") Then ' Incoming SMS and status report messages will be using trigger result = mobileGateway.EnableNewMessageNotification(MessageNotification.ReceivedMessage Or MessageNotification.StatusReport) ' Set to false to disable polling mobileGateway.PollNewMessages = False Else ' If you fail to receive status report indication, then try to comment this line, ' and uncomment out DisableMessageNotifications result = mobileGateway.EnableNewMessageNotification(MessageNotification.StatusReport) ' Disable incoming notifications since we want to use polling 'result = mobileGateway.DisableMessageNotifications(); ' Incoming SMS will be polled periodically mobileGateway.PollNewMessages = True End If Else ' Disable all incoming notifications result = mobileGateway.DisableMessageNotifications() ' No polling will be performed mobileGateway.PollNewMessages = False End If mobileGateway.Configuration.DeleteReceivedMessage = chkDeleteAfterReceive.Checked If result Then MessageBox.Show("Message settings are applied", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Error applying settings", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error]) End If Finally btnApplyMessageSettings.Enabled = True End Try End Sub Private Sub OnMessageReceived(sender As Object, e As MessageReceivedEventArgs) txtMessageLog.BeginInvoke(_displayMessageLog, e) End Sub Private Sub OnMessageSent(sender As Object, e As MessageEventArgs) Dim sms As Sms = DirectCast(e.Message, Sms) MessageBox.Show("Message is sent successfully to " & sms.DestinationAddress & ". Message index is " & String.Join(",", (sms.Indexes.ConvertAll(Of String)(Function(i As Integer) i.ToString())).ToArray()) & ". Message identifier is " & sms.Identifier, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Private Sub OnMessageFailed(sender As Object, e As MessageErrorEventArgs) Dim sms As Sms = DirectCast(e.Message, Sms) MessageBox.Show("Failed to send message to " & sms.DestinationAddress, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error]) MessageBox.Show(e.[Error].Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.[Error]) End Sub Private Sub ShowMessageLog(e As MessageReceivedEventArgs) If e.Message.MessageType = MessageTypeIndicator.MtiSmsDeliver Then txtMessageLog.AppendText("Received message from " & e.Message.PhoneNumber & vbLf) txtMessageLog.AppendText("Received date: " & e.Message.ReceivedDate & vbLf) txtMessageLog.AppendText("Message type: " & Convert.ToString(e.Message.MessageType) & vbLf) txtMessageLog.AppendText("Received content: " & e.Message.Content & vbLf) txtMessageLog.AppendText(vbLf) Else If e.Message.DeliveryStatus = MessageStatusReportStatus.Success Then txtMessageLog.AppendText("Message is delivered to " & e.Message.PhoneNumber & vbLf) txtMessageLog.AppendText("Delivered date: " & e.Message.ReceivedDate & vbLf) txtMessageLog.AppendText("Message type: " & Convert.ToString(e.Message.MessageType) & vbLf) txtMessageLog.AppendText("Content: " & e.Message.Content & vbLf) txtMessageLog.AppendText(vbLf) Else txtMessageLog.AppendText("Message is not delivered to " & e.Message.PhoneNumber & vbLf) txtMessageLog.AppendText("Message type: " & Convert.ToString(e.Message.MessageType) & vbLf) txtMessageLog.AppendText("Delivery status: " & Convert.ToString(e.Message.DeliveryStatus) & vbLf) txtMessageLog.AppendText("Content: " & e.Message.Content & vbLf) txtMessageLog.AppendText(vbLf) End If End If End Sub Private Sub ShowCallLog(e As IncomingCallEventArgs) txtIncomingCallIndication.AppendText("Call received from " & e.CallInformation.Number) txtIncomingCallIndication.AppendText(vbLf) txtIncomingCallIndication.AppendText("Number type - " & Convert.ToString(e.CallInformation.NumberType)) txtIncomingCallIndication.AppendText(vbLf & vbLf) End Sub Private Sub frmSMS_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing If mobileGateway IsNot Nothing Then mobileGateway.Disconnect() mobileGateway.Dispose() mobileGateway = Nothing End If End Sub Private Sub btnMakeCall_Click(sender As Object, e As EventArgs) Handles btnMakeCall.Click Try If Not String.IsNullOrEmpty(txtCallingNo.Text) Then btnMakeCall.Enabled = False mobileGateway.Dial(txtCallingNo.Text) Else MessageBox.Show("Calling number cannot be empty", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information) End If Finally btnMakeCall.Enabled = True End Try End Sub Private Sub btnHangUp_Click(sender As Object, e As EventArgs) Handles btnHangUp.Click Try btnHangUp.Enabled = False mobileGateway.HangUp() Finally btnHangUp.Enabled = True End Try End Sub Private Sub btnAnswerCall_Click(sender As Object, e As EventArgs) Handles btnAnswerCall.Click Try btnAnswerCall.Enabled = False mobileGateway.Answer() Finally btnAnswerCall.Enabled = True End Try End Sub Private Sub OnCallReceived(sender As Object, e As IncomingCallEventArgs) txtCallingNo.BeginInvoke(_displayCallLog, e) End Sub Private Sub OnGatewayConnect(sender As Object, e As ConnectionEventArgs) ' Called when gateway is connected 'MessageBox.Show("Connect"); Console.WriteLine(e.GatewayId) End Sub Private Sub OnGatewayDisconnect(sender As Object, e As ConnectionEventArgs) ' Called when gateway is disconnected 'MessageBox.Show("Disconnect"); Console.WriteLine(e.GatewayId) End Sub Private Sub OnWatchDogFailed(sender As Object, e As WatchDogEventArgs) ' Called when gateway is disconnected Console.WriteLine(e.GatewayId) If e.[Error] IsNot Nothing Then Console.WriteLine(e.ToString()) End If End Sub Private Shared Function GetDataCodingScheme(content As String) As MessageDataCodingScheme Dim i As Integer = 0 For i = 1 To content.Length Dim code As Integer = Convert.ToInt32(Convert.ToChar(content.Substring(i - 1, 1))) If code < 0 OrElse code > 255 Then Return MessageDataCodingScheme.Ucs2 End If Next Return MessageDataCodingScheme.DefaultAlphabet End Function Private Sub btnViewLogFile_Click(sender As Object, e As EventArgs) Handles btnViewLogFile.Click If Not String.IsNullOrEmpty(txtLogFile.Text) AndAlso File.Exists(txtLogFile.Text) Then System.Diagnostics.Process.Start(txtLogFile.Text) End If End Sub Private Sub btnClearLogFile_Click(sender As Object, e As EventArgs) Handles btnClearLogFile.Click If Not String.IsNullOrEmpty(txtLogFile.Text) AndAlso File.Exists(txtLogFile.Text) Then mobileGateway.ClearLog() End If End Sub Private Sub OnCallDialled(sender As Object, e As OutgoingCallEventArgs) txtOutgoingCallEvent.BeginInvoke(_displayCallEventLog, e) End Sub Private Sub ShowCallEventLog(e As OutgoingCallEventArgs) txtOutgoingCallEvent.AppendText("Dialled " & e.CallInformation.Number) txtOutgoingCallEvent.AppendText(vbCr & vbLf) txtOutgoingCallEvent.AppendText("Number type - " & Convert.ToString(e.CallInformation.NumberType)) txtOutgoingCallEvent.AppendText(vbCr & vbLf & vbCr & vbLf) End Sub Private Sub btnStatus_Click(sender As Object, e As EventArgs) Handles btnStatus.Click If mobileGateway.ValidateConnection() Then MessageBox.Show("Gateway is connected", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information) Else MessageBox.Show("Gateway is disconnected", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub End Class