Пример #1
0
        public static void AddVendorSpecificParameter(SubmitSm sm)
        {
            //0x1400 - 0x3FFF Reserved for SMSC Vendor specific optional parameters
            byte[] value = new byte[] { 0x01 };

            sm.Parameters.Add(new TLV(0x1410, value));
        }
Пример #2
0
        public static async Task SendSubmitSmWithUDH(SmppClient client)
        {
            //If you have UserDataHeader as byte array. You can create SubmitSm manually and pass it to headers collection.

            byte[] udh = new byte[]
            {
                5,  //UDHL,
                0,  //Concatenation
                3,  // Length
                50, //message reference
                1,  //total parts,
                1,  // part number
            };



            SubmitSm sm = new SubmitSm();

            sm.SourceAddress      = new SmeAddress("My Service");
            sm.DestinationAddress = new SmeAddress("+7917123456");
            sm.DataCoding         = DataCodings.UCS2;
            sm.RegisteredDelivery = 1;

            sm.UserData.ShortMessage = client.EncodingMapper.GetMessageBytes("test message", sm.DataCoding);
            sm.UserData.Headers      = udh;

            var resp = await client.Submit(sm);
        }
Пример #3
0
        private static void SendMessage(string command)
        {
            var parts       = command.Split(' ');
            var phoneNumber = parts[1];
            var message     = string.Join(" ",
                                          parts,
                                          2,
                                          parts.Length - 2);

            // This is set in the Submit PDU to the SMSC
            // If you are responding to a received message, make this the same as the received message
            var submitDataCoding = DataCodings.Default;

            // Use this to encode the message
            // We need to know the actual encoding.
            var encodeDataCoding = DataCodings.ASCII;

            // There is a default encoding set for each connection. This is used if the encodeDataCoding is Default

            SubmitSm     submitSm     = null;
            SubmitSmResp submitSmResp = null;

            connectionManager.SendMessage(phoneNumber,
                                          null,
                                          Ton.National,
                                          Npi.ISDN,
                                          submitDataCoding,
                                          encodeDataCoding,
                                          message,
                                          out submitSm,
                                          out submitSmResp);
        }
Пример #4
0
        private void ServerOnClientSubmitSm(object sender, SmppServerClient client, SubmitSm pdu)
        {
            Console.WriteLine($"Inbound message from {client.SystemID}");

            //Set server message id for the pdu;
            pdu.Response.MessageId = Guid.NewGuid().ToString().Substring(0, 8);
        }
        public void SendCommmand()
        {
            SubmitSm submitSm = new SubmitSm();

            submitSm.ServiceType = "USSD";
            submitSm.Parameters.Add(new UssdServiceOpParameter(USSDOperation.USSRRequest));
            submitSm.Parameters.Add(new TLV(OptionalTags.ItsSessionInfo, new byte[] { 11 }));
            submitSm.Parameters.Add(new TLV(OptionalTags.MoreMessagesToSend, new byte[] { 1 }));
        }
Пример #6
0
        protected virtual SubmitSm CreateSubmitSm()
        {
            var sm = new SubmitSm();

            //sm.SourceAddress.Ton = TypeOfNumber.Unknown;
            //sm.DestinationAddress.Ton = TypeOfNumber.Unknown;

            return(sm);
        }
Пример #7
0
        protected virtual SubmitSm CreateSubmitSm(SmppEncodingService smppEncodingService)
        {
            var sm = new SubmitSm(smppEncodingService);

            //sm.SourceAddress.Ton = TypeOfNumber.Unknown;
            //sm.DestinationAddress.Ton = TypeOfNumber.Unknown;

            return(sm);
        }
        //</SendMessage>

        // <CreateSubmitSm>
        public SubmitSm CreateSubmitSm()
        {
            SubmitSm sm = new SubmitSm();

            sm.UserData.ShortMessage = _client.EncodingMapper.GetMessageBytes("Test Test Test Test Test Test Test Test Test Test", DataCodings.Default);
            sm.SourceAddress         = new SmeAddress("1111", AddressTON.NetworkSpecific, AddressNPI.Unknown);
            sm.DestinationAddress    = new SmeAddress("79171234567", AddressTON.Unknown, AddressNPI.ISDN);
            sm.DataCoding            = DataCodings.UCS2;
            sm.SMSCReceipt           = SMSCDeliveryReceipt.SuccessOrFailure;

            return(sm);
        }
        /// <summary> Serialize SubmitSm object to the byte array. </summary>
        ///
        /// <param name="client"> The client. </param>
        /// <param name="pdu"> The SubmitSm object. </param>
        ///
        /// <returns> A byte array. </returns>
        public byte[] Serialize(SmppClient client, SubmitSm pdu)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                using (SmppWriter writer = new SmppWriter(stream, client.EncodingMapper))
                {
                    writer.WritePDU(pdu);

                    return(stream.ToArray());
                }
            }
        }
