public byte[] SendData(byte[] data, int timeoutSend = 60000, int timeoutRecv = 60000) { try { if (client != null && client.IsConnected()) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); byte[] dataEncrypt = CommonFunctions.Encryption(data, RSA.ExportParameters(false), false); sendDone.Reset(); receiveDone.Reset(); client.BeginSend(dataEncrypt, 0, dataEncrypt.Length, 0, new AsyncCallback(SendCallback), client); sendDone.WaitOne(timeoutSend); StateObject state = new StateObject(); state.workSocket = client; client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); receiveDone.WaitOne(timeoutRecv); return(responseServerData); } return(null); } catch (Exception ex) { LoggingData.WriteLog(ex); Console.WriteLine(ex.ToString()); return(null); } }
private bool SendSMS(string Number, string Content, byte dcs) { try { SmsSubmitPdu sms = new SmsSubmitPdu(Content, Number, dcs); string pdu = sms.ToString(false); string response = ExecuteCommands("AT+CMGS=" + sms.ActualLength.ToString() + "", 1000); if (!CheckNEXT(response)) { LoggingData.WriteLog("Send SMS failed. GSM Modem does not respond to commands"); return(false); } response = ExecuteCommands(pdu + char.ConvertFromUtf32(26), 10000); if (!CheckOK(response)) { LoggingData.WriteLog("Send SMS failed. GSM Modem does not respond to commands"); return(false); } ; return(true); } catch (Exception ex) { LoggingData.WriteLog(ex); return(false); } }
public bool OpenModem(out string msg) { try { if (!OpenPort()) { msg = "GSM Modem can not connect. Please check again"; return(false); } else { msg = ""; string response = ExecuteCommands("AT", 1000); if (!CheckOK(response)) { msg = "GSM Modem does not respond to commands. or the device is not a GSM modem"; ClosePort(); return(false); } InitModemConfig(); msg = string.Empty; return(true); } } catch (Exception ex) { LoggingData.WriteLog(ex); msg = "There was an unknown error. Please check and try again"; return(false); } }
public bool OpenPort(bool ResetConfig = false) { try { if (ResetConfig) { if (SpGSM_Modem != null && SpGSM_Modem.IsOpen) { SpGSM_Modem.Close(); } SpGSM_Modem.PortName = this.PortName; SpGSM_Modem.Open(); return(SpGSM_Modem.IsOpen); } else { if (!SpGSM_Modem.IsOpen) { SpGSM_Modem.Open(); } return(SpGSM_Modem.IsOpen); } } catch (Exception ex) { LoggingData.WriteLog(ex); return(false); } }
public string ExecuteCommands(string ATcommand, int timeout, string Error = "") { receiveNow.Reset(); try { string result = ""; SpGSM_Modem.Write(ATcommand + "\r"); do { if (receiveNow.WaitOne(timeout, false)) { string t = SpGSM_Modem.ReadExisting(); result += t; } else { string t = SpGSM_Modem.ReadExisting(); result += t; return(result); } }while (!result.EndsWith("\r\nOK\r\n") && !result.EndsWith("\r\n> ") && !result.EndsWith("\r\nERROR\r\n")); return(result); } catch (Exception ex) { LoggingData.WriteLog(ex); return(ex.Message); } }
public string WaitingData(int timeout, string ResultContain = null, string Error = "") { receive_AutoResponse.Reset(); try { string result = ""; do { if (receive_AutoResponse.WaitOne(timeout, false)) { string t = SpGSM_Modem_AutoResponse.ReadExisting(); result += t; } else { string t = SpGSM_Modem_AutoResponse.ReadExisting(); result += t; return(result); } }while ((!result.EndsWith("\r\nOK\r\n") && !result.EndsWith("\r\n> ") && !result.EndsWith("\r\nERROR\r\n") && !result.EndsWith("\r\n") && !result.EndsWith("\r")) && ((ResultContain != null && result.Contains(ResultContain)) || ResultContain == null)); return(result); } catch (Exception ex) { LoggingData.WriteLog(ex); return(string.Empty); } }
//Send USSD public string SendUSSD(string Code) { try { string USSDMsg = string.Empty; string USSD_Code = "AT+CUSD=1,\"" + Code + "\",15"; string response = ExecuteCommands(USSD_Code, 500); if (CheckOK(response)) { string resultStr = WaitingData(15000, "+CUSD"); //Nếu hỗ trợ định dạng plain-text thì vào đây làm việc string rs = USSDResult(resultStr); if (rs.Trim().Replace("\r", "").Replace("\n", "") == "") { LoggingData.WriteLog("Gửi USSD không thành công. Modem không phản hồi lệnh."); USSDMsg = "Gửi USSD không thành công. Modem không phản hồi lệnh."; return(USSDMsg); } USSDMsg = rs; return(rs); } else { //Nếu không hỗ trợ Text, thử với định dạng endcode 7bit string EndCodeUSSDCode = TextDataConverter.SeptetsToOctetsHex(Code); USSD_Code = "AT+CUSD=1,\"" + EndCodeUSSDCode + "\",15"; response = ExecuteCommands(USSD_Code, 500); if (CheckOK(response)) { string resultStr = WaitingData(15000); string HexString = USSDResult(resultStr); if (HexString.Trim().Replace("\r", "").Replace("\n", "") == "") { LoggingData.WriteLog("Gửi USSD không thành công. Modem không phản hồi lệnh."); USSDMsg = "Gửi USSD không thành công. Modem không phản hồi lệnh."; return(USSDMsg); } string USSDResultMsg = GSMConverter.Decode7BitText(HexString); USSDMsg = USSDResultMsg; return(USSDMsg); } else { LoggingData.WriteLog("Gửi USSD không thành công. Modem không phản hồi lệnh."); USSDMsg = "Gửi USSD không thành công. Modem không phản hồi lệnh."; return(USSDMsg); } } } catch (Exception ex) { LoggingData.WriteLog(ex); string USSDMsg = ex.Message; return(USSDMsg); } }
private void startConnect() { try { client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.BeginConnect(this._Address, this._Port, new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(TIME_OUT); } catch (Exception ex) { LoggingData.WriteLog(ex); } }
public void Disconnect(Socket client) { try { // Release the socket. client.BeginDisconnect(false, DisconnectCallback, client); } catch (Exception ex) { LoggingData.WriteLog(ex); Console.WriteLine(ex.ToString()); } }
private void SendCallback(IAsyncResult ar) { try { Socket handler = (Socket)ar.AsyncState; int bytesSent = handler.EndSend(ar); } catch (Exception ex) { LoggingData.WriteLog(ex); Console.WriteLine(ex.ToString()); } }
private void SendCallback(IAsyncResult ar) { try { Socket client = (Socket)ar.AsyncState; int bytesSent = client.EndSend(ar); sendDone.Set(); } catch (Exception ex) { sendDone.Set(); LoggingData.WriteLog(ex); Console.WriteLine(ex.ToString()); } }
private void AcceptCallback(IAsyncResult ar) { Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); IPEndPoint localIpEndPoint = handler.LocalEndPoint as IPEndPoint; Console.WriteLine(string.Format("{0}: Client connected: {1}", DateTime.Now, handler.RemoteEndPoint.ToString())); LoggingData.WriteLog(string.Format(string.Format("{0}: Client connected: {1}", DateTime.Now, handler.RemoteEndPoint.ToString()))); // Create the state object. StateObject state = new StateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); acceptConnection.Set(); }
private void ReceiveCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; responseServerData = null; try { if (client != null) { int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { byte[] byteRecv = new byte[bytesRead]; Array.Copy(state.buffer, 0, byteRecv, 0, bytesRead); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); byte[] decryptedData = CommonFunctions.Decryption(byteRecv, RSA.ExportParameters(true), false); responseServerData = decryptedData; ThreadPool.QueueUserWorkItem(new WaitCallback(stateQueue => { if (_actionProccesing != null) { _actionProccesing(ItemData.Parse(decryptedData), this); } })); receiveDone.Set(); state = new StateObject(); state.workSocket = client; client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); } } } catch (Exception ex) { receiveDone.Set(); LoggingData.WriteLog(ex); try { if (client != null) { Console.WriteLine("Disconected to {0} | ReadCallback", client.RemoteEndPoint.ToString()); client.Disconnect(true); } } catch { } Console.WriteLine(ex.ToString()); } }
public byte[] GetBytes() { try { BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, this); return(ms.ToArray()); } } catch (Exception ex) { LoggingData.WriteLog(ex); return(null); } }
private void ConnectCallback(IAsyncResult ar) { try { if (client != null) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); Console.WriteLine("{0:dd-MM-yyyy HH:mm:ss}: Connected to {1}", DateTime.Now, client.RemoteEndPoint.ToString()); } connectDone.Set(); } catch (Exception ex) { connectDone.Set(); LoggingData.WriteLog(ex); } }
private void ReadCallback(IAsyncResult ar) { String content = String.Empty; StateObject state = (StateObject)ar.AsyncState; Socket handler = state.workSocket; int bytesRead = 0; try { if (handler != null) { bytesRead = handler.EndReceive(ar); if (bytesRead > 0) { byte[] byteRecv = new byte[bytesRead]; Array.Copy(state.buffer, 0, byteRecv, 0, bytesRead); RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); byte[] decryptedData = CommonFunctions.Decryption(byteRecv, RSA.ExportParameters(true), false); ThreadPool.QueueUserWorkItem(new WaitCallback(stateQueue => { if (_actionProccesing != null) { _actionProccesing(ItemData.Parse(decryptedData), this, handler); } })); StateObject new_state = new StateObject(); new_state.workSocket = handler; handler.BeginReceive(new_state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), new_state); } } } catch (Exception ex) { LoggingData.WriteLog(ex); try { if (handler != null) { Console.WriteLine("Disconected to {0} | ReadCallback", handler.RemoteEndPoint.ToString()); handler.Disconnect(false); } } catch { } return; } }
public bool SendData(Socket client, byte[] data) { try { if (client != null && client.IsConnected()) { RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); byte[] dataEncrypt = CommonFunctions.Encryption(data, RSA.ExportParameters(false), false); client.BeginSend(dataEncrypt, 0, dataEncrypt.Length, 0, new AsyncCallback(SendCallback), client); return(true); } return(false); } catch (Exception ex) { LoggingData.WriteLog(ex); return(false); } }
public static ItemData Parse(byte[] arrBytes) { try { BinaryFormatter binForm = new BinaryFormatter(); using (MemoryStream memStream = new MemoryStream()) { memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); ItemData result = (ItemData)binForm.Deserialize(memStream); return(result); } } catch (Exception ex) { LoggingData.WriteLog(ex); return(null); } }
public bool OpenSpeechPort(string PortName) { try { _bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat(16000, 1)); _waveOut = new WaveOut(); PlayAudio(); //SerialPort SpGSM_Modem_Speech = new SafeSerialPort(); SpGSM_Modem_Speech.BaudRate = this.BaudRate; SpGSM_Modem_Speech.DataBits = this.DataBits; SpGSM_Modem_Speech.StopBits = this.Stopbits; SpGSM_Modem_Speech.Parity = this.Parity; SpGSM_Modem_Speech.WriteTimeout = 1000; SpGSM_Modem_Speech.Encoding = Encoding.GetEncoding("iso-8859-1"); SpGSM_Modem_Speech.DataReceived += portSpeech_DataReceived; SpGSM_Modem_Speech.DtrEnable = true; SpGSM_Modem_Speech.RtsEnable = true; SpGSM_Modem_Speech.ReadBufferSize = 100000; SpGSM_Modem_Speech.WriteBufferSize = 100000; if (SpGSM_Modem_Speech != null && SpGSM_Modem_Speech.IsOpen) { SpGSM_Modem_Speech.Close(); } SpGSM_Modem_Speech.PortName = PortName; SpGSM_Modem_Speech.Open(); _waveIn = new WaveIn(); _waveIn.WaveFormat = new WaveFormat(16000, 1); _waveIn.DataAvailable += new EventHandler <WaveInEventArgs>(waveSource_DataAvailable); _waveIn.RecordingStopped += new EventHandler <StoppedEventArgs>(waveSource_RecordingStopped); _waveIn.StartRecording(); return(SpGSM_Modem_Speech.IsOpen); } catch (Exception ex) { LoggingData.WriteLog(ex); return(false); } }
public void Start() { try { listener.Bind(localEndPoint); listener.Listen(MAX_CLIENTS); while (true) { acceptConnection.Reset(); Console.WriteLine(string.Format("{0}: Waiting for a connection on port {1}", DateTime.Now, _portListen)); listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); acceptConnection.WaitOne(); } } catch (Exception ex) { LoggingData.WriteLog(ex); this.Restart(); } }
private static void MonitorDeviceChanges() { try { var deviceArrivalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2"); var deviceRemovalQuery = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3"); arrival = new ManagementEventWatcher(deviceArrivalQuery); removal = new ManagementEventWatcher(deviceRemovalQuery); arrival.EventArrived += (o, args) => RaisePortsChangedIfNecessary(EventType.Insertion); removal.EventArrived += (sender, eventArgs) => RaisePortsChangedIfNecessary(EventType.Removal); // Start listening for events arrival.Start(); removal.Start(); } catch (ManagementException err) { LoggingData.WriteLog(err); Console.WriteLine("{0:dd-MM-yyyy HH:mm:ss}: {1} \r\nStackTrace: {2}", DateTime.Now, err.Message, err.StackTrace); } }
public bool SendLongSMS(string Number, string Content) { try { int chunkSize = 70; byte dcs = (byte)DataCodingScheme.GeneralCoding.Alpha16Bit; if (!CommonFunctions.ContainsUnicodeCharacter(Content)) { chunkSize = 140; dcs = (byte)DataCodingScheme.GeneralCoding.Alpha7BitDefault; } IEnumerable <string> multipart = CommonFunctions.SmartSplit(Content, chunkSize); int Success = 0; foreach (var msg in multipart) { bool rs = SendSMS(Number, msg, dcs); if (rs) { Success++; } Thread.Sleep(300); } if (Success == multipart.Count()) { return(true); } else { return(false); } } catch (Exception ex) { LoggingData.WriteLog(ex); return(false); } }
public bool OpenAutoResponsePort(string PortName) { try { //source = new CancellationTokenSource(); //CancellationToken token = source.Token; //taskWaitResponse = Task.Factory.StartNew(() => { //}, token); //SerialPort SpGSM_Modem_AutoResponse = new SafeSerialPort(); SpGSM_Modem_AutoResponse.BaudRate = this.BaudRate; SpGSM_Modem_AutoResponse.DataBits = this.DataBits; SpGSM_Modem_AutoResponse.StopBits = this.Stopbits; SpGSM_Modem_AutoResponse.Parity = this.Parity; SpGSM_Modem_AutoResponse.WriteTimeout = 500; SpGSM_Modem_AutoResponse.Encoding = Encoding.GetEncoding("iso-8859-1"); SpGSM_Modem_AutoResponse.DataReceived += portAutoResponse_DataReceived; SpGSM_Modem_AutoResponse.DtrEnable = true; SpGSM_Modem_AutoResponse.RtsEnable = true; if (SpGSM_Modem_AutoResponse != null && SpGSM_Modem_AutoResponse.IsOpen) { SpGSM_Modem_AutoResponse.Close(); } SpGSM_Modem_AutoResponse.PortName = PortName; SpGSM_Modem_AutoResponse.Open(); return(SpGSM_Modem_AutoResponse.IsOpen); } catch (Exception ex) { LoggingData.WriteLog(ex); return(false); } }
public static void Init() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(@"o========================================================================o"); Console.WriteLine(@"| _____ __ __ _____ _____ ______ _______ ________ _____ |"); Console.WriteLine(@"| / ____| \/ |/ ____| / ____| ____| __ \ \ / / ____| __ \ |"); Console.WriteLine(@"| | (___ | \ / | (___ | (___ | |__ | |__) \ \ / /| |__ | |__) | |"); Console.WriteLine(@"| \___ \| |\/| |\___ \ \___ \| __| | _ / \ \/ / | __| | _ / |"); Console.WriteLine(@"| ____) | | | |____) | ____) | |____| | \ \ \ / | |____| | \ \ |"); Console.WriteLine(@"| |_____/|_| |_|_____/ |_____/|______|_| \_\ \/ |______|_| \_\ |"); Console.WriteLine(@"| _ _ _ _ |"); Console.WriteLine(@"| | | | (_) (_) |"); Console.WriteLine(@"| | | | |_ _ __ __ ___ ___ ___ ___ |"); Console.WriteLine(@"| | | | | | '_ \ / _` \ \ /\ / / / __|/ _ \ |"); Console.WriteLine(@"| \ \_/ / | | | | (_| |\ V V /| \__ \ __/ |"); Console.WriteLine(@"| \___/|_|_| |_|\__,_| \_/\_/ |_|___/\___| |"); Console.WriteLine(@"| |"); Console.WriteLine(@"o========================================================================o"); Console.ResetColor(); Console.WriteLine(string.Format("{0}: Starting modem application to init drivers", DateTime.Now)); LoggingData.ClearLogs(); try { Process.Start(System.AppDomain.CurrentDomain.BaseDirectory + "ModemApp\\WirelessModem.exe"); Thread.Sleep(5000); foreach (var process in Process.GetProcessesByName("WirelessModem")) { process.Kill(); } Thread.Sleep(3000); Console.WriteLine(string.Format("{0}: Loading GSM modem control ", DateTime.Now)); do { Dictionary <string, object> dictData = CommonFunctions.GetSerializedObject(System.AppDomain.CurrentDomain.BaseDirectory + "GsmSettings.dat") as Dictionary <string, object>; string PortName = dictData["PORT_NAME"] as string; int BaudRate = (int)dictData["COM_BAUDRATE"]; int DataBit = (int)dictData["COM_DATA_BIT"]; StopBits stopBits = (StopBits)dictData["COM_STOP_BIT"]; Parity parity = (Parity)dictData["COM_PARITY"]; modem = new GSMModemDevice(PortName, BaudRate, 8, stopBits, parity); modem.OpenPort(); if (modem != null && modem.IsOpened()) { modem.InitModemConfig(); modem.setModemSIMReady(); Console.WriteLine(string.Format("{0}: GSM Modem ready on {1}", DateTime.Now, PortName)); break; } Console.WriteLine(string.Format("{0}: GSM Modem open port failed. Check your device is connected. Retry openmodem ", DateTime.Now)); Thread.Sleep(5000); } while (modem == null || !modem.IsOpened()); SerialPortService.PortsChanged += SerialPortService_PortsChanged; Thread threadServerSms = new Thread(RunServer); threadServerSms.IsBackground = true; threadServerSms.Start(); Console.WriteLine(string.Format("{0}: System is ready ...", DateTime.Now)); } catch (Exception ex) { LoggingData.WriteLog(ex); Console.WriteLine("{0:dd-MM-yyyy HH:mm:ss}: {1} \r\nStackTrace: {2}", DateTime.Now, ex.Message, ex.StackTrace); System.Diagnostics.Process.Start(System.AppDomain.CurrentDomain.BaseDirectory + "SmsProviderServerService.exe"); Environment.Exit(0); } }
public static Dictionary <string, GSMModemDevice> SearchModem() { try { int[] arrayBaudrate = new int[] { 115200 }; Dictionary <string, GSMModemDevice> lstResultDevices = new Dictionary <string, GSMModemDevice>(); List <string> ModemList = CommonFunctions.GetListModem(); List <string> PortListChecked = new List <string>(); foreach (string port in ModemList) { if (PortListChecked.Contains(port)) { continue; } foreach (int baudrateCheck in arrayBaudrate) { GSMModemDevice modemcom = new GSMModemDevice(port, baudrateCheck, 8, StopBits.One, Parity.None); if (!modemcom.OpenPort()) { modemcom.ClosePort(); modemcom.Dispose(); continue; } string response = modemcom.ExecuteCommands("AT", 500); if (!modemcom.CheckOK(response)) { modemcom.ClosePort(); modemcom.Dispose(); continue; } modemcom.InitModemConfig(); if (!modemcom.setModemSIMReady()) { modemcom.ClosePort(); modemcom.Dispose(); continue; } response = modemcom.ExecuteCommands("AT+GCAP", 200); if (!response.Contains("GSM")) { modemcom.ClosePort(); modemcom.Dispose(); continue; } modemcom.GetDeviceInfo(); modemcom.ClosePort(); if (!lstResultDevices.ContainsKey(port)) { lstResultDevices.Add(DateTime.Now.ToString("ddMMyyyyHHmmss"), modemcom); } if (!PortListChecked.Contains(port)) { PortListChecked.Add(port); } Thread.Sleep(200); } } return(lstResultDevices); } catch (Exception ex) { LoggingData.WriteLog(ex); return(null); } }