Login Login

CSharp:SMS - SMPP

From Aino Wiki

Jump to: navigation, search

Teoria

Come da SMPP.org:
Il protocollo SMPP è un protocollo industriale standard aperto progettato per fornire una interfaccia di comunicazione flessibile all'invio di brevi messaggi di testo (SMS) tra un centro messaggi (SMSC = Short Message Service Centre) ed entità short message (ESMEs ) poste al di fuori della rete mobile.

Fonte SMPP.org

Esempi di applicazioni ESME posson essere: allerta di email ricevute da VPS (Voice Processing System), servizi informazioni, applicazioni gestionali che usinno SMSC per determinare la posizione di veicoli servizio o notificarne la vicinanza, applicazioni di telemetria, WAP Proxy Server. Ovvero:

Fonte SMPP.org

Definizione del protocollo

L'SMPP è basato sullo scambio di richieste (request) e risposte (response) di unità di protocollo (protocol data units= PDUs) tra l'ESME e l'SMSC sfruttando il sottostante protocollo TCP/IP o connessione di rete X.25.
Il protocollo SMPP definisce:

  • un insieme di operazioni e associati PDUs (Protocol Data Units) per lo scambio di messaggi SMS tra ESME e SMSC.
  • i dati che le applicazioni ESME possono scambiarsi con un SMSC durante le operazioni SMPP.

NOTA

  • Ogni operazione SMPP deve consistere in una request PDU e associata response PDU. L'entità ricevente deve restituire l'associata SMPP response ad una request SMPP PDU.
  • La sola eccezione alla regola è: l'alert_notification PDU per cui non c'è alcuna response in uscita.

Lo scambio di messaggi tra un ESME e SMSC attraverso l'SMPP può esser classificato in 3 gruppi di transazioni come segue:

  1. messaggi inviati da ESME (Transmitter - TX) a SMSC; richiede autenticazione in qualità di trasmettitore.
  2. messaggi inviati da SMSC a ESME (Receiver - RX);
  3. messaggi inviati da ESME (Transceiver - TRX) a SMSC e messaggi inviati da SMSC a ESME (Transceiver).
Fonte SMPP.org

Descrizione della sessione SMPP

The SMPP protocol is a set of operations, each one taking the form of a request and response Protocol Data Unit (PDU) containing an SMPP command. For example, if an ESME wishes to submit a short message, it may send a submit_sm PDU to the MC. The MC responds with a submit_sm_resp PDU, indicating the success or failure of the request. Likewise, if an MC wishes to deliver a message to an ESME, it may send a deliver_sm PDU to an ESME, which in turn responds with a deliver_sm_resp PDU as a means of acknowledging the delivery.

Fonte SMPP.org

Le operazioni sono classificate nei seguenti gruppi:

  • Session Management - These operations are designed to enable the establishment of SMPP sessions between an ESME and MC and provide means of handling unexpected errors.
  • Message Submission - These operations are explicitly designed for the submission of messages from ESME(s) to the MC.
  • Message Delivery - These operations enable an MC to deliver messages to the ESME.
  • Message Broadcast - These operations are designed to provide Cell Broadcast service within a Message Centre.
  • Ancillary Operations (Operazioni ausiliarie) - These operations are designed to provide enhanced features such as cancellation, query or replacement of messages.

Implementazione teorica

Esempio SMPP PDU, invio SMS

Da [smpp.org]

submit_sm

submit_sm_resp

Comandi

[smpp.org]

Codici di errore

[smpp.org]

 

Helper C#

Esempio con Jamaa

Considerando che il seguente codice ancora non l'ho testato, segue la classe helper consistene in un collage di esempi presi dalla Wiki della libreria Jamaa:

using JamaaTech.Smpp.Net.Client;
using JamaaTech.Smpp.Net.Lib;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace XXX_Common
{
    public class SMPPHelper
    {
        //DOC:  https://github.com/AdhamAwadhi/JamaaSMPP/wiki
        public SmppClient Client = new SmppClient();
        public string TextSMSDelivered = string.Empty;
 
        private static readonly Logger m_logger = LogManager.GetCurrentClassLogger();
 
        /// <summary>
        /// Instaura una connessione al server SMSC (Short Message Service Centre)
        /// </summary>
        /// <param name="systemID"></param>
        /// <param name="password"></param>
        /// <param name="port"></param>
        /// <param name="host"></param>
        /// <param name="systemType"></param>
        /// <param name="defaultServiceType"></param>
        public SMPPHelper(string systemID, string password, int port
                        , string host, string systemType, string defaultServiceType)
        {
            SmppConnectionProperties properties = Client.Properties;
            properties.SystemID = systemID; // "mysystemid";
            properties.Password = password; // "mypassword";
            properties.Port = port; // 2034; //IP port to use
            properties.Host = host; // "196.23.3.12"; //SMSC host name or IP Address
            properties.SystemType = systemType; // "mysystemtype";
            properties.DefaultServiceType = defaultServiceType; // "mydefaultservicetype";
 
            //Handle the SmppClient.ConnectionStateChanged event to receive notifications 
            //when connection status changes
            Client.ConnectionStateChanged += Client_ConnectionStateChanged;
 
            //Resume a lost connection after 30 seconds
            Client.AutoReconnectDelay = 3000;
 
            //Send Enquire Link PDU every 15 seconds
            Client.KeepAliveInterval = 15000;
 
            //Start smpp client
            Client.Start();
        }
 
        private void Client_ConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e)
        {
            m_logger.Debug("SMPP connection status changes to '{0}'.", e.CurrentState);
            switch (e.CurrentState)
            {
                case SmppConnectionState.Closed:
                    //Connection to the remote server is lost
                    //Do something here
 
                    e.ReconnectInteval = 60000; //Try to reconnect after 1 min
                    break;
                case SmppConnectionState.Connected:
                    //A successful connection has been established
                    break;
                case SmppConnectionState.Connecting:
                    //A connection attemp is still on progress
                    break;
            }
        }
 
        public string SendSMS_Synchro(string destinationNr, string sourceAddress, string smsText)
        {
            string strErrorMsg = string.Empty;
            TextMessage msg = new TextMessage();
            int timeOut = 0; //?????????????
 
            try
            {
                m_logger.Debug("Sending SMS to {0}, sourceAddress='{1}'", destinationNr, sourceAddress);
 
                msg.DestinationAddress = destinationNr;     // "255455388333"; //Receipient number
                msg.SourceAddress = sourceAddress;          // "255344338333"; //Originating number
                msg.Text = smsText;
                msg.RegisterDeliveryNotification = true;    //I want delivery notification for this message
 
                Client.MessageDelivered += Client_MessageDelivered; //Per Notifica e verifica del messaggio inviato
 
                //Default encdoing:      System.Text.Encoding.BigEndianUnicode
                //But if you like UTF8:
                //Client.SmppEncodingService = new SmppEncodingService(System.Text.Encoding.UTF8);
 
                //Client.SendMessage(msg, timeOut);
                Client.SendMessage(msg);
            }
            catch (Exception ex)
            {
                m_logger.Error(ex);
                strErrorMsg = string.Format("Error sending to '{0}':\r\n{1}", destinationNr, ex.Message);
            }
            return strErrorMsg;
        }
 
 
        public string SendSMS_Asynchro(string destinationNr, string sourceAddress, string smsText)
        {
            string strErrorMsg = string.Empty;
            TextMessage msg = new TextMessage();
 
            try
            {
                msg.DestinationAddress = destinationNr; // "255455388333"; //Receipient number
                msg.SourceAddress = sourceAddress; // "255344338333"; //Originating number
                msg.Text = smsText; // "Hello, this is my test message!";
                msg.RegisterDeliveryNotification = true; //I want delivery notification for this message
 
                // ??? SmppClient client = GetSmppClient();
                Client.BeginSendMessage(msg, SendMessageCompleteCallback, Client);
            }
            catch (Exception ex)
            {
                m_logger.Error(ex);
                strErrorMsg = string.Format("Error sending to '{0}':\r\n{1}", destinationNr, ex.Message);
            }
            return strErrorMsg;
        }
 
        #region Private methods
        private void Client_MessageDelivered(object sender, MessageEventArgs e)
        {
            try
            {
                TextMessage msg = e.ShortMessage as TextMessage;
 
                //parse msg.Text for more details
                m_logger.Debug(msg.Text);
 
                TextSMSDelivered = msg.Text;
            }
            catch (Exception ex)
            {
                m_logger.Error(ex);
            }
        }
 
        private void SendMessageCompleteCallback(IAsyncResult result)
        {
            try
            {
                SmppClient client = (SmppClient)result.AsyncState;
                client.EndSendMessage(result);
            }
            catch (Exception ex)
            {
                m_logger.Error(ex);
            }
        }
        #endregion
    }
}

Mappa e Link


C# | Librerie di terze parti PlugIn


Visual Studio | MS SQL | Dizionario


Parole chiave:

Author