Пример #10
0
        private void server_evClientSubmitSm(object sender, SmppServerClient client, SubmitSm data)
        {
            long messageId = Interlocked.Increment(ref messageIdCounter);

            // You can set your own MessageId
            data.Response.MessageId = messageId.ToString();

            _log.Info("Client {0} sends message From:{1}, To:{2}, Text: {3}",
                      client.RemoteEndPoint, data.SourceAddress, data.DestinationAddress,
                      data.GetMessageText(client.EncodingMapper));


            _messageComposer.AddMessage(data);



            // Set unsuccess response status
            //data.Response.Status = CommandStatus.ESME_RSUBMITFAIL;


            if (data.SMSCReceipt != SMSCDeliveryReceipt.NotRequested)
            {
                //Send Delivery Receipt when required

                string messageText = data.GetMessageText(client.EncodingMapper);

                var dlrBuilder = SMS.ForDeliver()
                                 .From(data.DestinationAddress)
                                 .To(data.SourceAddress)
                                 .Receipt(new Receipt
                {
                    DoneDate   = DateTime.Now,
                    State      = MessageState.Delivered,
                    MessageId  = data.Response.MessageId,
                    ErrorCode  = "0",
                    SubmitDate = DateTime.Now,
                    Text       = messageText.Substring(0, Math.Min(20, messageText.Length))
                });

                if (data.DataCoding == DataCodings.UCS2)
                {
                    //short_message field cannot contain user data longer than 255 octets,
                    //therefore for UCS2 encoding we are sending DLR in message_payload parameter
                    dlrBuilder.MessageInPayload();
                }

                client.Deliver(dlrBuilder).ConfigureAwait(false);
            }
        }
Пример #11
0
        protected override IEnumerable <SendSmPDU> GetPDUs(DataCoding defaultEncoding)
        {
            SubmitSm sm = CreateSubmitSm();

            sm.SourceAddress.Address      = vSourceAddress;
            sm.DestinationAddress.Address = vDestinatinoAddress; // Urgh, typo :(
            sm.DataCoding = defaultEncoding;
            if (!string.IsNullOrEmpty(UserMessageReference))
            {
                var msgIdBytes = SMPPEncodingUtil.GetBytesFromCString(UserMessageReference);
                sm.Tlv.Add(new Lib.Protocol.Tlv.Tlv(Lib.Protocol.Tlv.Tag.user_message_reference, (ushort)msgIdBytes.Length, msgIdBytes));
            }

            if (vRegisterDeliveryNotification)
            {
                sm.RegisteredDelivery = RegisteredDelivery.DeliveryReceipt;
            }

            vMaxMessageLength = GetMaxMessageLength(defaultEncoding, false);
            byte[] bytes = SMPPEncodingUtil.GetBytesFromString(vText, defaultEncoding);

            string uni   = Encoding.Unicode.GetString(bytes);
            string ascii = Encoding.ASCII.GetString(bytes);
            string utf8  = Encoding.UTF8.GetString(bytes);

            // Unicode encoding return 2 items for 1 char
            // We check vText Length first
            if (vText.Length > vMaxMessageLength && bytes.Length > vMaxMessageLength) // Split into multiple!
            {
                var SegID = new Random().Next(1000, 9999);                            // create random SegmentID
                vMaxMessageLength = GetMaxMessageLength(defaultEncoding, true);
                var messages      = Split(vText, vMaxMessageLength);
                var totalSegments = messages.Count;                   // get the number of (how many) parts
                var udh           = new Udh(SegID, totalSegments, 0); // ID, Total, part

                for (int i = 0; i < totalSegments; i++)
                {
                    udh.MessageSequence = i + 1;                          // seq+1 , - parts of the message
                    sm.SetMessageText(messages[i], defaultEncoding, udh); // send parts of the message + all other UDH settings
                    yield return(sm);
                }
            }
            else
            {
                sm.SetMessageBytes(bytes);
                yield return(sm);
            }
        }
        public void SubmitReceived(SubmitSm data)
        {
            var entry = new MessageEntry
            {
                LocalSequence  = data.Header.Sequence,
                LocalMessageId = data.Response.MessageId
            };

            if (!_localSequences.TryAdd(data.Header.Sequence, entry))
            {
            }

            if (!_localMessage.TryAdd(data.Response.MessageId, entry))
            {
            }
        }
Пример #13
0
        public void SendSmsOldAproach()
        {
            SubmitSm sm = new SubmitSm();
            sm.ServiceType = "test";
            sm.UserDataPdu.ShortMessage = Client.GetMessageBytes("Only .Net only C#!!!", DataCodings.Default);
            sm.SourceAddr = "Komisar";
            sm.SourceAddrTon = 0;
            sm.SourceAddrNpi = 1;
            sm.DestAddr = "+37367347545";
            sm.DestAddrTon = 0;
            sm.DestAddrNpi = 1;
            sm.DataCoding = DataCodings.Default;
            sm.RegisteredDelivery = 1;

            var response = Client.Submit(sm);
        }
