Sending utf-8 chars in SMS via GSM modem - c#

I'm using a Nokia 5228 to send a SMS via the COM port, and I get wrong symbols when I send UTF-8 chars. English chars are working good.
How can I solve that problem?
public static string SMSMessage = "Привет";
public static string CellNumber = "number...";
private void Form1_Load(object sender, EventArgs e)
{
sp = new SerialPort();
sp.PortName = "COM12";
sp.Encoding = UTF8Encoding.UTF8;
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (!sp.IsOpen)
{
sp.Open();
this.sp.WriteLine(#"AT" + (char)(13));
Thread.Sleep(200);
this.sp.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(200);
this.sp.WriteLine(#"AT+CMGS=""" + CellNumber + #"""" + (char)(13));
Thread.Sleep(200);
this.sp.WriteLine(SMSMessage + (char)(26));
}
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Exception : {0}", ex.Message), "Port Error");
}
}

The problem was, that I had to use UCS2.
this.sp.WriteLine(StringToUCS2("Привет, привіт !##%") + char.ConvertFromUtf32(26));
public static string StringToUCS2(string str)
{
UnicodeEncoding ue = new UnicodeEncoding();
byte[] ucs2 = ue.GetBytes(str);
int i = 0;
while (i < ucs2.Length)
{
byte b = ucs2[i + 1];
ucs2[i + 1] = ucs2[i];
ucs2[i] = b;
i += 2;
}
return BitConverter.ToString(ucs2).Replace("-", "");
}

Related

Console application crashing

Hi guys i have here a console application written in c# ,
I have spend all my week finding and looking for the reason why it sometimes suddenly crashing,
this console app is running continuously, no closing means when i run it it will kept running no shutting down of computer
I put every method with try catch and every catch exception it will write it to the logs
but when the application crashed there's no logs so that means there's exception that not being handled
can some one help find the possible reason why.
I'm drop off the whole code here.
class Program
{
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
protected static string server_hostname = ConfigurationManager.AppSettings["ServerHostname"];
protected static string copychimp_server = "";
protected static int port_number = 0;
private static byte[] _buffer = new byte[10000];
private static List<Socket> _clientSockets = new List<Socket>();
private static Socket _serverSocket = new Socket(Dns.GetHostEntry(ConfigurationManager.AppSettings["ServerHostname"]).AddressList[0].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
private static Dictionary<string, DateTime> dict_cmd_lastsent = new Dictionary<string, DateTime>();
private static Dictionary<string, double> dict_cmd_interval = new Dictionary<string, double>();
private static Dictionary<string, string> dict_drive = new Dictionary<string, string>();
private static Dictionary<string, string> dict_host = new Dictionary<string, string>();
static bool ConsoleEventCallback(int eventType)
{
if (eventType == 2)
{
}
return false;
}
static ConsoleEventDelegate handler; // Keeps it from getting garbage collected
// Pinvoke
private delegate bool ConsoleEventDelegate(int eventType);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
static void Main(string[] args)
{
Console.Write(" Enter copychimp server: ");
copychimp_server = Console.ReadLine();
Console.Write("Enter port number: ");
port_number = Convert.ToInt16(Console.ReadLine());
//copychimp_server = args[0].ToString().Trim();
//port_number = Convert.ToInt16(args[1]);
//Thread.Sleep(3000);
try
{
var server_logs_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\logs\\" + copychimp_server;
var server_config_dir = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\config";
var server_config = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\config\\" + copychimp_server + ".config";
if (!Directory.Exists(server_config_dir))
{
Directory.CreateDirectory(server_config_dir);
}
if (!Directory.Exists(server_logs_dir))
{
Directory.CreateDirectory(server_logs_dir);
}
var config = "";
config += "<port>" + port_number + "</port>";
config += Environment.NewLine;
try
{
var pid = GetTagValue(File.ReadAllText(server_config), "PID");
var test_pid = Process.GetProcessById(Convert.ToInt16(pid));
var pname = test_pid.ProcessName;
ServerLogs(pname + " is currently active using PID (" + pid + ")");
config += "<PID>" + pid + "</PID>";
File.WriteAllText(server_config, config);
}
catch (Exception ex)
{
config += "<PID>" + Process.GetCurrentProcess().Id + "</PID>";
File.WriteAllText(server_config, config);
handler = new ConsoleEventDelegate(ConsoleEventCallback);
const int SW_HIDE = 0;
var handle = GetConsoleWindow();
ShowWindow(handle, SW_HIDE); // To hide
ServerStarted();
Console.ReadKey();
}
}
catch (Exception ex)
{
ServerLogs("Main error: " + ex.Message.ToString());
}
}
private static void ServerStarted()
{
try
{
IPHostEntry hostEntry = Dns.GetHostEntry(server_hostname);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, port_number);
ServerLogs("CopyChimpServer.exe Started. Waiting for connection...");
_serverSocket.Bind(localEndPoint);
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (SocketException ex)
{
ServerLogs("ServerStarted Error " + ex.Message.ToString());
}
}
private static string ServerCommand(string hostname)
{
var command = "";
try
{
CopyChimpDB copychimp_db = new CopyChimpDB();
DataTable dt_robocopy = copychimp_db.GetCopyChimp("GetCommand", hostname, "");
if (dt_robocopy.Rows.Count == 1)
{
command = dt_robocopy.Rows[0]["command"].ToString();
}
else if (dt_robocopy.Rows.Count > 1)
{
ServerLogs(hostname + " GetCommand error: Returns more than 1 row.");
}
}
catch (Exception ex)
{
ServerLogs(hostname + " ServerCommand error " + ex.ToString());
}
return command;
}
private static void ReceiveCallBack(IAsyncResult AR)
{
Thread.Sleep(1000);
Socket socket = null;
string hostname = "";
string ip_address = "";
CopyChimpDB copychimp_db = new CopyChimpDB();
try
{
socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];
hostname = dict_host[ip_address];
byte[] dataBuff = new byte[received];
Array.Copy(_buffer, dataBuff, received);
string message_to_client = "wait";
if (Convert.ToDouble(Math.Round((DateTime.Now - Convert.ToDateTime(dict_cmd_lastsent[hostname])).TotalMinutes, 2)) >= dict_cmd_interval[hostname])
{
var server_command = ServerCommand(hostname);
if (server_command.Trim() != "")
{
//string message_from_client = WebUtility.HtmlDecode(Encoding.ASCII.GetString(dataBuff));
message_to_client += "<DriveName>" + dict_drive[hostname] + "</DriveName>";
message_to_client += "<ServerCommand>" + ServerCommand(hostname) + "</ServerCommand>";
try
{
copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);
}
catch (Exception oraex)
{
ServerLogs(hostname + "--" + oraex.ToString());
}
dict_cmd_lastsent[hostname] = DateTime.Now;
//ServerLogs(hostname + " updated");
}
}
byte[] data = Encoding.ASCII.GetBytes(message_to_client);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
}
catch (SocketException ex)
{
try
{
//_clientSockets.Remove(socket);
ServerLogs(hostname + " SocketException! " + ex.Message.ToString());
if (hostname != "")
{
try
{
copychimp_db.PostCopyChimp("DisconnectMachine", hostname, ip_address);
}
catch (Exception oraex)
{
ServerLogs(hostname + "--" + oraex.ToString());
}
}
}
catch (Exception ex_)
{
ServerLogs(hostname + " DisconnectMachine error! " + ex_.ToString());
}
}
}
private static Thread thread;
private static void AcceptCallback(IAsyncResult AR)
{
string hostname = "";
try
{
CopyChimpDB copychimp_db = new CopyChimpDB();
Socket socket = _serverSocket.EndAccept(AR);
string ip_address = "";
//hostname checking
ip_address = (socket.RemoteEndPoint as IPEndPoint).ToString().Split(':')[0];
try
{
try
{
hostname = Dns.GetHostEntry(ip_address).HostName;
}
catch (Exception host_ex)
{
ServerLogs(ip_address + " GetHostEntry error: " + host_ex.Message.ToString());
DataTable dt_ip = copychimp_db.GetCopyChimp("GetHostnameByIpAddress", hostname, ip_address);
if (dt_ip.Rows.Count == 1)
{
hostname = dt_ip.Rows[0]["hostname"].ToString();
ServerLogs(ip_address + " GetHostnameByIpAddress : " + hostname);
}
}
DataTable dt_hostname = copychimp_db.GetCopyChimp("GetHostname", hostname, ip_address);
hostname = "";
if (dt_hostname.Rows.Count == 1)
{
hostname = dt_hostname.Rows[0]["hostname"].ToString();
}
else if (dt_hostname.Rows.Count > 1)
{
ServerLogs(hostname + " GetHostname error: Returns more than 1 row.");
}
if (hostname != "")
{
if (!_clientSockets.Contains(socket))
{
dict_host[ip_address] = hostname;
_clientSockets.Add(socket);
copychimp_db.PostCopyChimp("ConnectMachine", hostname, ip_address);
/*------------------------------------------------------------------------------------------------*/
dict_cmd_interval[hostname] = Convert.ToDouble(copychimp_db.GetCopyChimp("GetInterval", hostname, ip_address).Rows[0]["interval"].ToString());
/*------------------------------------------------------------------------------------------------*/
dict_cmd_lastsent[hostname] = Convert.ToDateTime(copychimp_db.GetCopyChimp("GetLastUpdate", hostname, ip_address).Rows[0]["lastupdate"]);
/*------------------------------------------------------------------------------------------------*/
dict_drive[hostname] = copychimp_db.GetCopyChimp("GetDriveName", hostname, ip_address).Rows[0]["drive_name"].ToString();
/*------------------------------------------------------------------------------------------------*/
thread = new Thread(() =>
{
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
});
thread.Start();
ServerLogs(hostname + " connected");
}
}
}
catch (Exception oraex)
{
ServerLogs(hostname + "--" + oraex.ToString());
}
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (SocketException ex)
{
ServerLogs("AcceptCallback SocketException " + hostname + ex.Message.ToString());
}
}
private static void SendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
private static void ServerLogs(string text)
{
bool logging_success = false;
try
{
string logpath = System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\logs\\" + copychimp_server + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".log";
do
{
try
{
string log = "[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "]" + " " + text + Environment.NewLine;
if (!File.Exists(logpath))
{
File.WriteAllText(logpath, log);
}
else
{
File.AppendAllText(logpath, log);
}
logging_success = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
} while (logging_success == false);
}
catch (Exception ex)
{
//send emai
}
}
private static string GetTagValue(string text, string tag)
{
var result = "";
try
{
var start_tag = "<" + tag + ">";
var end_tag = "</" + tag + ">";
int pFrom = text.IndexOf(start_tag) + start_tag.Length;
int pTo = text.LastIndexOf(end_tag);
result = text.Substring(pFrom, pTo - pFrom);
}
catch (Exception ex)
{
ServerLogs("GetTagValue() error " + ex.Message.ToString());
}
return result;
}
}
A help a highly appreciated thank you in advance.
I need to log it on the DB before the crushing occurred and i'm going to use it as reference for a new automatic emailing if the app crashed.

How to transfer the data from Chrome Browser Console onto C# file

We are getting joint data in JSON Objects format. The data is streaming live on the Chrome Console as you can see in the picture.
How do we take this data (from the Chrome Console) and send it over to a C# file on the computer in real-time?
From Console: JSON Object data from kinectv2
Here is some basic c# websocket code, it doesnt have to convert the data it receives to a string. I was just testing some stuff
C# simple websocket connection
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
public partial class MainWindow : Window
{
private Websocket_listen _listener;
public MainWindow()
{
_listener = new Websocket_listen("127.0.0.1", 13000);
_listener.StringReceived += _listener_StringReceived;
_listener.Start();
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
_running = false;
_listener.Stop();
}
private void _listener_StringReceived(string received)
{
}
}
public class Websocket_listen
{
public readonly int port = 13000;
public readonly IPAddress localAddr;
private TcpListener server = null;
private TcpClient client = null;
private NetworkStream stream = null;
private bool connected = false;
private byte[] bytes = new byte[2048];
private byte[] _last_key = new byte[4];
private int _last_message_length;
private bool read_more_message;
private Thread _current_thread;
private bool _running = true;
private int _received = 0;
private StringBuilder _results = new StringBuilder();
public event Action<string> StringReceived = null;
public Websocket_listen(string ipaddress, int port)
{
this.port = port;
localAddr = IPAddress.Parse(ipaddress);
server = new TcpListener(localAddr, port);
}
public void _running_loop()
{
while (_running)
{
try
{
server.Server.ReceiveTimeout = 5000;
server.Server.SendTimeout = 5000;
client = server.AcceptTcpClient();
// Get a stream object for reading and writing
stream = client.GetStream();
}
catch (Exception ex)
{
continue;
}
while (_running)
{
try
{
try
{
l.AcquireWriterLock(-1);
if (messsages.Count > 0)
{
byte[] msg = System.Text.Encoding.ASCII.GetBytes(messsages[0]);
//byte[] msg = System.Text.Encoding.ASCII.GetBytes("Connected to " + Environment.MachineName);
Array.Copy(msg, 0, bytes, 2, msg.Length);
bytes[0] = 0x81;
bytes[1] = (byte)msg.Length;
// Send back a response.
stream.Write(bytes, 0, msg.Length + 2);
messsages.RemoveAt(0);
}
}
finally
{
l.ReleaseWriterLock();
}
}
catch { }
try
{
_received = stream.Read(bytes, 0, bytes.Length);
}
catch
{
continue;
}
if (_received == 0)
continue;
if (!connected)
{
_is_connection();
continue;
}
if (!_parse_message())
break;
}
}
try
{
stream.Close();
client.Close();
}
catch (Exception ex)
{
}
}
private bool _parse_message()
{
int offset = 0;
int message_length = 0;
if (read_more_message)
{
_last_message_length -= bytes.Length;
message_length = _last_message_length;
if (message_length < bytes.Length)
message_length += 8;
}
else
{
_results.Clear();
var trigger = bytes[0];
var magic_byte = bytes[1];
bool is_text = (0x1 & trigger) != 0;
bool is_fin = (0x80 & trigger) != 0;
if (trigger == 0x88)
{
connected = false;
return false;
}
/*
text = 0x81
binary = 0x82
close 0x88
ping 0x89
pong -0x8A
*/
if (!is_fin)
{
return true;
}
if (!is_text)
{
return true;
}
//If the second byte minus 128 is between 0 and 125, this is the length of message.
//If it is 126, the following 2 bytes (16-bit unsigned integer), if 127, the following 8 bytes (64-bit unsigned integer) are the length.
var r = magic_byte - 128;
var key_starts_at = 0;
if (r <= 125)
{
key_starts_at = 2;
message_length = r;
}
else if (r == 126)
{
key_starts_at = 4;
message_length = BitConverter.ToUInt16(new byte[] { bytes[3], bytes[2] }, 0);
}
else if (r == 127)
{
key_starts_at = 10;
for (var m = 7; m >= 0; --m)
{
message_length += bytes[m] << (8 * (7 - m));
}
}
else
{
// not documented
}
//// because its encoded
_last_message_length = message_length;
Array.Copy(bytes, key_starts_at, _last_key, 0, 4);
offset = key_starts_at + 4;
}
for (var mx = 0; mx < message_length && offset + mx < bytes.Length; ++mx)
{
bytes[offset + mx] = (byte)(bytes[offset + mx] ^ _last_key[mx % 4]);
}
var new_result = System.Text.Encoding.ASCII.GetString(bytes, offset, Math.Min(message_length, bytes.Length - offset));
_results.Append(new_result);
read_more_message = message_length > bytes.Length;
if (!read_more_message)
{
try
{
StringReceived?.Invoke(_results.ToString());
}
catch (Exception ex)
{
}
}
return true;
}
private void _is_connection()
{
try
{
string data = System.Text.Encoding.ASCII.GetString(bytes, 0, _received);
if (!new Regex("^GET").IsMatch(data))
return;
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
connected = true;
}
catch (Exception ex)
{
}
}
public void Stop()
{
_running = false;
}
public void Start()
{
// Start listening for client requests.
server.Start();
_current_thread = new Thread(new ThreadStart(_running_loop));
_current_thread.Start();
}
ReaderWriterLock l = new ReaderWriterLock();
List<string> messsages = new List<string>();
internal void Send(string msg)
{
try
{
l.AcquireWriterLock(-1);
messsages.Add(msg);
}
catch
{
}
finally
{
l.ReleaseWriterLock();
}
}
}
not a very robust javascript simple websocket to connect to c# with the same port
try {
var isopen = false;
connection = new WebSocket('ws://127.0.0.1:13000');
// When the connection is open, send some data to the server
connection.onopen = function () {
isopen = true;
connection.send('Ping'); // Send the message 'Ping' to the server
$('#open_messages').html("connection made\r\n<br>");
$('#socket_errors').html("");
};
// Log errors
connection.onerror = function (error) {
console.log('WebSocket Error ', error);
$('#socket_errors').html(error.currentTarget.url + " failed\r\n<br><button id=\"reconnect\">Try to connect</button>");
};
// Log messages from the server
connection.onmessage = function (e) {
console.log('Server: ', e);
$('#messages').append(e.data + "\r\n<br>");
};
connection.onclose = function(x) {
console.log('closed ', x);
$('#open_messages').html("Disconnected\r\n<br>");
$('#socket_errors').html("<button id=\"reconnect\">Connect</button>");
};
} catch (err) {
console.log(err);
}
That should get you started sending data back and forth, but will probably need extra exception handling.
Not sure if sending strings across is efficient, by you could probably change the data later.

How do I send a Ping request three times?

I'm new to this site and I am a beginner at programming. I am trying to get this program to ping three times every time the send button is hit. I want the pingDetailsTextBox to say something similar to this: Pinging www.yahoo.com . . .
98.139.180.149 41ms
98.139.180.149 56ms
98.139.180.149 51ms
I have tried several different things to get it to work, but the code is just beyond my knowledge.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Net.NetworkInformation;
using System.Globalization;
namespace Microsoft.Samples.PingClient
{
partial class PingClientForm : Form
{
Ping pingClient = new Ping();
public PingClientForm()
{
InitializeComponent();
pingClient.PingCompleted +=
new PingCompletedEventHandler(pingClient_PingCompleted);
}
private void pingClient_PingCompleted(object sender, PingCompletedEventArgs e)
{
// Check to see if an error occurred. If no error, then display
// the address used and the ping time in milliseconds.
if (e.Error == null)
{
if (e.Cancelled)
{
pingDetailsTextBox.Text += " Ping cancelled. \r\n";
}
else
{
if (e.Reply.Status == IPStatus.Success)
{
pingDetailsTextBox.Text +=
" " + e.Reply.Address.ToString() + " " +
e.Reply.RoundtripTime.ToString(
NumberFormatInfo.CurrentInfo) + "ms" + "\r\n";
}
else
{
pingDetailsTextBox.Text +=
" " + GetStatusString(e.Reply.Status) + "\r\n";
}
}
}
else
{
// Otherwise display the error.
pingDetailsTextBox.Text += " Ping error.\r\n";
MessageBox.Show(
"An error occurred while sending this ping. " +
e.Error.InnerException.Message);
}
sendButton.Enabled = true;
}
private string GetStatusString(IPStatus status)
{
switch (status)
{
case IPStatus.Success:
return "Success.";
case IPStatus.DestinationHostUnreachable:
return "Destination host unreachable.";
case IPStatus.DestinationNetworkUnreachable:
return "Destination network unreachable.";
case IPStatus.DestinationPortUnreachable:
return "Destination port unreachable.";
case IPStatus.DestinationProtocolUnreachable:
return "Destination protocol unreachable.";
case IPStatus.PacketTooBig:
return "Packet too big.";
case IPStatus.TtlExpired:
return "TTL expired.";
case IPStatus.ParameterProblem:
return "Parameter problem.";
case IPStatus.SourceQuench:
return "Source quench.";
case IPStatus.TimedOut:
return "Timed out.";
default:
return "Ping failed.";
}
}
private void sendButton_Click(object sender, EventArgs e)
{
// Select all the text in the address box.
addressTextBox.SelectAll();
if (addressTextBox.Text.Length != 0)
{
// Disable the Send button.
sendButton.Enabled = false;
pingDetailsTextBox.Text +=
"Pinging " + addressTextBox.Text + " . . .\r\n";
// Send ping request.
pingClient.SendAsync(addressTextBox.Text, null);
}
else
{
MessageBox.Show("Please enter an IP address or host name.");
}
}
private void cancelButton_Click(object sender, EventArgs e)
{
// Cancel any pending pings.
pingClient.SendAsyncCancel();
}
}
}
Okay, I checked the documentation and I think what you can do is make the following edits instead:
int pingCount = 0;
private void pingClient_PingCompleted(object sender, PingCompletedEventArgs e)
{
pingCount++;
//if error else logic etc
if(pingCount < 3) {
pingClient.SendAsync(addressTextBox.Text, null);
} else {
sendButton.Enabled = true;
}
}
private void sendButton_Click(object sender, EventArgs e)
{
pingCount = 0;
//etc
}
Why do you need to do .SendAsync() and that PingCompleted bit? I just do .Send():
public static IPStatus CheckConn(string host, ref PingReply pngReply)
{
Ping png = new Ping();
try
{
pngReply = png.Send(host);
return pngReply.Status;
}
catch (Exception ex)
{
MessageBox.Show("Exception: " + ex.Message());
}
}
Then you can just get the IPStatus returned and use ref to get the pngReply back out with this:
private void sendButton_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
btn.Enabled = false;
string host = addressTextBox.Text;
pingDetailsTextBox.Text = String.Empty;
PingReply pngReply = null;
IPStatus ipStatus;
string strStatus = String.Empty;
if (!String.IsNullOrEmpty(host))
{
for (int i=0; i < 3; i++)
{
pingDetailsTextBox.Text +=
"Pinging " + host + " . . .\r\n";
ipStatus = CheckConn(host, ref pngReply);
strStatus = GetStatusString(ipStatus);
if (ipStatus == IPStatus.Success)
{
pingDetailsTextBox.Text +=
" " + pngReply.Address.ToString() + " " +
pngReply.RoundtripTime.ToString(
NumberFormatInfo.CurrentInfo) + "ms" + "\r\n";
}
else
{
pingDetailsTextBox.Text +=
" " + strStatus + "\r\n";
}
}
}
else
MessageBox.Show("No host to ping.");
btn.Enabled = true;
}

