Untitled

 avatar
unknown
plain_text
4 years ago
2.4 kB
5
Indexable
using System;
using System.Linq;
using System.Threading.Tasks;
using System.IO.Ports;


public class SmsSender
    {
        public SerialPort SerialPort { get; set; }
        public bool IsAvailable { get => CanOpen && PortExists; }

        public bool CanOpen {
            get
            {
                bool retValue = false;
                try
                {
                    if (PortExists)
                    {
                        SerialPort.Open();
                        retValue = true;
                    }
                }
                catch (Exception)
                {
                    retValue = false;
                }
                finally
                {
                    SerialPort.Close();
                }
                return retValue;
            } 
        }

        public bool PortExists
        {
            get
            {
                string[] ports = SerialPort.GetPortNames();
                if (SerialPort.PortName != null)
                    return ports.Contains(SerialPort.PortName);
                return false;
            }
        }

        public SmsSender(string portName)
        {
            SerialPort = new SerialPort(portName)
            {
                BaudRate = 115200,
                DataBits = 8,
                Parity = Parity.None,
                ReadTimeout = 300,
                WriteTimeout = 300,
                StopBits = StopBits.One,
                Handshake = Handshake.None
            };             
        }

        public async void sendSMS(string mobNo, string msg)
        {
            string telNo = Char.ConvertFromUtf32(34) + mobNo + Char.ConvertFromUtf32(34);

            try
            {
                if (IsAvailable)
                {
                    SerialPort.Open();
                    // sp.Encoding = Encoding.Unicode;
                    SerialPort.Write("AT+CMGF=1" + Char.ConvertFromUtf32(13));
                    SerialPort.Write("AT+CMGS=" + telNo + Char.ConvertFromUtf32(13));
                    SerialPort.Write(msg + Char.ConvertFromUtf32(26) + Char.ConvertFromUtf32(13));
                    SerialPort.Close();
                    await Task.Delay(500);
                }
            }
            catch (Exception ex)
            {
                // To do //
            }
        }


    }
Editor is loading...