Пример #14
0
        public void SendSmsOldAproach()
        {
            SubmitSm sm = new SubmitSm();

            sm.ServiceType = "test";
            sm.UserDataPdu.ShortMessage = Client.GetMessageBytes("Only .Net only C#!!!", DataCodings.Default);
            sm.SourceAddr         = "Komisar";
            sm.SourceAddrTon      = 0;
            sm.SourceAddrNpi      = 1;
            sm.DestAddr           = "+37367347545";
            sm.DestAddrTon        = 0;
            sm.DestAddrNpi        = 1;
            sm.DataCoding         = DataCodings.Default;
            sm.RegisteredDelivery = 1;

            var response = Client.Submit(sm);
        }
        private async void WhenReceiveSubmitSmFromClient(object sender, SmppServerClient serverClient, SubmitSm receivedPdu)
        {
            _storage.SubmitReceived(receivedPdu);

            SubmitSm pduToSMSC = receivedPdu.Clone();

            //reset sequence number to allow proxyClient to assigne next sequence number from his generator
            pduToSMSC.Header.Sequence = 0;

            SubmitSmResp respFromSMSC = await _proxyClient.Submit(pduToSMSC);

            _storage.SubmitForwarded(receivedPdu, respFromSMSC);

            if (receivedPdu.SMSCReceipt == SMSCDeliveryReceipt.NotRequested)
            {
                _storage.DeliveryReceiptNotRequested(receivedPdu.Response.MessageId);
            }
        }
Пример #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            SMPPEncodingUtil.UCS2Encoding = Encoding.BigEndianUnicode;

            mmSessionBindInfo                  = new SessionBindInfo();
            mmSessionBindInfo.SystemID         = "********";
            mmSessionBindInfo.Password         = "******";
            mmSessionBindInfo.ServerName       = "*******";
            mmSessionBindInfo.Port             = 1234;
            mmSessionBindInfo.InterfaceVersion = InterfaceVersion.v34;
            mmSessionBindInfo.SystemType       = "SMPP";
            mmSessionBindInfo.AllowTransmit    = true;
            mmSessionBindInfo.AllowReceive     = true;
            mmSessionBindInfo.AddressNpi       = NumberingPlanIndicator.Unknown;
            mmSessionBindInfo.AddressTon       = TypeOfNumber.Unknown;
            mmSession              = SmppClientSession.Bind(mmSessionBindInfo, 0);
            mmSession.PduReceived += new EventHandler <PduReceivedEventArgs>(PduReceivedEventHander);


            mmSubmitSm = new SubmitSm();

            mmSubmitSm.DataCoding                 = DataCoding.UCS2;
            mmSubmitSm.ServiceType                = "CMT";      // cellular  messaging
            mmSubmitSm.RegisteredDelivery         = RegisteredDelivery.DeliveryReceipt;
            mmSubmitSm.DestinationAddress.Address = "********"; // destination
            mmSubmitSm.DestinationAddress.Npi     = NumberingPlanIndicator.ISDN;
            mmSubmitSm.DestinationAddress.Ton     = TypeOfNumber.International;
            mmSubmitSm.SourceAddress.Npi          = NumberingPlanIndicator.Unknown;
            mmSubmitSm.SourceAddress.Ton          = TypeOfNumber.Aphanumeric;
            mmSubmitSm.SourceAddress.Address      = "*********";

            try
            {
                mmSubmitSm.SetMessageText(Encoding.UTF8.GetString(Encoding.UTF8.GetBytes("Текст")), DataCoding.UCS2);
                mmSubmitSmResp = mmSession.SendPdu(mmSubmitSm) as SubmitSmResp;
                MessageBox.Show(DateTime.Now.ToString());
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }

            MessageBox.Show(mmSubmitSmResp.MessageID + " , " + mmSubmitSmResp.Header.ErrorCode.ToString() + " , " + mmSubmitSm.GetMessageText());
        }
Пример #17
0
        private static void SendMessage(string command)
        {
            string[] parts       = command.Split(' ');
            string   phoneNumber = parts[1];
            string   message     = string.Join(" ", parts, 2, parts.Length - 2);

            // This is set in the Submit PDU to the SMSC
            // If you are responding to a received message, make this the same as the received message
            DataCodings submitDataCoding = DataCodings.Default;

            // Use this to encode the message
            // We need to know the actual encoding.
            DataCodings encodeDataCoding = DataCodings.ASCII;

            // There is a default encoding set for each connection. This is used if the encodeDataCoding is Default

            SubmitSm     submitSm     = null;
            SubmitSmResp submitSmResp = null;

            connectionManager.SendMessage(phoneNumber, null, Ton.National, Npi.ISDN, submitDataCoding, encodeDataCoding, message, out submitSm, out submitSmResp);
            Console.Write("submitSm:{0}, submitSmResp:{1}, messageId:{2}", submitSm.DestAddr, submitSmResp.Status, submitSmResp.MessageId);
        }
Пример #18
0
        protected override IEnumerable <SendSmPdu> GetPdUs(DataCoding defaultEncoding)
        {
            SubmitSm sm = new SubmitSm();

            sm.SourceAddress.Address      = VSourceAddress;
            sm.DestinationAddress.Address = VDestinatinoAddress; // Urgh, typo :(
            sm.DataCoding = defaultEncoding;
            if (VRegisterDeliveryNotification)
            {
                sm.RegisteredDelivery = RegisteredDelivery.DeliveryReceipt;
            }

            _vMaxMessageLength = GetMaxMessageLength(defaultEncoding, false);
            byte[] bytes = SmppEncodingUtil.GetBytesFromString(_vText, defaultEncoding);

            // Unicode encoding return 2 items for 1 char
            // We check vText Length first
            if (_vText.Length > _vMaxMessageLength && bytes.Length > _vMaxMessageLength) // Split into multiple!
            {
                var segId = new Random().Next(1000, 9999);                               // create random SegmentID
                _vMaxMessageLength = GetMaxMessageLength(defaultEncoding, true);
                var messages      = Split(_vText, _vMaxMessageLength);
                var totalSegments = messages.Count;                   // get the number of (how many) parts
                var udh           = new Udh(segId, totalSegments, 0); // ID, Total, part

                for (int i = 0; i < totalSegments; i++)
                {
                    udh.MessageSequence = i + 1;                          // seq+1 , - parts of the message
                    sm.SetMessageText(messages[i], defaultEncoding, udh); // send parts of the message + all other UDH settings
                    yield return(sm);
                }
            }
            else
            {
                sm.SetMessageBytes(bytes);
                yield return(sm);
            }
        }
