Using one SerialPort instance without statics
up vote
0
down vote
favorite
To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.
In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.
Please tell me if this is a good way to go about this. Also let me know what my bad habits are.
public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;
}
//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}
//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}
public string formatedData;
public string comment = "///This is a defaul (no) comment";
public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}
//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }
//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;
return formatedData;
}
}
public class convertAndSendData : theSerialUsed
{
//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{
//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);
//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();
try
{
portSetup.Open();
//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);
////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);
//Send user data with cntl-z command
portSetup.Write(result + "u001a");
//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}
c# serial-port
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
up vote
0
down vote
favorite
To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.
In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.
Please tell me if this is a good way to go about this. Also let me know what my bad habits are.
public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;
}
//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}
//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}
public string formatedData;
public string comment = "///This is a defaul (no) comment";
public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}
//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }
//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;
return formatedData;
}
}
public class convertAndSendData : theSerialUsed
{
//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{
//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);
//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();
try
{
portSetup.Open();
//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);
////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);
//Send user data with cntl-z command
portSetup.Write(result + "u001a");
//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}
c# serial-port
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
IMO the inheriting doesn't buy you anything. If you create another instance ofconvertAndSendDataa newSerialPortinstance will be created. But maybe I don't get what you want.
– Heslacher
Nov 22 at 16:35
Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25
Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.
In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.
Please tell me if this is a good way to go about this. Also let me know what my bad habits are.
public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;
}
//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}
//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}
public string formatedData;
public string comment = "///This is a defaul (no) comment";
public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}
//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }
//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;
return formatedData;
}
}
public class convertAndSendData : theSerialUsed
{
//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{
//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);
//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();
try
{
portSetup.Open();
//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);
////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);
//Send user data with cntl-z command
portSetup.Write(result + "u001a");
//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}
c# serial-port
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
To avoid making SerialPort static, my code is using inheritance to make sure the same SerialPort instance is being used.
In the application, only one COM port is to be used with the code. The first class i declare a new instance of serial port in the constructor. The second class, inherited from the first, doesn't need to create a new instance as it's base class has already been initialized once.
Please tell me if this is a good way to go about this. Also let me know what my bad habits are.
public class theSerialUsed
{
public SerialPort portSetup;
public theSerialUsed()
{
portSetup = new SerialPort(Global.COMPort, Int32.Parse(Global.baudRate), 0, 8);
portSetup.Encoding = System.Text.Encoding.UTF8;
}
//Check packet size of user data
public int checkdataSize(string r)
{
int result;
if (r.Length % 2 != 0)
{
result = (8 * r.Length / 2) + 4;
}
else { result = 8 * r.Length / 2; }
return result;
}
//Convert user data to hex val
public string ToHex(string input)
{
StringBuilder sb = new StringBuilder();
foreach (char c in input)
sb.AppendFormat("{0:X2}", (int)c);
return sb.ToString().Trim();
}
public string formatedData;
public string comment = "///This is a defaul (no) comment";
public string returnUserdataWithPrefix(string userData, string comment)
{
string FormattedCellCount = Global.SelectedCell.ToString();
if (comment != "")
{
this.comment = comment;
}
//Add the right abount of leading zeros to cells bwefore sending
if (Global.SelectedCell < 100 && Global.SelectedCell > 10)
{
FormattedCellCount = '0' + FormattedCellCount;
}
else if (Global.SelectedCell < 10) { FormattedCellCount = "00" + FormattedCellCount; }
//build final user datastring
formatedData = "css" + Global.SelectedWing.ToString() + FormattedCellCount + userData + this.comment + ';' + Global.SelectedUserID;
return formatedData;
}
}
public class convertAndSendData : theSerialUsed
{
//Send complete message to Serial Port
public void sendCollectedDataToPort(string userData, string comment)
{
//add prefix and surfix to userdata
userData = returnUserdataWithPrefix(userData, comment);
//Translate userdata into message into HEX>> Prefix PID and language type to msg
string result = "8204FF01" + ToHex(userData);
//Set Check sum from size of userdata
string packsize = checkdataSize(result).ToString();
try
{
portSetup.Open();
//send SDS-TL header
portSetup.Write("AT+CTSDS=12,0,0,0,0" + "rn");
Thread.Sleep(500);
////send receiver number and size of user data
portSetup.Write("AT+CMGS=" + Global.fepDestination + "," + packsize + "rn");
Thread.Sleep(500);
//Send user data with cntl-z command
portSetup.Write(result + "u001a");
//check response from radio
if (portSetup.ReadExisting().Contains("+CME ERROR:1") == false )
{
MessageBox.Show("Message Sent");
}
else
{
MessageBox.Show("Message Failed to send");
}
portSetup.Close();
}
catch (Exception ex)
{
if (ex is System.IO.IOException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": Is not connected to anything");
}
else if (ex is System.UnauthorizedAccessException)
{
MessageBox.Show("Failed to send rn" + Global.COMPort + ": is already in use");
}
else
{
throw;
}
}
}
}
c# serial-port
c# serial-port
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited Nov 22 at 20:43
200_success
127k15148411
127k15148411
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked Nov 22 at 16:24
Mrparkin
11
11
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Mrparkin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
IMO the inheriting doesn't buy you anything. If you create another instance ofconvertAndSendDataa newSerialPortinstance will be created. But maybe I don't get what you want.
– Heslacher
Nov 22 at 16:35
Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25
Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27
add a comment |
3
IMO the inheriting doesn't buy you anything. If you create another instance ofconvertAndSendDataa newSerialPortinstance will be created. But maybe I don't get what you want.
– Heslacher
Nov 22 at 16:35
Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25
Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27
3
3
IMO the inheriting doesn't buy you anything. If you create another instance of
convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.– Heslacher
Nov 22 at 16:35
IMO the inheriting doesn't buy you anything. If you create another instance of
convertAndSendData a new SerialPort instance will be created. But maybe I don't get what you want.– Heslacher
Nov 22 at 16:35
Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25
Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25
Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27
Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Mrparkin is a new contributor. Be nice, and check out our Code of Conduct.
Mrparkin is a new contributor. Be nice, and check out our Code of Conduct.
Mrparkin is a new contributor. Be nice, and check out our Code of Conduct.
Mrparkin is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208238%2fusing-one-serialport-instance-without-statics%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
IMO the inheriting doesn't buy you anything. If you create another instance of
convertAndSendDataa newSerialPortinstance will be created. But maybe I don't get what you want.– Heslacher
Nov 22 at 16:35
Create a single serial port and inject that into dependents
– Nkosi
Nov 22 at 22:25
Or create a wrapper/abstraction of the port, only exposing the needed functionality (to avoid unwanted behavior by dependents) and inject that into dependents
– Nkosi
Nov 22 at 22:27