Esempio n. 1
0
        public bool Connect(int comPort, int baudRate, int timeout)
        {
            try
            {
                Gsm = new GsmCommMain(comPort, baudRate, timeout);

                if (!Gsm.IsOpen())
                {
                    Gsm.Open();
                }

                return(true);
            }
            catch (System.Exception ex)
            {
                LogError(ex.Message);

                if (Gsm.IsConnected() && Gsm.IsOpen())
                {
                    Gsm.Close();
                }

                return(false);
            }
        }
 public static void Open()
 {
     if (!gsObj.IsOpen())
     {
         gsObj.Open();
     }
 }
Esempio n. 3
0
        public void Send(string message, string nr)
        {
            SmsSubmitPdu pdu = new SmsSubmitPdu(message, nr, "");

            try
            {
                if (!comm.IsOpen())
                {
                    comm.Open();
                }

                if (!comm.IsConnected())
                {
                    Singleton.Show_MessageBox("błąd portu");
                    return;
                }

                /*if (comm.GetPinStatus() != PinStatus.Ready) {
                 *  comm.EnterPin(PIN);
                 *  Thread.Sleep(1000);
                 * }*/

                comm.SendMessage(pdu);
                Thread.Sleep(1000);
            }
            catch (Exception ex)
            {
                Singleton.Show_MessageBox(ex.Message);
                return;
            }
            //Singleton.Show_MessageBox("wysyłam " + message + "na numer: " + nr);
        }
Esempio n. 4
0
 private static bool _disconnect_from_gsm()
 {
     _GsmComm.Close();
     if (!_GsmComm.IsOpen())
     {
         return(true);
     }
     return(false);
 }
Esempio n. 5
0
 public void closePort()
 {
     try
     {
         if (comm.IsOpen())
         {
             comm.Close();
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Esempio n. 6
0
        public async void RegisterConfiguration(ISmsConfiguration Config)
        {
            _server = new GsmCommMain(Config.Port, Config.BaudRate, 5000);
            do
            {
                await Task.Delay(100);

                if (_server.IsOpen())
                {
                    // connect event
                    OnServerConnected.CrossInvoke(this, new SmsServerConnected()
                    {
                        TimeConnected = DateTime.Now
                    });
                    break;
                }
                else
                {
                    try
                    {
                        _server.Open();
                    }
                    catch (Exception ex)
                    {
                        OnServerConnectionFail.CrossInvoke(this, new ServerConnectErrorEventArgs()
                        {
                            DatePosted = DateTime.Now,
                            guid       = Guid.NewGuid(),
                            Message    = ex.InnerException.Message ?? ex.Message
                        });
                    }
                }
            }while (true);
        }
Esempio n. 7
0
        public Boolean closePort()
        {
            bool close = false;

            try
            {
                comm.Close();
                if (!comm.IsOpen())
                {
                    try
                    {
                        sendBgWorker.CancelAsync();
                    } catch (Exception ex)
                    {
                    }

                    close                  = true;
                    portOpen               = false;
                    btn_connect.Text       = "Connect";
                    btn_connect.BackColor  = Color.DodgerBlue;
                    btn_refresh.Enabled    = true;
                    cbo_port.SelectedIndex = -1;
                    cbo_port.Enabled       = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("No port selected \n" + "Message : " + ex.Message);
                close = false;
            }
            return(close);
        }
Esempio n. 8
0
        private void votecountsFrm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // Kill SMS server if running
            DestroySmsServer();

            // Clean up comm object
            if (comm != null)
            {
                // Unregister events

                comm.PhoneConnected    -= new EventHandler(comm_PhoneConnected);
                comm.PhoneDisconnected -= new EventHandler(comm_PhoneDisconnected);
                if (registerMessageReceived)
                {
                    comm.MessageReceived   -= new MessageReceivedEventHandler(comm_MessageReceived);
                    registerMessageReceived = false;
                }

                // Close connection to phone
                if (comm != null && comm.IsOpen())
                {
                    comm.Close();
                }

                comm = null;
                Environment.Exit(0);
            }
        }
Esempio n. 9
0
        public async Task <bool> SendSMS(string sms, List <string> phones)
        {
            try
            {
                await Task.FromResult(true);

                GsmCommMain comm = new GsmCommMain("COM6", 1, 80000);
                if (!comm.IsOpen())
                {
                    comm.Open();
                }

                foreach (var phone in phones)
                {
                    SmsSubmitPdu[] messagePDU = SmartMessageFactory.CreateConcatTextMessage(sms, true, phone);
                    comm.SendMessages(messagePDU);
                }

                comm.Close();
                return(true);
            }
            catch (Exception ex)
            {
            }
            return(false);
        }
Esempio n. 10
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (comm != null)
     {
         comm.PhoneConnected    -= new EventHandler(comm_PhoneConnected);
         comm.PhoneDisconnected -= new EventHandler(comm_PhoneDisconnected);
         // Close connection to phone
         if (comm != null && comm.IsOpen())
         {
             comm.Close();
         }
         comm = null;
     }
 }
Esempio n. 11
0
        }// Open Modem

        public String ReadSms()
        {
            DecodedShortMessage[] decsms = null;
            if (comm.IsOpen())
            {
                do
                {
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        decsms         = comm.ReadMessages(PhoneMessageStatus.All, PhoneStorageType.Sim);
                        Cursor.Current = Cursors.Default;
                    }
                    catch (Exception ex)
                    {
                    }
                    Thread.Sleep(1);
                } while (decsms == null);
            }
            int len = decsms.Length;

            return("OK");
        }
