Trying to develop small application using GsmComm Library.
At the moment a have some problems with detecting if phone is connected or no.
it's detects when phone is disconnected, but doesn't want to detect phone when is connected back again ...
Any idea why ?
my code:
GsmCommMain gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
gsm.PhoneConnected += new EventHandler(gsmPhoneConnected);
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}
Sorry for late answer. Just noticed your question.
There is no need to use EventHandler for connection. If you want to call some functions after phone/gsm modem is connected you should call them after you opened port and (!) checked whether connection is established using IsConnected() member function in GsmCommMain class.
var gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
//gsm.PhoneConnected += new EventHandler(gsmPhoneConnected); // not needed..
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
if(gsm.IsConnected()){
this.onPhoneConnectedChange(true);
}
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
/*public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}*/
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}
Related
I'm trying to check my RDP credentials using c#
Here is my reference : Remote Desktop using C#.NET
And here is what I've done so far :
private void testBtn_Click(object sender, EventArgs e) {
try {
AxMsRdpClient8NotSafeForScripting ax = new AxMsRdpClient8NotSafeForScripting();
ax.OnLoginComplete += Ax_OnLoginComplete;
ax.OnLogonError += Ax_OnLogonError;
ax.OnFatalError += Ax_OnFatalError;
ax.Size = new Size(1, 1);
ax.CreateControl();
ax.Server = ipTbx.Text;
ax.UserName = userNameTbx.Text;
MsRdpClient8NotSafeForScripting sec = (MsRdpClient8NotSafeForScripting)ax.GetOcx();
sec.AdvancedSettings8.ClearTextPassword = passwordTbx.Text;
sec.AdvancedSettings8.EnableCredSspSupport = true;
ax.Connect();
} catch (Exception ex) {
MessageBox.Show("Error : " + ex.Message);
}
}
private void Ax_OnFatalError(object sender, IMsTscAxEvents_OnFatalErrorEvent e) {
SaySomething();
}
private void Ax_OnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e) {
SaySomething();
}
private void Ax_OnLoginComplete(object sender, EventArgs e) {
SaySomething();
}
public void SaySomething() {
MessageBox.Show("Worked!");
}
As you can see, I've done everything in the article way. But nothing happens, even an exception would be worthy.
Any Idea?
I trying to do an inteface to monitoring the Serial Port. I am using Visual forms. So, I had created a combobox to select the PortCOM, a TextBox to send the data to Serial Port and a TextBoxReceber to receive the Serial Data. I trying print the data received in the TextBoxReceber, I'm using the AppendText but I haven't sucess. Anybody can help me?
My Form1.cs is:
namespace ConsoleESP
{
public partial class Form1 : Form
{
string RxString = "";
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
atualizaCOMs();
}
private void atualizaCOMs()
{
int i = 0;
bool quantDif = false;
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDif = true;
}
}
}
else quantDif = true;
if (quantDif == false) return;
comboBox1.Items.Clear();
foreach(string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
comboBox1.SelectedIndex = 0;
}
private void timerCOM_Tick(object sender, EventArgs e)
{
atualizaCOMs();
}
private void btConnect_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen == false)
{
try
{
serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
}
catch
{
return;
}
if (serialPort1.IsOpen)
{
btConnect.Text = "Desconectar";
comboBox1.Enabled = false;
}
}
else
{
try
{
serialPort1.Close();
comboBox1.Enabled = true;
btConnect.Text = "Conectar";
}
catch
{
return;
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (serialPort1.IsOpen == true) serialPort1.Close();
}
private void btEnviar_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
serialPort1.Write(textBoxEnviar.Text);
}
private delegate void RefreshTextBox();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(TrataDadoRecebido));
}
private void TrataDadoRecebido(object sender, EventArgs e)
{
textBoxReceber.AppendText(RxString);
}
}
}
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I am trying to get read data from rs 485 communication interface and write in the textbox but i am not getting the data from this code. I am working on water measurement and I am beginner in c#. I have seen similar question like this but unable to get the answer. The data format is like this. D014802,+000.042,+000.082,003680,+000805.66,+025.25,0193FA,0.99697,0000,B7C9
Help me out .
public partial class MainForm : Form
{
SerialPort aSerialPort;
InputRegister mobjGlobalform2;
Form3 mobjGlobalform3;
LoginForm AdminLogin = new LoginForm();
//Form6 softwareVersion = new Form6();
bool isUserMode = true;
public MainForm()
{
InitializeComponent();
getAvailablePorts();
}
private void btn_close_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
InputRegister mobjform2 = new InputRegister();
if (checkBox1.Checked)
{
mobjGlobalform2 = mobjform2;
mobjform2.Show();
if(isUserMode==true)
{
mobjform2.groupbox_form2Takuwa.Hide();
mobjform2.Height = 215;
mobjform2.Width = 575;
}
}
else
{
mobjGlobalform2.Close();
//mobjform2.Close();
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
Form3 mobjform3 = new Form3();
if (checkBox2.Checked)
{
mobjGlobalform3 = mobjform3;
mobjform3.Show();
if(isUserMode==true)
{
mobjform3.groupbx_form3takuwamode.Hide();
mobjform3.Height = 254;
mobjform3.Width = 407;
}
}
else
{
mobjGlobalform3.Close();
//mobjform2.Close();
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
label13.Text = DateTime.Now.ToString();
// splitContainer1.Panel2.Controls.Add(label13);
if(AdminLogin.isAdminMode)
{
lbl_AdminLogout.Show();
isUserMode = false;
}
}
private void btn_Clear_Click(object sender, EventArgs e)
{
txtbox_ShowData.Text = String.Empty; // clear the data from text box
}
private void MenuStrip_AdminLogin_Click(object sender, EventArgs e)
{
//Form5 mobjform5 = new Form5();
AdminLogin.Show();
}
private void lbl_AdminLogout_Click(object sender, EventArgs e)
{
AdminLogin.isAdminMode = false;
isUserMode = true;
lbl_AdminLogout.Hide();
MessageBox.Show("Logout Successful");
}
private void btn_SoftwareVersion_Click(object sender, EventArgs e)
{
//softwareVersion.Show();
Form6 Versionform6 = new Form6();
Versionform6.Height = 272;
Versionform6.Width = 507;
Versionform6.Show();
}
private void btn_connectaddress_Click(object sender, EventArgs e)
{
Setting addressconnectform6 = new Setting();
addressconnectform6.Show();
if(isUserMode == true)
{
addressconnectform6.groupbx_takuwaform7.Hide();
addressconnectform6.Height = 257;
addressconnectform6.Width = 657;
}
else
{
addressconnectform6.groupbx_takuwaform7.Show();
}
}
#region combox
// port show in combobox
private void getAvailablePorts()
{
string[] ports = SerialPort.GetPortNames();
cbbx_comport.Items.Clear();
foreach (string comport in ports)
{
cbbx_comport.Items.Add(comport);
}
}
#endregion
private void btn_Connect_Click(object sender, EventArgs e)
{
initializeSensor();
aSerialPort.DataReceived += new SerialDataReceivedEventHandler(Rs485DataReceivedEventHandler);
}
private void Rs485DataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
this.Invoke((MethodInvoker)delegate { DataReceived(recvData); });
}
private void initializeSensor()
{
aSerialPort = new SerialPort(cbbx_comport.Text);
aSerialPort.BaudRate = 38400;
aSerialPort.Parity = Parity.None;
aSerialPort.StopBits = StopBits.One;
aSerialPort.DataBits = 8;
if (aSerialPort.IsOpen == false)
{
try
{
aSerialPort.Open();
//aSerialPort.WriteLine("c"); //clear
//aSerialPort.WriteLine("o");
}
catch { }
}
}
private void DataReceived(string recvData)
{
txtbx_sensorData.Text = recvData;
}
You are instantiating a local variable, not the field.
Instead of
SerialPort aSerialPort = new SerialPort(cbbx_comport.Text);
Try
aSerialPort = new SerialPort(cbbx_comport.Text);
I have code that takes data from serial com port from a weighing machine. It works okay, but receives data in several lines. I'm trying to make it receive data in one line.
In the code below I need to take weight from weigh bridge machine automatically by timer using Visual Studio 2005. It works, but I receive weight values on several lines.
I need to receive weight in one line and automatically update and convert it to an integer.
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace CommSample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void Application_Idle(object sender, EventArgs e)
{
label3.Text = serialPort1.IsOpen ? "[Open]" : "[Closed]";
}
private void button1_Click(object sender, EventArgs e)
{
if (pollingCheckbox.Checked)
{
timer1.Enabled = true;
}
else
{
timer1.Enabled = false;
TransmitCommand();
}
}
private void TransmitCommand()
{
if (textBox1.Text.Length > 0)
{
if (serialPort1.IsOpen)
{
serialPort1.Write(textBox1.Text + "\r");
}
}
}
private void ClosePort()
{
if (serialPort1.IsOpen)
{
serialPort1.DataReceived -= new SerialDataReceivedEventHandler(serialPort1_DataReceived);
serialPort1.Close();
}
}
private void closePortToolStripMenuItem_Click(object sender, EventArgs e)
{
ClosePort();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = Properties.Settings.Default.Port;
serialPort1.BaudRate = Properties.Settings.Default.Baud;
serialPort1.DataBits = Properties.Settings.Default.DataBits;
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), Properties.Settings.Default.Parity);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Properties.Settings.Default.StopBits);
Application.Idle += new EventHandler(Application_Idle);
}
private void OpenPort()
{
serialPort1.Open();
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
private void openPortToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenPort();
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
ClosePort();
using (Form2 form = new Form2())
{
if (form.ShowDialog(this) == DialogResult.OK)
{
serialPort1.PortName = Properties.Settings.Default.Port;
serialPort1.BaudRate = Properties.Settings.Default.Baud;
serialPort1.DataBits = Properties.Settings.Default.DataBits;
serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), Properties.Settings.Default.Parity);
serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Properties.Settings.Default.StopBits);
}
}
}
void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!InvokeRequired)
{
if (e.EventType == SerialData.Chars)
{
string portData = serialPort1.ReadExisting();
textBox2.AppendText(portData);
}
}
else
{
SerialDataReceivedEventHandler invoker = new SerialDataReceivedEventHandler(serialPort1_DataReceived);
BeginInvoke(invoker, new object[] { sender, e });
}
}
private void pollingCheckbox_CheckedChanged(object sender, EventArgs e)
{
if (timer1.Enabled && !pollingCheckbox.Checked)
{
timer1.Enabled = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (pollingCheckbox.Checked)
{
TransmitCommand();
}
}
}
}
I'm trying to make a simple application to test the RS422 communications with another computer. Using the RS232 interfaces this program is working smoothly, but with the RS422 is not working, as there is one computer that can't send. To complex the scenario a little bit more, I can communicate through RS422 using a HyperTerminal.
Here is the code:
public partial class MainForm : Form
{
private SerialPort m_port;
public MainForm()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames());
m_port = new SerialPort();
m_port.BaudRate = 9600;
m_port.DataBits = 8;
m_port.Parity = Parity.None;
m_port.StopBits = StopBits.One;
m_port.Handshake = Handshake.None;
m_port.Encoding = new ASCIIEncoding();
m_port.ReceivedBytesThreshold = 1;
m_port.DataReceived += DataReceivedEvent;
}
~MainForm()
{
if (m_port != null)
m_port.Close();
}
private void openClick(object sender, EventArgs e)
{
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_buttonSend.Enabled = true;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void ButtonSendClick(object sender, EventArgs e)
{
m_port.WriteLine(m_testBox.Text);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
m_receivedText.Text += m_port.ReadLine();
}
}
Any help or experience with this technology is appreciated. Thanks!
EDIT
There is a lot of differences between the trace with Portmon of Hyperterminal and the .NET component. There is one of the lines that got my attention as it reefers to the wait mask of the port interruption IOCTL_SERIAL_SET_WAIT_MASK.
With HyperTerminal:
IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask: RLSD ERR
With the .NET SerialPort component
IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask: RXCHAR RXFLAG CTS DSR RLSD BRK ERR RING
Anybody knows how to change the mask from the component? This is getting deep...
Finally there was a problem in the initialitation and another one with the blocking ReadLine call. RTS and DTS must be enabled.
Here is the code
using System;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
namespace ComPlay
{
public partial class MainForm : Form
{
private SerialPort m_port;
private byte [] m_buffer = new byte[10];
public MainForm()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames());
m_list.SelectedIndex = 0;
m_port = new SerialPort(SerialPort.GetPortNames()[0],9600,Parity.None,8,StopBits.One);
m_port.Handshake = Handshake.None;
m_port.RtsEnable = true;
m_port.DtrEnable = true;
m_port.DataReceived += DataReceivedEvent;
m_port.PinChanged += PinChangedEvent;
}
~MainForm()
{
if (m_port != null)
m_port.Close();
}
private void openClick(object sender, EventArgs e)
{
if (m_port.IsOpen)
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_buttonSend.Enabled = true;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void ButtonSendClick(object sender, EventArgs e)
{
byte [] r_bytes = Encoding.ASCII.GetBytes(m_testBox.Text);
m_port.Write(r_bytes,0,r_bytes.Length);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
m_port.Read(m_buffer, 0, m_buffer.Length);
m_receivedText.Text += Encoding.ASCII.GetString(m_buffer);
}
private void PinChangedEvent(object sender, SerialPinChangedEventArgs args)
{
}
}
}
The important thing to begin transmitting was to change this
IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:80000000 Replace:80000040 XonLimit:1024 XoffLimit:1024
to this
IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:80000001 Replace:80000040 XonLimit:1024 XoffLimit:1024
activating RTS and DTR.