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
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
3
IMO the inheriting doesn't buy you anything. If you create another instance ofconvertAndSendData
a newSerialPort
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
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
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
edited Nov 22 at 20:43
200_success
127k15148412
127k15148412
asked Nov 22 at 16:24
Mrparkin
11
11
3
IMO the inheriting doesn't buy you anything. If you create another instance ofconvertAndSendData
a newSerialPort
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
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 ofconvertAndSendData
a newSerialPort
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
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
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
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
convertAndSendData
a newSerialPort
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
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