Esempio n. 12
0
 private void chkReceived_CheckedChanged(object sender, EventArgs e)
 {
     if (comm != null && comm.IsOpen() == true)
     {
         if (chkReceived.Checked == true)
         {
             comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
             comm.EnableMessageNotifications();
         }
         else
         {
             comm.DisableMessageNotifications();
         }
     }
 }
Esempio n. 13
0
        private static bool _connect2gsm()
        {
            string[] _coms = SerialPort.GetPortNames();

            foreach (string com in _coms)
            {
                _GsmComm = new GsmCommMain(com, 9600, 150);

                try
                {
                    if (!_GsmComm.IsOpen())
                    {
                        _GsmComm.Open();
                    }
                    if (_GsmComm.IsOpen())
                    {
                        return(true);
                    }
                }
                catch (Exception e) { string st = e.Message; }
            }

            return(false);
        }
Esempio n. 14
0
 public void Close() //ref GsmCommMain comm
 {
     try
     {
         while (comm != null && (comm.IsConnected() || comm.IsOpen()))
         {
             //comm.ResetToDefaultConfig();
             //comm.ReleaseProtocol();
             comm.Close();
         }
     }
     catch (Exception)
     {
         ;
     }
     comm = null;
 }
Esempio n. 15
0
 //Méthode pour envoyer un message
 public void Send(string message, string number, string nothing)
 {
     Cursor.Current = Cursors.WaitCursor;
     try
     {
         SmsSubmitPdu pdu;
         pdu = new SmsSubmitPdu(message, number, nothing);  // "" indicate SMSC No
         if (!comm.IsOpen())
         {
             comm.Open();
         }
         comm.SendMessage(pdu);
         MessageBox.Show("message envoyé", "ENVOIE SIMPLE", MessageBoxButtons.OK, MessageBoxIcon.Information);
         comm.Close();
     }
     catch (Exception)
     {
         MessageBox.Show("L'envoie a échoué", "ENVOIE SIMPLE", MessageBoxButtons.OK, MessageBoxIcon.Information);
     }
     Cursor.Current = Cursors.Default;
 }
Esempio n. 16
0
        public void cleanUp()
        {
            if (comm == null)
            {
                return;
            }

            //comm.DisableMessageNotifications();     //disable message notifications
            // unregister all the event handlers.
            comm.MessageReceived -= new MessageReceivedEventHandler(comm_MessageReceived);

            comm.MessageSendComplete -= new GsmCommMain.MessageEventHandler(comm_MessageSendComplete);

            // Close connection to phone
            if (comm.IsOpen())
            {
                comm.Close();
            }



            logger = null;
        }
