Exemple #1
0
        public ShortMessageCollection ReadSMS()
        {
            ShortMessageCollection messages = null;

            try
            {
                port.WriteLine("AT+CMGF=1" + System.Environment.NewLine);
                port.WriteLine("AT+CMGL=\"ALL\"\r" + System.Environment.NewLine);

                Thread.Sleep(1000);
                TimeOut();

                messages = ParseMessages(response);
                response = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
        }
        public ShortMessageCollection ReadSMS(string p_strCommand)
        {
            // Set up the phone and read the messages
            ShortMessageCollection messages = null;

            try
            {
                #region Execute Command
                // Check connection
                ExecCommand("AT", 300, "No phone connected");
                // Use message format "Text mode"
                ExecCommand("AT+CMGF=1", 300, "Failed to set message format.");
                // Read the messages
                string input = ExecCommand(p_strCommand, 500, "Failed to read the messages.");
                #endregion

                #region Parse messages
                messages = ParseMessages(input);
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
        }
        public ShortMessageCollection ReadSMS(SerialPort port, string p_strCommand)
        {
            ShortMessageCollection messages = null;

            try
            {
                // Check connection
                ExecCommand(port, "AT", 300, "No phone connected");
                // Use message format "Text mode"
                ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
                // Use character set "PCCP437"
                //ExecCommand(port, "AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
                // Select SIM storage
                ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
                // Read the messages
                String input = ExecCommand(port, p_strCommand, 5000, "Failed to read the messages.");

                messages = ParseMessages(input);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
        }
        private bool ParseMessages(string input, out ShortMessageCollection messages)
        {
            messages = new ShortMessageCollection();

            try
            {
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");

                Match m = r.Match(input);

                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage(m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value,
                                                        m.Groups[4].Value, m.Groups[5].Value, m.Groups[6].Value);

                    messages.Add(msg);

                    m = m.NextMatch();
                }
            }
            catch (Exception ex)
            {
                messages = null;

                return(false);
            }

            return(true);
        }
Exemple #5
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();

            try
            {
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
                Match m = r.Match(input);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();
                    //msg.Index = int.Parse(m.Groups[1].Value);
                    msg.Index    = m.Groups[1].Value;
                    msg.Status   = m.Groups[2].Value;
                    msg.Sender   = m.Groups[3].Value;
                    msg.Alphabet = m.Groups[4].Value;
                    msg.Sent     = m.Groups[5].Value;
                    msg.Message  = m.Groups[6].Value;
                    messages.Add(msg);

                    m = m.NextMatch();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(messages);
        }
        public ShortMessageCollection ReadSMS(SerialPort port, string strPortName, string strBaudRate)
        {
            //lvwMessages.Items.Clear();
            //Update();

            // Set up the phone and read the messages
            ShortMessageCollection messages = null;

            try
            {
                #region Open Port
                //this.port = OpenPort(strPortName, strBaudRate);
                #endregion

                #region Execute Command
                // Check connection
                ExecCommand(port, "AT", 300, "No phone connected at " + strPortName + ".");
                // Use message format "Text mode"
                ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
                // Use character set "ISO 8859-1"
                //ExecCommand("AT+CSCS=\"8859-1\"", 300, "Failed to set character set."); //error
                ExecCommand(port, "AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
                // Select SIM storage
                ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
                // Read the messages
                string input = ExecCommand(port, "AT+CMGL=\"ALL\"", 5000, "Failed to read the messages.");
                #endregion

                #region Parse messages
                messages = ParseMessages(input);
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (port != null)
                {
                    #region Close Port
                    //ClosePort(this.port);
                    //port.Close();
                    //port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
                    //this.port = null;
                    #endregion
                }
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
            //DisplayMessages(messages);
        }
Exemple #7
0
        private void btnReadSMS_Click(object sender, EventArgs e)
        {
            try
            {
                //count SMS
                int uCountSMS = objclsSMS.CountSMSmessages(this.port);
                if (uCountSMS > 0)
                {
                    #region Command

                    string strCommand = "AT+CMGL=\"ALL\"";

                    if (this.rbReadAll.Checked)
                    {
                        strCommand = "AT+CMGL=\"ALL\"";
                    }
                    else if (this.rbReadUnRead.Checked)
                    {
                        strCommand = "AT+CMGL=\"REC UNREAD\"";
                    }
                    else if (this.rbReadStoreSent.Checked)
                    {
                        strCommand = "AT+CMGL=\"STO SENT\"";
                    }
                    else if (this.rbReadStoreUnSent.Checked)
                    {
                        strCommand = "AT+CMGL=\"STO UNSENT\"";
                    }

                    #endregion Command

                    // If SMS exist then read SMS

                    #region Read SMS

                    //.............................................. Read all SMS ....................................................
                    objShortMessageCollection = objclsSMS.ReadSMS(this.port, strCommand);
                    foreach (ShortMessage msg in objShortMessageCollection)
                    {
                        ListViewItem item = new ListViewItem(new string[] { msg.Index, msg.Sent, msg.Sender, msg.Message });
                        item.Tag = msg;
                        lvwMessages.Items.Add(item);
                    }

                    #endregion Read SMS
                }
                else
                {
                    lvwMessages.Clear();
                    //MessageBox.Show("There is no message in SIM");
                    this.statusBar1.Text = "There is no message in SIM";
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message);
            }
        }
        static void Main(string[] args)
        {
            while (true)
            {
                ModemSMS sms = new ModemSMS();
                sms.OpenConnection();
                ShortMessageCollection      smsData = sms.ReadSMS("AT+CMGL=\"ALL\"");
                Dictionary <string, string> smsList = new Dictionary <string, string>();
                foreach (ShortMessage aMessage in smsData)
                {
                    smsList.Add(aMessage.Index, aMessage.Message);
                    Console.WriteLine(aMessage.Message);
                }


                if (smsData.Count != 0)
                {
                    foreach (ShortMessage aMessage in smsData)
                    {
                        sms.DeleteSMS("AT+CMGD=" + aMessage.Index + ",0");
                        sms.SendSMS(aMessage.Sender, "Your SMS Received...");
                        Console.WriteLine("Message Sent to: " + aMessage.Sender);
                    }
                }
                sms.CloseConnection();
                System.Threading.Thread.Sleep(4000);
            }

            //sms.DeleteSMS("AT+CMGD=<index>,0");
            //sms.DeleteSMS("AT+CMGD=1,4");
            //String command = "AT^CURC=0";
            //sms.ExecCommand(command,300,"Error");

            //System.Threading.Thread.Sleep(2000);
            //while (true)
            //{
            //    smsList = new Dictionary<string, string>();
            //    smsData = sms.ReadSMS("AT + CMGL =\"ALL\"");
            //    if(smsData.Count != 0)
            //    {
            //        foreach(ShortMessage aMessage in smsData)
            //{
            //sms.DeleteSMS("AT+CMGD="+aMessage.Index+",0");
            //sms.SendSMS(aMessage.Sender, "Your SMS Received...");
            //Console.WriteLine("Message Sent to: " + aMessage.Sender);
            //        }


            //    }
            //    Console.WriteLine(smsData.Count);
            //    System.Threading.Thread.Sleep(2000);
            //}

            //bool send = sms.SendSMS("+8801926662274", "Dear Atique Reza Chowdhury, This is an auto generated sms. :)");

            Console.ReadKey();
        }
Exemple #9
0
        public ShortMessageCollection ReadSMS(SerialPort port, string p_strCommand)
        {
            // Set up the phone and read the messages
            ShortMessageCollection messages = null;

            try
            {
                #region Execute Command
                // Check connection
                ExecCommand(port, "AT", 300, "No phone connected");

                // Use message format "Text mode"
                ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");

                // Use character set "PCCP437"
                ExecCommand(port, "AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");

                // Select SIM storage
                ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");

                // Read the messages
                string input = ExecCommand(port, p_strCommand, 5000, "Failed to read the messages.");

                #endregion


                #region Execute PDU Command
                ExecCommand(port, "AT", 300, "No phone connected");
                ExecCommand(port, "AT+CMGF=0", 300, "Failed to set message format.");  //PDU Format
                var result = ExecCommand(port, "AT+CSCS=\"GSM\"", 300, "Failed to set character set.");
                ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");

                input = ExecCommand(port, "AT+CMGL=4", 5000, "Failed to read the messages.");

                #endregion

                #region Parse messages
                messages = ParseMessages(input);
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
        }
Exemple #10
0
        private void btnTestComclick(object sender, System.EventArgs e)
        {
            COM port = new COM();

            port.ReadSMS(port.COMSMS);
            #region Read SMS
            //.............................................. Read all SMS ....................................................
            ShortMessageCollection objShortMessageCollection = port.ReadSMS(port.COMSMS);
            //string[] strmsg;
            foreach (ShortMessage msg in objShortMessageCollection)
            {
                messageList = new string[] { msg.Index, msg.Sent, msg.Sender, msg.Message };
                strmsg      = strmsg + messageList[0] + messageList[1] + messageList[2] + messageList[3] + "\n";
            }
            MessageBox.Show("SMS " + strmsg);
            #endregion
        }
            public void SuccessfullyReturnsAllMessages()
            {
                // READ THIS: http://tech.findmypast.com/dont-mock-what-you-dont-own/
                // Arrange
                var manager = new SmsManager(_serialPort);

                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGF=1\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CSCS=\"PCCP437\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CPMS=\"SM\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns("\r\nOK\r\n");
                    manager._receiveNow.Set();
                });
                _serialPort.When(sp => sp.Write(Arg.Is <string>(a => a == "AT+CMGL=\"ALL\"\r"))).Do(c =>
                {
                    _serialPort.ReadExisting().Returns(
                        @"+CMGL: 1,""REC UNREAD"",""+31628870634"",,""11/01/09,10:26:26+04""
This is text message 1
+CMGL: 2,""REC UNREAD"",""+31628870634"",,""11/01/09,10:26:49+04""
This is text message 2
OK
"
                        );
                    manager._receiveNow.Set();
                });

                // Act
                ShortMessageCollection result = manager.ReadSMS(_serialPort, "AT+CMGL=\"ALL\"");

                // Assert
                Assert.AreEqual(2, result.Count);
                StringAssert.Contains("This is text message 2", result[1].Message);
            }
        public bool ReadTextMessage(out ShortMessageCollection messages, bool readSIM)
        {
            messages = new ShortMessageCollection();

            try
            {
                if (IsModemWorking())
                {
                    ExecuteCommand(FormatAsTextString, 300);                    //, "Failed to set message format."

                    // Use character set "PCCP437"
                    ExecuteCommand("AT+CSCS=\"PCCP437\"", 300);
                    // Select SIM storage
                    if (readSIM)
                    {
                        ExecuteCommand("AT+CPMS=\"SM\"", 300);
                    }
                    else
                    {
                        ExecuteCommand("AT+CPMS=\"ME\"", 300);
                    }
                    //, "Failed to select message storage.");
                    // Read the messages
                    string input = ExecuteCommand("AT+CMGL=\"ALL\"", 5000);   //, "Failed to read the messages.");

                    if (!ParseMessages(input, out messages))
                    {
                        return(false);
                    }

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                messages = null;

                return(false);
            }
        }
            public void SuccessfullyParsesMessages()
            {
                // Arrange
                var messages =
                    @"+CMGL: 1,""REC UNREAD"",""+31628870634"",,""11/01/09,10:26:26+04""
This is text message 1
+CMGL: 2,""REC UNREAD"",""+31628870634"",,""11/01/09,10:26:49+04""
This is text message 2
OK
";
                var manager = new SmsManager(_serialPort);

                // Act
                ShortMessageCollection result = manager.ParseMessages(messages);

                // Assert
                Assert.AreEqual(2, result.Count);
                StringAssert.Contains("This is text message 2", result[1].Message);
            }
        public ShortMessageCollection CheckForNewMessage(bool readSIM)
        {
            ShortMessageCollection result = new ShortMessageCollection();

            ShortMessageCollection messages;

            if (ReadTextMessage(out messages, readSIM))
            {
                foreach (ShortMessage item in messages)
                {
                    if (item.Status == "REC UNREAD")
                    {
                        result.Add(item);
                    }
                }
            }

            return(result);
        }
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
            Match m = r.Match(input);

            while (m.Success)
            {
                ShortMessage msg = new ShortMessage();
                msg.Index    = m.Groups[1].Value;  // Disable - temp pa 25/09/15
                msg.Status   = m.Groups[2].Value;
                msg.Sender   = m.Groups[3].Value;
                msg.Alphabet = m.Groups[4].Value;
                msg.Sent     = m.Groups[5].Value;
                msg.Message  = m.Groups[6].Value;
                messages.Add(msg);

                m = m.NextMatch();
            }

            return(messages);
        }
        public ShortMessageCollection ReadSMS(SerialPort port, string Command)
        {
            // Set up the phone and read the messages
            ShortMessageCollection messages = null;

            try
            {
                #region Execute Command
                // Check connection
                string input = ExecCommand(port, "AT", 300, "No phone connected");
                // Use message format "Text mode"
                input = ExecCommand(port, "AT+CMGF=1", 1000, "Failed: To Set Txt format.");
                // Use character set "PCCP437"
                //ExecCommand(port,"AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");  // stops incomplete msg rxd
                // Select SIM storage
                input = ExecCommand(port, "AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
                // Read the messages
                input = ExecCommand(port, Command, 1000, "Failed to read the messages.");
                #endregion

                #region Parse messages
                messages = ParseMessages(input);
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Reads all SMS messages on the modem
        /// </summary>
        /// <param name="port">The serial port on which the modem resides</param>
        /// <param name="command">The AT read command to execute</param>
        /// <returns>A collection of SMS messages</returns>
        private ShortMessageCollection ReadSMS(SerialPort port, string command)
        {
            // Set up the phone and read the messages
            ShortMessageCollection messages = null;

            try
            {
                #region Execute Command
                // Check connection
                ExecCommand("AT", 300, "No phone connected");
                // Use message format "Text mode"
                ExecCommand("AT+CMGF=1", 300, "Failed to set message format.");
                // Use character set "PCCP437"
                ExecCommand("AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
                // Select SIM storage
                ExecCommand("AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
                // Read the messages
                string input = ExecCommand(command, 5000, "Failed to read the messages.");
                #endregion

                #region Parse messages
                messages = ParseMessages(input);
                #endregion
            }
            catch
            {
                throw;
            }

            if (messages != null)
            {
                return(messages);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Handles each tick of the poll timer
        /// </summary>
        /// <param name="sender">The timer that fired this event</param>
        /// <param name="e">The event arguments</param>
        private void UpdateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            int messageCount = CountSMSMessages();

            if (messageCount > 0)
            {
                //UpdateTimer.Stop();

                ShortMessageCollection messages = ReadSMS(Port, "AT+CMGL=\"ALL\"");
                foreach (ShortMessage message in messages)
                {
                    SmsMessages.Enqueue(message);
                }

                if (DeleteSMS(Port, "AT+CMGD=1,4"))
                {
                    // success on deletion!
                }
                else
                {
                    // failed to delete, which is bad, uh-oh...
                    throw new InvalidOperationException("Can't proceed - old SMS messages cannot be deleted.");
                }

                do
                {
                    if (SmsMessages.Count > 0)
                    {
                        ShortMessage message = SmsMessages.Dequeue();
                        ExecuteMessageContent(message);
                    }
                } while (SmsMessages.Count != 0);

                //UpdateTimer.Start();
            }
        }
Exemple #19
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();

            try
            {
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
                Match m = r.Match(input);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();

                    //msg.Index = int.Parse(m.Groups[1].Value);
                    msg.Index = m.Groups[1].Value;
                    msg.Status = m.Groups[2].Value;
                    msg.Sender = m.Groups[3].Value;
                    msg.Alphabet = m.Groups[4].Value;
                    msg.Sent = m.Groups[5].Value;
                    msg.Message = m.Groups[6].Value;

                    messages.Add(msg);

                    m = m.NextMatch();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return messages;
        }
Exemple #20
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            try
            {
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
                Match m = r.Match(input);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();
                    msg.Index = m.Groups[1].Value;
                    msg.Status = m.Groups[2].Value;
                    msg.Sender = ConvertRusFromUCS2(m.Groups[3].Value);
                    msg.Alphabet = m.Groups[4].Value;
                    DateTime sourceDate = DateTime.ParseExact(m.Groups[5].Value, "dd/M/yy,HH:mm:ss+ff", CultureInfo.InvariantCulture);
                    msg.SentDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, sourceDate.Hour, sourceDate.Minute, sourceDate.Second, sourceDate.Millisecond);

                    msg.Text = ConvertRusFromUCS2(m.Groups[6].Value);

                    messages.Add(msg);
                    m = m.NextMatch();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Ошибка парсинга сообщений: " + ex.Message);
            }
            return messages;
        }
Exemple #21
0
        public ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            try
            {
                //Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");

                String inputAux = input;
                inputAux = inputAux.Replace("\r\n", @"\x");
                inputAux = inputAux.Replace("\n", "");
                inputAux = inputAux.Replace(@"\x", "\r\n");
                Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n"); ;
                Match m = r.Match(inputAux);
                while (m.Success)
                {
                    ShortMessage msg = new ShortMessage();
                    //msg.Index = int.Parse(m.Groups[1].Value);
                    msg.Index = m.Groups[1].Value;
                    msg.Status = m.Groups[2].Value;
                    msg.Sender = m.Groups[3].Value;
                    msg.Alphabet = m.Groups[4].Value;
                    msg.Sent = m.Groups[5].Value;
                    msg.Message = m.Groups[6].Value;
                    messages.Add(msg);

                    m = m.NextMatch();
                }

            }
            catch (Exception ex)
            {
                //_logger.Error("ParseMessages", ex);
                _causa = ex.Message;
                Console.WriteLine("ParseMessages " + ex.Message);
            }
            return messages;
        }
Exemple #22
0
        private void btnReadSMS_Click(object sender, EventArgs e)
        {
            try
            {
                //count SMS 
                int uCountSMS = objclsSMS.CountSMSmessages(this.port);
                if (uCountSMS > 0)
                {

                    #region Command
                    string strCommand = "AT+CMGL=\"ALL\"";

                    if (this.rbReadAll.Checked)
                    {
                        strCommand = "AT+CMGL=\"ALL\"";
                    }
                    else if (this.rbReadUnRead.Checked)
                    {
                        strCommand = "AT+CMGL=\"REC UNREAD\"";
                    }
                    else if (this.rbReadStoreSent.Checked)
                    {
                        strCommand = "AT+CMGL=\"STO SENT\"";
                    }
                    else if (this.rbReadStoreUnSent.Checked)
                    {
                        strCommand = "AT+CMGL=\"STO UNSENT\"";
                    }
                    #endregion

                    // If SMS exist then read SMS
                    #region Read SMS
                    //.............................................. Read all SMS ....................................................
                    objShortMessageCollection = objclsSMS.ReadSMS(this.port, strCommand);
                    foreach (ShortMessage msg in objShortMessageCollection)
                    {

                        ListViewItem item = new ListViewItem(new string[] { msg.Index, msg.Sent, msg.Sender, msg.Message });
                        item.Tag = msg;
                        lvwMessages.Items.Add(item);

                    }
                    #endregion

                }
                else
                {
                    lvwMessages.Clear();
                    //MessageBox.Show("There is no message in SIM");
                    this.statusBar1.Text = "There is no message in SIM";
                    
                }
            }
            catch (Exception ex)
            {
                ErrorLog(ex.Message);
            }
        }
Exemple #23
0
        public ShortMessageCollection ProcessingNewIncomeSMSMessages(ShortMessageCollection messages, GsmModem modem)
        {
            IncomeSMSSaveMutex.WaitOne();
            ShortMessageCollection notSend = new ShortMessageCollection();
            try
            {
                using (SMSContext context = new SMSContext())
                {

                    ServicePhone ServicePhone = GetServicePhoneById(modem.ServicePhone.ServicePhoneId, context);
                    foreach (ShortMessage message in messages)
                    {
                        bool NotSaved = true;
                        bool isGarbage = true;
                        try
                        {
                            int firstWordLength = message.Text.Contains(" ") ? message.Text.Substring(0, message.Text.IndexOf(" ")).Length : 0;
                            string firstWord = message.Text.Contains(" ") ? message.Text.Substring(0, message.Text.IndexOf(" ")).Replace("\n", "").Replace("\r", "") : null;
                            Client client = GetClientByPhone(message.Sender, context);
                            bool haveFirstWord = !String.IsNullOrEmpty(firstWord);
                            bool ClientSMSAndNotAnswer = false;

                            if (client != null && haveFirstWord)
                            {
                                isGarbage = false;
                                IncomeSMS incomeSMS = GetIncomeSMS(firstWord, client.ClientId, context);
                                if (incomeSMS == null)
                                    ClientSMSAndNotAnswer = true;
                                else
                                {

                                    message.Recipient = incomeSMS.SenderNumber;
                                    message.Sender = ServicePhone.PhoneNumber;
                                    message.Text = message.Text.Substring(firstWordLength + 1);
                                    message.IsRead = true;
                                    if (ClientIsNotBlocked(client))
                                    {
                                        IncomeClientSMS incomeClientSMS = SaveIncomeClientSMS(message, ServicePhone, incomeSMS, client, context);
                                        if (incomeClientSMS != null) NotSaved = false;
                                        int answerId = AddAnswer(incomeSMS.MessageId, incomeClientSMS.IncomeClientSMSId, Answer.AnswerSource.SMS);
                                    }
                                }
                            }
                            if ((client == null || ClientSMSAndNotAnswer) && message.Sender != null && message.Sender.Length > 10)
                            {
                                isGarbage = false;
                                client = haveFirstWord ? GetClientByShortKey(firstWord, ServicePhone, context) : null;
                                string text;
                                if (ServicePhone.Type == ServicePhone.PhoneType.Private)
                                {
                                    client = GetClientByServicePhone(ServicePhone, context);
                                    text = message.Text;
                                }
                                else
                                {
                                    text = message.Text.Substring(firstWord.Length + 1);
                                }

                                IncomeSMS incomeSMS = null;

                                incomeSMS = context.IncomeSMS.FirstOrDefault(x => x.SenderNumber.Equals(message.Sender) && x.RecipientNumber.Equals(ServicePhone.PhoneNumber) && DbFunctions.DiffSeconds(x.DateTime, message.SentDate) <= 30 && x.Status != IncomeSMS.IncomeSMSStatus.Sent);

                                if (incomeSMS != null)
                                {
                                    incomeSMS.Text += message.Text;
                                    context.SaveChanges();
                                    NotSaved = false;
                                    message.IsRead = true;
                                }
                                else if (incomeSMS == null && client != null)
                                {
                                    if (ClientIsNotBlocked(client))
                                    {
                                        incomeSMS = SaveIncomeSMS(client, text, message.Sender, ServicePhone.PhoneNumber, message.SentDate, firstWord, context);
                                        if (incomeSMS != null) NotSaved = false;
                                    }
                                    message.IsRead = true;
                                }

                            }

                            if (NotSaved & !isGarbage)
                            {
                                notSend.Add(message);
                                message.IsRead = true;
                            }
                        }
                        catch
                        {
                            if (NotSaved & !isGarbage)
                            {
                                notSend.Add(message);
                                message.IsRead = true;
                            }
                        }

                    }

                    foreach (ShortMessage message in messages.Where(x => x.IsRead == false))
                    {
                        bool Saved = false;
                        try
                        {
                            Client client = GetClientByPhone(message.Sender, context);
                            if (client != null)
                            {
                                IncomeClientSMS incomeClientSMS = null;

                                incomeClientSMS = context.IncomeClientSMS.FirstOrDefault(x => x.Client.ClientId == client.ClientId && DbFunctions.DiffSeconds(x.DateTime, message.SentDate) <= 15 && x.Status != IncomeClientSMS.IncomeClientSMSStatus.Sent);

                                if (incomeClientSMS != null)
                                {

                                    incomeClientSMS.Text += message.Text;
                                    context.Entry(incomeClientSMS).State = System.Data.Entity.EntityState.Modified;
                                    context.SaveChanges();
                                    Saved = true;
                                }

                            }
                            else
                            {
                                IncomeSMS incomeSMS = null;

                                incomeSMS = context.IncomeSMS.FirstOrDefault(x => x.SenderNumber.Equals(message.Sender) && x.RecipientNumber.Equals(ServicePhone.PhoneNumber) && DbFunctions.DiffSeconds(x.DateTime, message.SentDate) <= 30 && x.Status != IncomeSMS.IncomeSMSStatus.Sent);

                                if (incomeSMS != null)
                                {
                                    incomeSMS.Text += message.Text;
                                    context.Entry(incomeSMS).State = System.Data.Entity.EntityState.Modified;
                                    context.SaveChanges();
                                    Saved = true;
                                }

                            }

                        }
                        catch
                        {
                            if (!Saved) notSend.Add(message);
                        }

                    }

                }
                return notSend;
            }
            catch (Exception e)
            {
                notSend = messages;
                return notSend;
            }
            finally
            {
                IncomeSMSSaveMutex.ReleaseMutex();
            }
        }
 public override void OnReadAllSMSCompleated(ShortMessageCollection smsCollection)
 {
     base.OnReadAllSMSCompleated(smsCollection);
 }
Exemple #25
0
        private ShortMessageCollection ParseMessages(string input)
        {
            ShortMessageCollection messages = new ShortMessageCollection();
            Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
            Match m = r.Match(input);

            string[] mySplit = input.Split(new string[] { "+CMGL:" }, StringSplitOptions.None);
            int num = mySplit.Length - 1;
            for (int i = 1; i <= num; i++)
            {
                string sms = mySplit[i].Replace("\r\nOK\r", "");
                sms = sms.Replace("\r\n", "");
                sms = sms.Replace(",\"", ",");
                sms = sms.Replace("\"", ",");
                sms = sms.Replace("\r\n", ",");
                string[] mess = sms.Split(',');

                if (mess.Length > 4)
                {
                    for (int y = 5; y < mess.Length; y++)
                        mess[4] += ","+mess[y];
                }

                ShortMessage msg = new ShortMessage();
                msg.Index = int.Parse(mess[0]);
                msg.Status = mess[1];
                msg.Sender = mess[3];
                msg.Alphabet = "";
                msg.Sent = DateTime.Now.ToString();
                if (mess[4].IndexOf("\n") > -1) mess[4].Replace("\n", "");
                msg.Message = mess[4];
                messages.Add(msg);
            }

            return messages;
        }