Пример #19
0
        private void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            SubmitSm            submitSm         = null;
            SubmitSmResp        submitSmResp     = null;
            List <SubmitSm>     submitSmList     = null;
            List <SubmitSmResp> submitSmRespList = null;
            var QMessages = new OutSMSRepo(db).GetPendingSMSQueue();

            //AddLog("dd", "worker work", "OUT", "4003", Color.Black);
            if (!object.ReferenceEquals(QMessages, null) && (QMessages.Count > 0))
            {
                while (QMessages.Count > 0)
                {
                    if (ContinueSending)
                    {
                        var OutMsg   = QMessages.Dequeue();
                        int retvalue = -1;
                        if (!string.IsNullOrEmpty(OutMsg.Receiver) && !string.IsNullOrEmpty(OutMsg.Message))
                        {
                            if (OutMsg.Message.Length <= 70)
                            {
                                retvalue = connectionManager.SendMessage(OutMsg.Receiver, null, Ton.Unknown, Npi.Unknown, DataCodings.UCS2
                                                                         , DataCodings.UCS2, OutMsg.Message, out submitSm, out submitSmResp);
                            }
                            else
                            {
                                retvalue = connectionManager.SendMessageLarge(OutMsg.Receiver, null, Ton.Unknown, Npi.Unknown, DataCodings.UCS2
                                                                              , DataCodings.UCS2, OutMsg.Message, out submitSmList, out submitSmRespList);
                            }
                            AddLog(OutMsg.Receiver, OutMsg.Message, "OUT", OutMsg.Sender, "Bw_DoWork", Color.Black);
                            new OutSMSRepo(db).RemoveMessage(OutMsg.Id);
                            //Thread.Sleep(100);
                        }
                    }
                }
            }
        }
        public void SubmitForwarded(SubmitSm req, SubmitSmResp remoteResp)
        {
            MessageEntry entry;

            if (!_localSequences.TryGetValue(req.Header.Sequence, out entry))
            {
                throw new Exception("Cannot find message with local sequence " + req.Header.Sequence);
            }

            entry.RemoteSequence  = remoteResp.Header.Sequence;
            entry.RemoteMessageId = remoteResp.MessageId;

            MessageEntry remoteEntry;

            if (_remoteMessage.TryRemove(remoteResp.MessageId, out remoteEntry))
            {
                entry.Receipt = remoteEntry.Receipt;
                OnReceiptReadyForForward(entry);
            }
            else
            {
                _remoteMessage.TryAdd(remoteResp.MessageId, entry);
            }
        }
Пример #21
0
 private async void WhenServerReceivesPDU(object sender, SmppServerClient serverClient, SubmitSm data)
 {
     if (data.RegisteredDelivery == 1)
     {
         //Send Delivery Receipt when required
         await serverClient.Deliver(
             SMS.ForDeliver()
             .From(data.SourceAddress)
             .To(data.DestinationAddress)
             .Coding(data.DataCoding)
             .Receipt(new Receipt
         {
             DoneDate   = DateTime.Now,
             State      = MessageState.Delivered,
             MessageId  = data.Response.MessageId,
             ErrorCode  = "0",
             SubmitDate = DateTime.Now
         }
                      )
             )
         .ConfigureAwait(false);
     }
 }