multicasting from c# to android using UDP

I have developed UDP multicast server in c# and UDP multicast reciever in Android,but iam not able to recieve data from server to client(Android).Is it because of the port numbers
i have used in code ? Your help is greatly appretiated and will save me nights.
***Server code
namespace Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UdpClient udpclient = new UdpClient();
IPAddress multicastaddress = IPAddress.Parse("233.45.17.10");
udpclient.JoinMulticastGroup(multicastaddress);
IPEndPoint remoteep = new IPEndPoint(multicastaddress, 10000);
Byte[] buffer = null;
for (int i=1;i<30;i++)
{
buffer = Encoding.Unicode.GetBytes(i.ToString());
int flag = udpclient.Send(buffer, buffer.Length, remoteep);
}
MessageBox.Show("Data Sent TO " + ip.Text + "On Port " + port.Text);
status.Text = "Connected";
}
private void disconnect_Click(object sender, EventArgs e)
{
this.Close();
}
}
}***
Client code(Android):
public class TestMulticast extends Activity
{
static boolean done = false;
EditText et;
TextView tv;
Button b;
MulticastSocket socket;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b=(Button)findViewById(R.id.b);
et=(EditText)findViewById(R.id.et);
tv =(TextView)findViewById(R.id.tv);
b.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v)
{
try
{
String msg = et.getText().toString();
socket.send(new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, InetAddress.getByName("192.168.1.6"), 10000));
Toast.makeText(getApplicationContext(), "sent", 100).show();
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
if (!done)
{
try
{
WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiinfo = wifiManager.getConnectionInfo();
int intaddr = wifiinfo.getIpAddress();
if (intaddr == 0)
{
tv.setText("Unable to get WIFI IP address");
}
else
{
byte[] byteaddr = null;
byteaddr = new byte[] {
(byte)(intaddr & 0xff),
(byte)(intaddr >> 8 & 0xff),
(byte)(intaddr >> 16 & 0xff),
(byte)(intaddr >> 24 & 0xff)
};
String machineName = "androidtestdevice";
InetAddress addr = InetAddress.getByAddress(machineName, byteaddr);
tv.append("Using address: " + addr + "\n");
Toast.makeText(getApplicationContext(), "using address"+addr, 50).show();
// create socket
socket = new MulticastSocket(11111);
// set network interface
NetworkInterface iface = NetworkInterface.getByInetAddress(addr);
Toast.makeText(getApplicationContext(), "First address on interface is: " + getAddressFor(iface), 50).show();
tv.append("First address on interface is: " + getAddressFor(iface) + "\n");
// The following line throws an exception in Android (Address is not available)
// If it's not called, the socket can receives packets
// Equivalent code in seems to C work.
//socket.setNetworkInterface(iface);
// join group
socket.joinGroup(InetAddress.getByName("233.45.17.10"));
tv.append("It worked\n");
// start receiving
new DatagramListener(socket, tv).start();
}
}
catch (Exception e) {
tv.append(e.toString() + "\n");
e.printStackTrace();
}
}
}
class DatagramListener extends Thread {
private DatagramSocket socket;
private TextView tv;
DatagramListener(DatagramSocket s, TextView tv) {
socket = s;
this.tv = tv;
}
public void run() {
byte[] buf = new byte[1000];
try {
while (true) {
DatagramPacket recv = new DatagramPacket(buf, buf.length);
socket.receive(recv);
System.out.println("received: " + new String(recv.getData(), recv.getOffset(), recv.getLength()));
runOnUiThread(new MyRunnable(new String(recv.getData(), recv.getOffset(), recv.getLength()), tv));
Toast.makeText(getApplicationContext(), "Now showing data", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "received: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
static private class MyRunnable implements Runnable {
private TextView tv;
private String text;
public MyRunnable(String text, TextView tv) {
this.tv = tv;
this.text = text;
}
public void run() {
tv.append(text + "\n");
}
}
public static InetAddress getAddressFor(NetworkInterface iface) {
Enumeration<InetAddress> theAddresses = iface.getInetAddresses();
boolean found = false;
InetAddress firstAddress = null;
while ((theAddresses.hasMoreElements()) && (found != true)) {
InetAddress theAddress = theAddresses.nextElement();
if (theAddress instanceof Inet4Address) {
firstAddress = theAddress;
found = true;
}
}
return firstAddress;
}
}
Multicast packets are filtered in many android devices depending on vendor (some do others don't htc would filter it most likely), presumably to save battery. it is not blocked in android as such but the vendors.

SMS connecting to a phone from C# and getting a response

I wrote code to send an SMS using my GSM phone which is attached to the computer through COM port. The code is below.
The problem is I do see that it is in the outbox of the phone and it actually appears to have been sent, but when I contact the recipient they say that I have not received the message.
I test the phone, and I create and send a message using only the phone and it works perfectly. However, when I do this with my code, it APPEARS to have been sent, and I am getting all the correct AT COMMAND responses from the phone, but the message is actually NOT sent.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SerialPort serialPort1;
int m_iTxtMsgState = 0;
const int NUM_MESSAGE_STATES = 4;
const string RESERVED_COM_1 = "COM1";
const string RESERVED_COM_4 = "COM4";
public Form1()
{
InitializeComponent();
this.Closing += new CancelEventHandler(Form1_Closing);
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1 = new SerialPort(GetUSBComPort());
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
serialPort1.Open();
//ThreadStart myThreadDelegate = new ThreadStart(ReceiveAndOutput);
//Thread myThread = new Thread(myThreadDelegate);
//myThread.Start();
this.serialPort1.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
}
private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
serialPort1.Close();
}
private void SendLine(string sLine)
{
serialPort1.Write(sLine);
sLine = sLine.Replace("\u001A", "");
consoleOut.Text += sLine;
}
public void DoWork()
{
ProcessMessageState();
}
public void ProcessMessageState()
{
switch (m_iTxtMsgState)
{
case 0:
m_iTxtMsgState = 1;
SendLine("AT\r\n"); //NOTE: SendLine must be the last thing called in all of these!
break;
case 1:
m_iTxtMsgState = 2;
SendLine("AT+CMGF=1\r\n");
break;
case 2:
m_iTxtMsgState = 3;
SendLine("AT+CMGW=" + Convert.ToChar(34) + "+9737387467" + Convert.ToChar(34) + "\r\n");
break;
case 3:
m_iTxtMsgState = 4;
SendLine("A simple demo of SMS text messaging." + Convert.ToChar(26));
break;
case 4:
m_iTxtMsgState = 5;
break;
case 5:
m_iTxtMsgState = NUM_MESSAGE_STATES;
break;
}
}
private string GetStoredSMSID()
{
return null;
}
/* //I don't think this part does anything
private void serialPort1_DataReceived_1(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string response = serialPort1.ReadLine();
this.BeginInvoke(new MethodInvoker(() => textBox1.AppendText(response + "\r\n")));
}
*/
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(500);
char[] msg;
msg = new char[613];
int iNumToRead = serialPort1.BytesToRead;
serialPort1.Read(msg, 0, iNumToRead);
string response = new string(msg);
this.BeginInvoke(new MethodInvoker(() => textBox1.AppendText(response + "\r\n")));
serialPort1.DiscardInBuffer();
if (m_iTxtMsgState == 4)
{
int pos_cmgw = response.IndexOf("+CMGW:");
string cmgw_num = response.Substring(pos_cmgw + 7, 4);
SendLine("AT+CMSS=" + cmgw_num + "\r\n");
//stop listening to messages received
}
if (m_iTxtMsgState < NUM_MESSAGE_STATES)
{
ProcessMessageState();
}
}
catch
{ }
}
private void button1_Click(object sender, EventArgs e)
{
m_iTxtMsgState = 0;
DoWork();
}
private void button2_Click(object sender, EventArgs e)
{
string[] sPorts = SerialPort.GetPortNames();
foreach (string port in sPorts)
{
consoleOut.Text += port + "\r\n";
}
}
private string GetUSBComPort()
{
string[] sPorts = SerialPort.GetPortNames();
foreach (string port in sPorts)
{
if (port != RESERVED_COM_1
&& port != RESERVED_COM_4)
{
return port;
}
}
return null;
}
}
This is my code that works (tested) with U9 Telia cellular modem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Configuration;
using UsbEject.Library;
using Utils;
namespace Hardware
{
public class TeliaModem : IDisposable
{
public delegate void NewSmsHandler(InboundSMS sms);
public event NewSmsHandler OnNewSMS;
#region private data
System.IO.Ports.SerialPort modemPort;
Timeouter _lastModemKeepAlive;
private delegate void DataReceivedDelegate();
private DataReceivedDelegate dataReceivedDelegate;
Queue<OutboundSMS> _outSmses = new Queue<OutboundSMS>();
enum ModemState
{
Error = -1, NotInitialized, PowerUp, Initializing, Idle,
SendingSMS, KeepAliveAwaitingResponse
};
Timeouter ModemStateTimeouter = new Timeouter(timeout_s: 10, autoReset: false);
ModemState _modemState = ModemState.NotInitialized;
ModemState CurrentModemState
{
get
{
return _modemState;
}
set
{
_modemState = value;
ModemStateTimeouter.Reset();
NihLog.Write(NihLog.Level.Debug, "State changed to: " + value.ToString());
}
}
private System.Windows.Forms.Control _mainThreadOwnder;
#endregion
public TeliaModem(System.Windows.Forms.Control mainThreadOwnder)
{
_mainThreadOwnder = mainThreadOwnder;
dataReceivedDelegate = new DataReceivedDelegate(OnDataReceived);
}
public void SendSMS(string phone, string text)
{
_outSmses.Enqueue(new OutboundSMS(phone, text));
HeartBeat();
}
private void SendSmsNow()
{
OutboundSMS sms = _outSmses.Peek();
sms.Attempt++;
if (sms.Attempt > sms.MaxTries)
{
NihLog.Write(NihLog.Level.Error, "Failure to send after " + sms.MaxTries + " tries");
_outSmses.Dequeue();
return;
}
NihLog.Write(NihLog.Level.Info, "Sending SMS: " + sms.ToString());
WriteToModem("AT+CMGS=\"" + sms.Destination + "\"\r");
System.Threading.Thread.Sleep(500);
WriteToModem(sms.Text);
byte[] buffer = new byte[1];
buffer[0] = 26; // ^Z
modemPort.Write(buffer, offset:0, count:1);
CurrentModemState = ModemState.SendingSMS;
}
public void Dispose()
{
UninitModem();
}
public void HeartBeat()
{
if (CurrentModemState == ModemState.NotInitialized)
{
TryInitModem();
return;
}
if (IsTransitionalState(CurrentModemState) && ModemStateTimeouter.IsTimedOut())
{
NihLog.Write(NihLog.Level.Error, "Modem error. Timed out during " + CurrentModemState);
CurrentModemState = ModemState.Error;
return;
}
if (CurrentModemState == ModemState.Idle && _lastModemKeepAlive.IsTimedOut())
{
// Send keepalive
WriteToModem("AT\r");
CurrentModemState = ModemState.KeepAliveAwaitingResponse;
return;
}
if (CurrentModemState == ModemState.Error)
{
NihLog.Write(NihLog.Level.Debug, "Reenumerating modem...");
UninitModem();
return;
}
if (_outSmses.Count != 0 && CurrentModemState == ModemState.Idle)
{
SendSmsNow();
return;
}
}
private string pendingData;
private void OnDataReceived()
{
// Called in the main thread
string nowWhat = modemPort.ReadExisting();
pendingData += nowWhat;
string[] lines = pendingData.Split(new string[] { "\r\n" }, StringSplitOptions.None);
if (lines.Length == 0)
{
pendingData = string.Empty;
return;
}
else
{
pendingData = lines[lines.Length - 1];
}
// This happens in main thread.
for (int i = 0; i < lines.Length - 1; i++)
{
string line = lines[i];
if (line.Length >= 5 && line.Substring(0, 5) == "+CMT:")
{
// s+= read one more line
if (i == lines.Length - 1) // no next line
{
pendingData = line + "\r\n" + pendingData; // unread the line
continue;
}
string line2 = lines[++i];
NihLog.Write(NihLog.Level.Debug, "RX " + line);
NihLog.Write(NihLog.Level.Debug, "RX " + line2);
InboundSMS sms = new InboundSMS();
sms.ParseCMT(line, line2);
if(OnNewSMS != null)
OnNewSMS(sms);
}
else // Not a composite
NihLog.Write(NihLog.Level.Debug, "RX " + line);
if (line == "OK")
{
OnModemResponse(true);
}
else if (line == "ERROR")
{
OnModemResponse(false);
NihLog.Write(NihLog.Level.Error, "Modem error");
}
}
}
private void ProcessSmsResult(bool ok)
{
if (!ok)
{
OutboundSMS sms = _outSmses.Peek();
if (sms.Attempt < sms.MaxTries)
{
NihLog.Write(NihLog.Level.Info, "Retrying sms...");
return;
}
NihLog.Write(NihLog.Level.Error, "Failed to send SMS: " + sms.ToString());
}
_outSmses.Dequeue();
}
private void OnModemResponse(bool ok)
{
if (CurrentModemState == ModemState.SendingSMS)
ProcessSmsResult(ok);
if (!ok)
{
NihLog.Write(NihLog.Level.Error, "Error during state " + CurrentModemState.ToString());
CurrentModemState = ModemState.Error;
return;
}
switch (CurrentModemState)
{
case ModemState.NotInitialized:
return;
case ModemState.PowerUp:
WriteToModem("ATE0;+CMGF=1;+CSCS=\"IRA\";+CNMI=1,2\r");
CurrentModemState = ModemState.Initializing;
break;
case ModemState.Initializing:
case ModemState.SendingSMS:
case ModemState.KeepAliveAwaitingResponse:
CurrentModemState = ModemState.Idle;
break;
}
}
private void CloseU9TelitNativeApp()
{
bool doneSomething;
do
{
doneSomething = false;
Process[] processes = Process.GetProcessesByName("wirelesscard");
foreach (Process p in processes)
{
p.CloseMainWindow();
doneSomething = true;
NihLog.Write(NihLog.Level.Info, "Killed native U9 app");
System.Threading.Thread.Sleep(1000); // Will not wait if no native app is started
}
} while (doneSomething);
}
void WriteToModem(string s)
{
modemPort.Write(s);
NihLog.Write(NihLog.Level.Debug, "TX " + s);
}
void UninitModem()
{
if (modemPort != null)
modemPort.Dispose();
modemPort = null;
CurrentModemState = ModemState.NotInitialized;
}
private bool IsTransitionalState(ModemState ms)
{
return ms == ModemState.Initializing
|| ms == ModemState.SendingSMS
|| ms == ModemState.PowerUp
|| ms == ModemState.KeepAliveAwaitingResponse;
}
Timeouter _initFailureTimeout =
new Timeouter(timeout_s: 10, autoReset:false, timedOut:true);
void TryInitModem()
{
// Try pistoning the modem with higher frequency. This does no harm (such as redundant logging)
PrepareU9Modem(); // Will do nothing if modem is okay
if (!_initFailureTimeout.IsTimedOut())
return; // Don't try too frequently
if (modemPort != null)
return;
const string modemPortName = "Basecom HS-USB NMEA 9000";
const int speed = 115200;
string portName = Hardware.Misc.SerialPortFromFriendlyName(modemPortName);
if (portName == null)
{
NihLog.Write(NihLog.Level.Error, "Modem not found (yet). ");
_initFailureTimeout.Reset();
return;
}
NihLog.Write(NihLog.Level.Info, string.Format("Found modem port \"{0}\" at {1}", modemPortName, portName));
modemPort = new System.IO.Ports.SerialPort(portName, speed);
modemPort.ReadTimeout = 3000;
modemPort.NewLine = "\r\n";
modemPort.Open();
modemPort.DiscardInBuffer();
modemPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(delegate { _mainThreadOwnder.Invoke(dataReceivedDelegate); }); // called in different thread!
_lastModemKeepAlive = new Timeouter(60, true);
WriteToModem("AT+CFUN=1\r");
CurrentModemState = ModemState.PowerUp;
}
void CheatU9Telit()
{
// U9 telit appears as USB CDrom on the bus, until disk eject is sent.
// Then, it reappears as normal stuff.
VolumeDeviceClass volumeDeviceClass = new VolumeDeviceClass();
foreach (Volume device in volumeDeviceClass.Devices)
{
if (device.FriendlyName == "PCL HSUPA Modem USB Device")
{
NihLog.Write(NihLog.Level.Info, "Trying to initialize: " + device.FriendlyName);
device.EjectCDRomNoUI();
}
}
}
void PrepareU9Modem()
{
CloseU9TelitNativeApp(); // Closes the autorun native app
CheatU9Telit();
}
}
public class OutboundSMS
{
public string Destination;
public string Text;
public int MaxTries;
public int Attempt = 0;
public OutboundSMS(string dest, string txt)
{
Destination = dest;
Text = txt;
MaxTries = 3;
}
override public string ToString()
{
if(Attempt > 1)
return string.Format("\"{0}\" to {1}, attempt {2}",
Text, Destination, Attempt);
else
return string.Format("\"{0}\" to {1}",
Text, Destination);
}
}
public class InboundSMS
{
public string SourcePhone;
public DateTime ReceiveTime;
public string Text;
public void ParseCMT(string line1, string line2)
{
string[] fields = line1.Split(new char[] { ',', ' ', '/', ':', '"' });
if (fields.Length < 12)
throw new ApplicationException("CMT message too short. Expected 2 fields");
SourcePhone = fields[3];
ReceiveTime = DateTime.Parse("20" + fields[7] + "-" + fields[8] + "-" + fields[9] + " " + fields[10] + ":" + fields[11] + ":" + fields[12].Substring(0, 2)); //test carefully
Text = line2;
}
};
}
Usage example in a winforms application:
Hardware.TeliaModem _modem;
public Form1()
{
InitializeComponent();
_modem = new Hardware.TeliaModem(this);
_modem.OnNewSMS += new Hardware.TeliaModem.NewSmsHandler(ProcessNewSMS);
_timer.Interval = 1000; // milliseconds
_timer.Tick += new EventHandler(OnTimerTick);
_timer.Start();
}
To send an SMS:
_modem.SendSMS(sms.SourcePhone, "Aircon is now " + BoolToString.ON_OFF(_aircon.On));
On timer event, once every second:
private void OnTimerTick(object o, EventArgs e)
{
_modem.HeartBeat();
}
This is registered as Winforms timer handler, so that modem will not have a thread.
Some utility classes used:
namespace Utils
{
public class StopWatch
{
protected DateTime _resetTime;
public StopWatch() { Reset(); }
public void Reset() { _resetTime = DateTime.Now; }
public double TotalSeconds { get { return (DateTime.Now - _resetTime).TotalSeconds; } }
public TimeSpan Time { get { return DateTime.Now - _resetTime; } }
};
public class Timeouter : StopWatch
{
private bool _autoReset;
private double _timeout_s;
public Timeouter(double timeout_s, bool autoReset, bool timedOut = false)
{
_timeout_s = timeout_s;
_autoReset = autoReset;
if (timedOut)
_resetTime -= TimeSpan.FromSeconds(_timeout_s + 1); // This is surely timed out, as requested
}
public bool IsTimedOut()
{
if (_timeout_s == double.PositiveInfinity)
return false;
bool timedout = this.TotalSeconds >= _timeout_s;
if (timedout && _autoReset)
Reset();
return timedout;
}
public void Reset(double timeout_s) { _timeout_s = timeout_s; Reset(); }
public double TimeLeft { get { return _timeout_s - TotalSeconds; } }
}
}
I implemented this in order to turn on air conditioner with SMS (yeah, I live in a hot country). It works. Please feel free to use any of this code.
Enjoy.
Microsoft provides a pretty decent VB.Net example in a KB article "How to access serial and parallel ports by using Visual Basic .NET". I'm not sure what your phone returns, however, if you change the buffer loop in the example, you can at least print out the reply:
MSComm1.Output = "AT" & Chr(13)
Console.WriteLine("Send the attention command to the modem.")
Console.WriteLine("Wait for the data to come back to the serial port...")
' Make sure that the modem responds with "OK".
' Wait for the data to come back to the serial port.
Do
Buffer = Buffer & MSComm1.Input
Console.WriteLine("Found: {0}", Buffer)
Loop Until InStr(Buffer, "OK" & vbCrLf)
GSMComm is a C# library that will allow you to easily interact with a GSM mobile in text or PDU mode. (The site also has a bunch of testing utilities)
Working with GSM modem to send SMS has never been a good idea as such. Here's a checklist to make sure your SMS is sent out properly.
You are sending the SMS in text mode. Try sending it in PDU mode.
Try this library http://phonemanager.codeplex.com/
Do you change SMSC number before sending out the SMS, if so make sure the SMSC is correct.
Also make sure your SIM card has enough credits to let you send outbound SMS.
Check the network status especially when you're sending out SMS from your program. This might be a problem.
I recommend you checkout the Lite edition of NowSMS gateway that comes for free and lets you work with GSM modem very continently. NowSMS will give you api abstraction over a GSM modem connection, so you wil just need to call the Http Api of NowSMS gateway, rest will be taken care by the NowSMS gateway.
Above all this, if your end-users are going to remain internet connected while using your application or if your application is web-based and hosted over internet, I strongly recoomend to do away with GSM modem option and opt-in for reliable Http SMS gateway service providers.

Categories