Esempio n. 17
0
        private int?findGSMCommPort()
        {
            String[] portNames  = System.IO.Ports.SerialPort.GetPortNames();
            int?     portNumber = null;

            foreach (string portName in portNames)
            {
                String[] port = portName.Split(new string[] { "COM" }, StringSplitOptions.None);

                GsmCommMain comm = new GsmCommMain(Int32.Parse(port[1]), gsmBaudRate /*baudRate*/, gsmTimeOut /*timeout*/);
                try
                {
                    comm.Open();

                    if (comm.IsConnected())
                    {
                        AddressData addrData = comm.GetSmscAddress();
                        portNumber = Convert.ToInt32(port[1]);
                    }
                    comm.Close();
                    if (portNumber != null)
                    {
                        break;
                    }
                }
                catch (Exception e)
                {
                    if (comm.IsOpen())
                    {
                        comm.Close();
                    }
                }
            }


            return(portNumber);
        }
Esempio n. 18
0
        private static void ModemPollingLoop()
        {
            //Find a port where the modem is at
            _logger.Info("Searching for a modem...");
            for (int i = 1; i <= 256; i++)
            {
                if (TestConnection($"COM{i}"))
                {
                    break;
                }
            }

            if (_comm.IsOpen() && _comm.IsConnected())
            {
                _logger.Info("Modem found");
                _logger.Info("Setting modem settings...");
                _comm.SelectCharacterSet("ucs2"); //Use UTF-16 encoding when getting data from modem

                //Hook debugging event if user wants to debug modem commands
                if (_config.GetValue("Debug/ModemCommands", false))
                {
                    _comm.LoglineAdded += comm_LoglineAdded;
                }

                try
                {
                    _comm.SetSmscAddress(_config.GetValue("General/SMSCenter", ""));
                }
                catch (Exception)
                {
                    _logger.Warn("Invalid SMS Center number or this feature is not supported by current modem");
                }

                _logger.Info("Listening for incoming messages...");
                while (_comm.IsOpen())
                {
                    if (_comm.IsConnected())
                    {
                        try
                        {
                            //Get all messages saved on SIM
                            DecodedShortMessage[] messages = _comm.ReadMessages(PhoneMessageStatus.All,
                                                                                PhoneStorageType.Sim);

                            foreach (DecodedShortMessage message in messages)
                            {
                                SmsPdu pdu = message.Data;
                                if (pdu is SmsDeliverPdu) // Check if it's SMS and not some kind of a service message
                                {
                                    SmsDeliverPdu data = (SmsDeliverPdu)pdu;
                                    _logger.Debug($"Received message from {data.OriginatingAddress}: " +
                                                  data.UserDataText + $" [TIMESTAMP: {data.SCTimestamp.ToSortableString()}]");

                                    ChangePassword(data.OriginatingAddress, data.UserDataText);

                                    //Delete message so it won't be parsed again
                                    //and so we don't have a problem with free space on SIM
                                    //in the future
                                    _comm.DeleteMessage(message.Index, message.Storage);
                                }
                                else
                                {
                                    _logger.Warn($"Received unknown message type: {pdu.GetType()}");
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            _logger.Warn($"Cannot read messages: {ex.Message} ({ex.GetType()})");
                            break;
                        }

                        //Sleep 5 seconds between message checks
                        Thread.Sleep(5000);
                    }
                    else
                    {
                        _logger.Error("Lost cellular network connection");
                        break;
                    }
                }
            }
            else
            {
                _logger.Fatal("No modem found");
            }

            //Close modem connection
            try
            {
                _comm.Close();
            }
            catch (Exception) { }
        }
Esempio n. 19
0
        public static String sendSMS(String phoneno, String message, String portno, bool usePDU = true)
        {
            String responseOfAction = "";

            if (usePDU == false)
            {
                try
                {
                    // for more info visit https://stackoverflow.com/a/15450868/8140312
                    SerialPort sp = new SerialPort();
                    sp.PortName = portno;
                    sp.Open();
                    SendCommand("AT", sp);
                    SendCommand("AT+CMGF=1", sp);
                    SendCommand("AT+CSCS=\"GSM\"", sp);
                    SendCommand("AT+CMGS=\"" + phoneno + "\"", sp);

                    var response = SendCommand(message + "\x1A", sp);

                    if (response.Contains("ERROR"))
                    {
                        responseOfAction = $"Unable to send SMS{Environment.NewLine}RESPONSE: “{response}”";
                    }
                    else
                    {
                        responseOfAction = $"SMS sent successfully.{Environment.NewLine}RESPONSE: “{response}”";
                    }
                    sp.Close();

                    return(responseOfAction);
                }
                catch (Exception e)
                {
                    return(e.Message);
                }
            }
            else
            {
                // GsmComm is installed from nuget Package Manager
                GsmCommMain GsmCom = null;
                try
                {
                    GsmCom = new GsmCommMain(portno, 9600, 5000);
                    GsmCom.Open();
                    GsmCom.PortName.ToString();
                    OutgoingSmsPdu[] pdus = null;
                    bool             isValidGSMCharaters = isValidGSMCharateres(message);
                    if (isValidGSMCharaters)
                    {
                        pdus = SmartMessageFactory.CreateConcatTextMessage(message, false, phoneno);
                    }
                    else
                    {
                        pdus = SmartMessageFactory.CreateConcatTextMessage(message, true, phoneno);
                    }
                    Debug.WriteLine($" ===>> {isValidGSMCharaters}");
                    //var st = new Stopwatch();
                    //st.Start();
                    long smsSent = 0;
                    if (pdus != null)
                    {
                        foreach (OutgoingSmsPdu pdu in pdus)
                        {
                            GsmCom.SendMessage(pdu);
                        }
                        //smsSent = st.ElapsedMilliseconds;
                    }
                    GsmCom.Close();
                    //var gsmClsed = st.ElapsedMilliseconds;
                    //st.Stop();
                    //Debug.WriteLine($"smsSentIN: {smsSent} == gsmClosed in {gsmClsed - smsSent }");
                    String formate = isValidGSMCharaters == true ? "GSM" : "Unicode";
                    return($"Message Sent with {portno.ToString()} in “{formate}” format in {pdus.Count()} part(s)");
                }
                catch (Exception exp)
                {
                    if (GsmCom.IsOpen())
                    {
                        GsmCom.Close();
                    }
                    return("Not send: " + exp.Message);
                    // goto lebe;
                }
            }
        }
Esempio n. 20
0
        private void btn_connect_Click(object sender, EventArgs e)
        {
            string pname = "";

            if (cbo_port.SelectedIndex == -1)
            {
                MessageBox.Show("Please select a port");
                return;
            }
            if (!portOpen)
            {
                pname          = cbo_port.Text;
                comm           = new GsmCommMain(pname, 9600, 150);
                Cursor.Current = Cursors.Default;
                bool retry;
                do
                {
                    retry = false;
                    try
                    {
                        Cursor.Current = Cursors.WaitCursor;
                        comm.Open();
                        Cursor.Current = Cursors.Default;
                        MessageBox.Show("Modem Connected Sucessfully");
                        cbo_port.Enabled = false;
                        // btn_connect_dis.Text = "Disconnect";
                        portOpen = true;
                        if (comm.IsOpen())
                        {
                            btn_connect.BackColor = Color.Red;
                            btn_connect.ForeColor = Color.White;
                            btn_connect.Text      = "Disconnect";
                            btn_refresh.Enabled   = false;
                            sendBgWorker.RunWorkerAsync();
                        }
                    }
                    catch (Exception)
                    {
                        Cursor.Current = Cursors.Default;
                        if (MessageBox.Show(this, "GSM Modem is not available", "Check",
                                            MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                        {
                            retry = true;
                        }
                        else
                        {
                            return;
                        }
                    }
                }while (retry);
            }
            else
            {
                if (closePort())
                {
                    portOpen         = false;
                    cbo_port.Enabled = true;
                    MessageBox.Show("Port closed.");
                }
            }
        }
Esempio n. 21
0
        public void ProcessAllMessage()
        {
            try
            {
                BSOB.SMS[] allSms = bsob.SMSGetAll();

                foreach (BSOB.SMS sms in allSms)
                {
                    Order(sms);
                    bsob.SetReplyStatus(sms.ID);
                }
            }
            catch (Exception ex)
            {
                LogError(ex.Message);

                if (Gsm.IsConnected() && Gsm.IsOpen())
                {
                    Gsm.Close();
                }
            }
        }
Esempio n. 22
0
        private bool Open()
        {
            try
            {
                //  ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
                //  ManagementObjectSearcher searcher2 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_POTSModem ");
                ManagementObjectSearcher searcher3 = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity ");

                /*         foreach (ManagementObject queryObj in searcher.Get())
                 *       {
                 *
                 *           MessageBox.Show(queryObj["Name"].ToString());
                 *
                 *           if (queryObj["Name"].ToString().Contains(Modem))   // i.e "ST-Ericsson ... "
                 *           {
                 *
                 *               string xx = queryObj["Description"].ToString();
                 *               //  string com = queryObj["DeviceID"].ToString();
                 *               // int index = com.LastIndexOf('M');
                 *                if(index > 0 && index <= 5)                     // Check for valid COMx port
                 *               // port = Convert.ToInt32(com.Substring(index + 1, com.Length - index - 1));
                 *              //
                 *           }
                 *       }
                 *
                 * foreach (ManagementObject queryObj2 in searcher2.Get())
                 * {
                 *
                 * // MessageBox.Show(queryObj2["Name"].ToString());
                 *
                 *  if (queryObj2["Name"].ToString().Contains(Modem))   // i.e "ST-Ericsson ... "
                 *  {
                 *
                 *      string com = System.Convert.ToString(queryObj2["Description"]);
                 *
                 *      if (com.Contains("(COM"))
                 *      {
                 *          int index = com.LastIndexOf('M');
                 *          if (index > 0 && index <= 5)                     // Check for valid COMx port
                 *              port = Convert.ToInt32(com.Substring(index + 1, com.Length - index - 1));
                 *      }
                 *      //  string com = queryObj["DeviceID"].ToString();
                 *      // int index = com.LastIndexOf('M');
                 *      // if(index > 0 && index <= 5)                     // Check for valid COMx port
                 *      // port = Convert.ToInt32(com.Substring(index + 1, com.Length - index - 1));
                 *      //
                 *  }
                 * }
                 */
                foreach (ManagementObject queryObj3 in searcher3.Get())
                {
                    //MessageBox.Show(queryObj3["Name"].ToString());

                    if (queryObj3["Name"].ToString().Contains(Modem))   // i.e "ST-Ericsson ... "
                    {
                        if ((string)queryObj3["Status"] == "OK")
                        {
                            string com = System.Convert.ToString(queryObj3["Name"]);

                            if (com.Contains("(COM"))
                            {
                                int    index  = com.LastIndexOf('M');
                                int    index2 = com.LastIndexOf(')');
                                string substr = com.Substring(index + 1, com.Length - index2 + 1);
                                port = Convert.ToInt32(substr);
                                // Get Modem Port
                                if (port > 3)
                                {
                                    port -= 2;  // i.e if 18 then port=16
                                }
                                break;
                            }
                        }
                    }
                }

                if (port != 0)
                {
                    comm = new GsmCommMain(port, BaudRate, 1000);
                    // Register with network

                    comm.PhoneConnected += new EventHandler(comm_PhoneConnected);
                    comm.PhoneConnected += new EventHandler(comm_PhoneDisconnected);

                    try
                    {
                        if (!comm.IsOpen())
                        {
                            comm.Open();
                        }
                        if (this.comm.IsOpen())
                        {
                            return(true);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Modem unable to open: " + ex);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Port not found: " + ex);
                // EventLog.WriteEntry("AeiGenAlert: Comm  is Closed");
            }
            return(false);
        }