Пример #22
0
        /// <summary>
        /// Gets PDU from stream, parses
        /// </summary>
        /// <param name="pdu">PDU to handle</param>
        private void PduHandler(string pdu)
        {
            string response = string.Empty;

            Events.LogChannelEvent(channel_name, "Receiving [" + Common.command_id.Values[Common.command_id.IndexOfKey(uint.Parse(pdu.Substring(8, 8), System.Globalization.NumberStyles.HexNumber))] + "]", debug ? pdu : "");

            switch (Common.command_id.Values[Common.command_id.IndexOfKey(uint.Parse(pdu.Substring(8, 8), System.Globalization.NumberStyles.HexNumber))])
            {
            case "generic_nack":
                // they do not understand my command
                // may be a bug in my pdu
                break;

            case "bind_transceiver_resp":
                var bind_transceiver = new BindTransceiverResp(pdu);
                commands_queue.Remove(bind_transceiver.sequence_number);
                if (bind_transceiver.command_status != 0)
                {
                    Events.LogChannelEvent(channel_name, "Error: " + Common.command_status[bind_transceiver.command_status].description);
                    if (!is_server)
                    {
                        // try to reconnect
                        Thread.Sleep(reconnectDelay);
                        Task.Run(() => { Gate.Clients[channel_name].Connect(); });
                    }
                }
                break;

            case "bind_transmitter_resp":
                var bind_transmitter = new BindTransmitterResp(pdu);
                commands_queue.Remove(bind_transmitter.sequence_number);
                if (bind_transmitter.command_status != 0)
                {
                    Events.LogChannelEvent(channel_name, "Error: " + Common.command_id[bind_transmitter.command_status]);

                    if (!is_server)
                    {
                        Thread.Sleep(reconnectDelay);
                        Task.Run(() => { Gate.Clients[channel_name].Connect(); });
                    }
                }

                break;

            case "bind_receiver_resp":
                var bind_receiver = new BindReceiverResp(pdu);
                commands_queue.Remove(bind_receiver.sequence_number);
                if (bind_receiver.command_status != 0)
                {
                    Events.LogChannelEvent(channel_name, "Error: " + Common.command_id[bind_receiver.command_status]);
                    Quit();

                    if (!is_server)
                    {
                        Thread.Sleep(reconnectDelay);
                        Task.Run(() => { Gate.Clients[channel_name].Connect(); });
                    }
                }

                break;

            case "submit_sm":
                var submit_sm_s      = new SubmitSm(pdu);
                var submit_sm_resp_s = new SubmitSmResp();

                submit_sm_resp_s.MessageID       = Guid.NewGuid().ToString("n");
                submit_sm_resp_s.sequence_number = submit_sm_s.sequence_number;
                response = submit_sm_resp_s.Encode();

                Events.LogChannelEvent(channel_name, "Message received from " + submit_sm_s.Sender + " to " + submit_sm_s.Recipient);
                Events.LogChannelEvent(channel_name, "Sending [submit_sm_resp]");
                SendPDU(response);

                if (submit_sm_s.isMultipart)
                {
                    int parts = 0;
                    lock (multipart_messages)
                    {
                        multipart_messages.Add(submit_sm_s.MultipartMessage);

                        foreach (Common.MultipartMessage mm in multipart_messages)
                        {
                            if (mm.reference == submit_sm_s.MultipartMessage.reference)
                            {
                                parts++;
                            }
                        }
                    }
                    if (parts == submit_sm_s.MultipartMessage.num_of_parts)
                    {
                        var for_remove    = new List <Common.MultipartMessage>();
                        var short_message = new StringBuilder();
                        var str           = new string[parts];
                        lock (multipart_messages)
                        {
                            foreach (Common.MultipartMessage mm in multipart_messages)
                            {
                                if (mm.reference == submit_sm_s.MultipartMessage.reference)
                                {
                                    for_remove.Add(mm);
                                    try
                                    {
                                        str[mm.part_num - 1] = mm.short_message;
                                    }
                                    catch (Exception e1)
                                    {
                                        Events.LogEvent(LogEvent.Level.Error, channel_name + " - " + e1 + "  " + pdu);
                                    }
                                }
                            }

                            foreach (Common.MultipartMessage k in for_remove)
                            {
                                multipart_messages.Remove(k);
                            }
                        }
                        // can be required
                        // short_message.Append("(" + submit_sm_s.MultipartMessage.reference.ToString() + ") ");
                        try
                        {
                            for (int k = 0; k < parts; k++)
                            {
                                short_message.Append(str[k]);
                            }
                            submit_sm_s.Body = short_message.ToString();
                        }
                        catch (Exception e1)
                        {
                            Events.LogEvent(LogEvent.Level.Error, channel_name + " - " + e1 + "  " + pdu);
                        }

                        Events.LogNewMessageEvent(channel_name, submit_sm_resp_s.MessageID, submit_sm_s.Sender, submit_sm_s.Recipient, submit_sm_s.Body, submit_sm_s.BodyFormat, submit_sm_s.RegisteredDelivery);
                    }
                }
                else
                {
                    Events.LogNewMessageEvent(channel_name, submit_sm_resp_s.MessageID, submit_sm_s.Sender, submit_sm_s.Recipient, submit_sm_s.Body, submit_sm_s.BodyFormat, submit_sm_s.RegisteredDelivery);
                }
                break;

            case "submit_sm_resp":
                try
                {
                    var submit_sm_resp = new SubmitSmResp(pdu);
                    if (submitted_messages.ContainsKey(submit_sm_resp.sequence_number))
                    {
                        var submitSmRespMessageId = "";
                        if (!string.IsNullOrEmpty(submit_sm_resp.MessageID))
                        {
                            submitSmRespMessageId = submit_sm_resp.MessageID;
                        }

                        if (submit_sm_resp.command_status == 0)
                        {
                            Events.LogMessageChangeStatusEvent(
                                submitted_messages[submit_sm_resp.sequence_number].message_id, Common.MessageStatus.sent, submitSmRespMessageId);
                        }
                        else
                        {
                            if (Common.command_status.ContainsKey(submit_sm_resp.command_status))
                            {
                                Events.LogMessageChangeStatusEvent(
                                    submitted_messages[submit_sm_resp.sequence_number].message_id,
                                    Common.MessageStatus.rejected, submitSmRespMessageId);
                            }
                            else
                            {
                                Events.LogMessageChangeStatusEvent(
                                    submitted_messages[submit_sm_resp.sequence_number].message_id,
                                    Common.MessageStatus.sent);
                            }
                        }
                        submitted_messages.Remove(submit_sm_resp.sequence_number);
                    }

                    if (submit_sm_resp.command_status != 0)
                    {
                        Events.LogChannelEvent(channel_name, "Error sending: " + submit_sm_resp.command_status);
                    }
                    else
                    {
                        Events.LogChannelEvent(channel_name, "Message reference: " + submit_sm_resp.MessageID);
                    }
                }
                catch (Exception e1)
                {
                    Events.LogEvent(LogEvent.Level.Error, channel_name + " - " + e1.ToString());
                }
                break;

            case "enquire_link":
                var enquire_link      = new EnquireLink(pdu);
                var enquire_link_resp = new EnquireLinkResp();

                enquire_link_resp.sequence_number = enquire_link.sequence_number;
                response = enquire_link_resp.Encode();
                SendPDU(response);
                Events.LogChannelEvent(channel_name, "Sending [enquire_link_resp]", debug ? response : "");
                break;

            case "enquire_link_resp":
                var enquire_link_resp_o = new EnquireLinkResp(pdu);
                commands_queue.Remove(enquire_link_resp_o.sequence_number);
                break;

            case "deliver_sm":
                DeliverSm deliver_sm;
                try
                {
                    deliver_sm        = new DeliverSm(pdu);
                    deliver_sm.Is8bit = use8bit;
                    deliver_sm.Decode();
                }
                catch (CommandLengthException)
                {
                    Events.LogEvent(LogEvent.Level.Error, channel_name + ". Command length error.");
                    break;
                }
                catch (Exception e1)
                {
                    Events.LogEvent(LogEvent.Level.Error, channel_name + ". Error: " + e1.Message);
                    break;
                }

                // Send Resp
                var deliver_sm_resp = new DeliverSmResp();
                deliver_sm_resp.MessageID       = Guid.NewGuid().ToString("n");
                deliver_sm_resp.sequence_number = deliver_sm.sequence_number;
                response = deliver_sm_resp.Encode();

                Events.LogChannelEvent(channel_name, "Sending [deliver_sm_resp]", debug ? response : "");
                SendPDU(response);

                // Multipart message
                if (deliver_sm.isMultipart)
                {
                    int parts = 0;
                    lock (multipart_messages)
                    {
                        multipart_messages.Add(deliver_sm.MultipartMessage);


                        foreach (Common.MultipartMessage mm in multipart_messages)
                        {
                            if (mm.reference == deliver_sm.MultipartMessage.reference)
                            {
                                parts++;
                            }
                        }
                    }
                    if (parts == deliver_sm.MultipartMessage.num_of_parts)
                    {
                        List <Common.MultipartMessage> for_remove = new List <Common.MultipartMessage>();
                        StringBuilder short_message = new StringBuilder();
                        string[]      str           = new string[parts];

                        lock (multipart_messages)
                        {
                            foreach (Common.MultipartMessage mm in multipart_messages)
                            {
                                if (mm.reference == deliver_sm.MultipartMessage.reference)
                                {
                                    for_remove.Add(mm);
                                    try
                                    {
                                        str[mm.part_num - 1] = mm.short_message;
                                    }
                                    catch (Exception e1)
                                    {
                                        Events.LogEvent(LogEvent.Level.Error, channel_name + " - " + e1.ToString() + "  " + pdu);
                                    }
                                }
                            }

                            foreach (Common.MultipartMessage k in for_remove)
                            {
                                multipart_messages.Remove(k);
                            }
                        }

                        try
                        {
                            for (int k = 0; k < parts; k++)
                            {
                                short_message.Append(str[k]);
                            }
                            deliver_sm.Body = short_message.ToString();
                        }
                        catch (Exception e1)
                        {
                            Events.LogEvent(LogEvent.Level.Error, channel_name + " - " + e1.ToString() + "  " + pdu);
                        }
                    }
                    else
                    {
                        // Multipart message is not built yet, wait for the rest
                        break;
                    }
                }

                // Delivery report
                if (deliver_sm.ESMClass == 4)
                {
                    Events.LogChannelEvent(channel_name, "Message ref: " + deliver_sm.Reference + " " + deliver_sm.DeliveryStatus, debug ? pdu : "");
                    if (deliver_sm.DeliveryStatus.ToUpper() == "DELIVR")
                    {
                        Events.LogMessageDeliverReportEvent(deliver_sm.Reference, Common.MessageStatus.delivered_ACK_received);
                    }
                    if (deliver_sm.DeliveryStatus.ToUpper() == "EXPIRE")
                    {
                        Events.LogMessageDeliverReportEvent(deliver_sm.Reference, Common.MessageStatus.ACK_expired);
                    }
                    if (deliver_sm.DeliveryStatus.ToUpper() == "UNKNOW")
                    {
                        Events.LogMessageDeliverReportEvent(deliver_sm.Reference, Common.MessageStatus.unknown_recipient);
                    }
                    if (deliver_sm.DeliveryStatus.ToUpper() == "ACCEPT")
                    {
                        Events.LogMessageDeliverReportEvent(deliver_sm.Reference, Common.MessageStatus.received_routed);
                    }
                    if (deliver_sm.DeliveryStatus.ToUpper() == "REJECT")
                    {
                        Events.LogMessageDeliverReportEvent(deliver_sm.Reference, Common.MessageStatus.rejected);
                    }
                    if (deliver_sm.DeliveryStatus.ToUpper() == "UNDELI")
                    {
                        Events.LogMessageDeliverReportEvent(deliver_sm.Reference, Common.MessageStatus.message_undeliverable);
                    }

                    break;
                }

                // Log message
                Events.LogChannelEvent(channel_name, "Message received from " + deliver_sm.Sender + " to " + deliver_sm.Recipient, debug ? pdu : "");
                Events.LogNewMessageEvent(channel_name, deliver_sm_resp.MessageID, deliver_sm.Sender, deliver_sm.Recipient, deliver_sm.Body, deliver_sm.BodyFormat, deliver_sm.RegisteredDelivery);

                break;

            case "deliver_sm_resp":
                try
                {
                    var deliver_sm_resp2 = new DeliverSmResp(pdu);
                    if (submitted_messages.ContainsKey(deliver_sm_resp2.sequence_number))
                    {
                        var deliverSmRespMessageId = "";
                        if (!string.IsNullOrEmpty(deliver_sm_resp2.MessageID))
                        {
                            deliverSmRespMessageId = deliver_sm_resp2.MessageID;
                        }

                        if (deliver_sm_resp2.command_status == 0)
                        {
                            if (registered_delivery != 1 && submitted_messages[deliver_sm_resp2.sequence_number].registered_delivery)
                            {
                                Events.LogMessageChangeStatusEvent(submitted_messages[deliver_sm_resp2.sequence_number].message_id, Common.MessageStatus.sent, deliverSmRespMessageId);
                            }
                        }
                        else
                        {
                            if (Common.command_status.ContainsKey(deliver_sm_resp2.command_status))
                            {
                                Events.LogMessageChangeStatusEvent(
                                    submitted_messages[deliver_sm_resp2.sequence_number].message_id,
                                    Common.MessageStatus.rejected, deliverSmRespMessageId);
                            }
                            else
                            {
                                Events.LogMessageChangeStatusEvent(
                                    submitted_messages[deliver_sm_resp2.sequence_number].message_id,
                                    Common.MessageStatus.sent, deliverSmRespMessageId);
                            }
                        }
                        submitted_messages.Remove(deliver_sm_resp2.sequence_number);
                    }

                    if (deliver_sm_resp2.command_status != 0)
                    {
                        Events.LogChannelEvent(channel_name, "Error sending: " + deliver_sm_resp2.command_status);
                    }
                    else
                    {
                        Events.LogChannelEvent(channel_name, "Message reference: " + deliver_sm_resp2.MessageID);
                    }
                }
                catch (Exception e1)
                {
                    Events.LogEvent(LogEvent.Level.Error, channel_name + " - " + e1);
                }
                break;

            case "data_sm":
                var data_sm_s      = new DataSm(pdu);
                var data_sm_resp_s = new DataSmResp();

                data_sm_resp_s.MessageID       = Guid.NewGuid().ToString("n");
                data_sm_resp_s.sequence_number = data_sm_s.sequence_number;
                response = data_sm_resp_s.Encode();

                Events.LogChannelEvent(channel_name, "Message received from " + data_sm_s.Sender + " to " + data_sm_s.Recipient, debug ? pdu : "");
                Events.LogChannelEvent(channel_name, "Sending [data_sm_resp]");
                SendPDU(response);

                Events.LogNewMessageEvent(channel_name, data_sm_resp_s.MessageID, data_sm_s.Sender, data_sm_s.Recipient, data_sm_s.Body, data_sm_s.BodyFormat, data_sm_s.RegisteredDelivery);

                break;

            case "data_sm_resp":
                try
                {
                    var data_sm_resp = new DataSmResp(pdu);
                    if (submitted_messages.ContainsKey(data_sm_resp.sequence_number))
                    {
                        var dataSmRespMessageId = "";
                        if (!string.IsNullOrEmpty(data_sm_resp.MessageID))
                        {
                            dataSmRespMessageId = data_sm_resp.MessageID;
                        }

                        if (data_sm_resp.command_status == 0)
                        {
                            if (registered_delivery != 1 && submitted_messages[data_sm_resp.sequence_number].registered_delivery)
                            {
                                Events.LogMessageChangeStatusEvent(submitted_messages[data_sm_resp.sequence_number].message_id, Common.MessageStatus.sent, dataSmRespMessageId);
                            }
                        }
                        else
                        {
                            if (Common.command_status.ContainsKey(data_sm_resp.command_status))
                            {
                                Events.LogMessageChangeStatusEvent(submitted_messages[data_sm_resp.sequence_number].message_id, Common.MessageStatus.rejected, dataSmRespMessageId);
                            }
                            else
                            {
                                Events.LogMessageChangeStatusEvent(submitted_messages[data_sm_resp.sequence_number].message_id, Common.MessageStatus.sent, dataSmRespMessageId);
                            }
                        }
                        submitted_messages.Remove(data_sm_resp.sequence_number);
                    }

                    if (data_sm_resp.command_status != 0)
                    {
                        Events.LogChannelEvent(channel_name, "Error sending: " + data_sm_resp.command_status);
                    }
                    else
                    {
                        Events.LogChannelEvent(channel_name, "Message reference: " + data_sm_resp.MessageID);
                    }
                }
                catch (Exception e1)
                {
                    Events.LogEvent(LogEvent.Level.Error, channel_name + ". error: " + e1);
                }
                break;

            case "unbind":
                var unbind      = new Unbind(pdu);
                var unbind_resp = new UnbindResp();
                unbind_resp.sequence_number = unbind.sequence_number;
                response = unbind_resp.Encode();
                SendPDU(response);

                Events.LogChannelEvent(channel_name, "Sending [unbind_resp]", debug ? response : "");

                enquire_link_timer.Stop();
                timeout_timer.Stop();

                tcp_stream.Close();
                tcp_client.Close();

                Gate.Clients.Remove(channel_name);
                Gate.Servers.Remove(channel_name);

                Events.LogChannelEvent(channel_name, "Disconnected");

                // should reconnect if it was a client
                if (!is_server)
                {
                    Thread.Sleep(10000);
                    Task.Run(() => { Gate.Clients[channel_name].Connect(); });
                }
                break;

            case "unbind_resp":
                ;
                break;

            default:
                Events.LogChannelEvent(channel_name, "Receiving unknown command", pdu);
                break;
            }
        }
Пример #23
0
        /// <summary>
        /// Sends message
        /// </summary>
        /// <param name="message_id">Unique message id</param>
        /// <param name="sender">Sender</param>
        /// <param name="recipient">Recipient</param>
        /// <param name="body">body</param>
        /// <param name="body_format">Body format. unicode,ascii,wap_push</param>
        /// <param name="delivery_report">Request delivery report</param>
        /// <returns>0 if successful,
        /// 1 - No active connection,
        /// 2 - Too many messages per second
        /// 3 - Duplicate sequence number </returns>
        public virtual int SubmitSm(int message_id, string sender, string recipient, string body, string body_format = "ascii", bool delivery_report = true)
        {
            if (!connected)
            {
                Events.LogMessageChangeStatusEvent(message_id, Common.MessageStatus.received_route_failure);
                return(1);
            }

            // check for max sms count
            if (max_threads != 0)
            {
                int now_second = DateTime.Now.Second;
                if (now_second != last_second)
                {
                    last_second             = now_second;
                    sent_during_last_second = 0;
                }
                else
                {
                    sent_during_last_second++;
                }
                if (max_threads < sent_during_last_second)
                {
                    // messages should be resubmitted later
                    Events.LogMessageChangeStatusEvent(message_id, Common.MessageStatus.queued);

                    return(2); // too many SMS per second
                }
            }

            var submit_sm = new SubmitSm();

            while (submitted_messages.ContainsKey(sequence_number))
            {
                sequence_number++;
            }

            submit_sm.sequence_number = sequence_number;
            var sm = new submitted_message();

            sm.message_id          = message_id;
            sm.submitted_time      = DateTime.Now;
            sm.registered_delivery = delivery_report;
            try
            {
                submitted_messages.Add(submit_sm.sequence_number, sm);
            }
            catch (ArgumentException)
            {
                Events.LogChannelEvent(channel_name, "Duplicate sequence number.");
                Events.LogMessageChangeStatusEvent(message_id, Common.MessageStatus.queued);
                return(3);
            }

            submit_sm.Sender     = sender;
            submit_sm.Recipient  = recipient;
            submit_sm.Body       = body;
            submit_sm.BodyFormat = body_format;
            submit_sm.Is8bit     = use8bit;

            submit_sm.ServiceType = system_type;

            submit_sm.SourceAddrTON = source_ton;
            submit_sm.SourceAddrNPI = source_npi;

            submit_sm.DestAddrTON = destination_ton;
            submit_sm.DestAddrNPI = destination_npi;

            submit_sm.SplitBaseASCII = split_base_ascii;

            submit_sm.RegisteredDelivery = delivery_report ? 1 : 0;

            submit_sm.LargeMessageHandleMethod = large_message;
            multipart_sequence_number++;
            if (multipart_sequence_number == 255)
            {
                multipart_sequence_number = 1;
            }
            submit_sm.MultipartSequenceNumber = multipart_sequence_number;
            string[] pdu = submit_sm.EncodeM();

            Events.LogChannelEvent(channel_name, "Sending from " + sender + " to " + recipient);

            var k = pdu.Length;

            foreach (var part in pdu)
            {
                Events.LogChannelEvent(channel_name, "Sending [submit_sm]", debug ? part : "");

                SendPDU(part);
                if (k != 1)
                {
                    Thread.Sleep(multypart_delay);
                }
                k--;

                if (registered_delivery == 1 && delivery_report)
                {
                    Events.LogMessageChangeStatusEvent(message_id, Common.MessageStatus.submitted_waiting_for_ACK);
                }
                else
                {
                    Events.LogMessageChangeStatusEvent(message_id, Common.MessageStatus.received_routed);
                }
            }

            return(0);
        }
 //How to set MessageId
 //
 //<SetMessageIdForSubmitSm>
 private void ServerOnClientSubmitSm(object sender, SmppServerClient client, SubmitSm data)
 {
     data.Response.MessageId = Guid.NewGuid().ToString().Substring(0, 8);
 }